diff --git a/CODEOWNERS b/CODEOWNERS index b67f9238f88620dfb6e7d7e94208300ca6778b69..4f7ab1dad900229e988205402075da217e03f536 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -155,10 +155,10 @@ zh-cn/application-dev/media/avsession-guidelines.md @zengyawen @liuyuehua1 @saga zh-cn/application-dev/media/image.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/media/camera.md @zengyawen @liuyuehua1 @saga2020 @currydavids zh-cn/application-dev/media/remote-camera.md @zengyawen @liuyuehua1 @saga2020 @currydavids -zh-cn/application-dev/security/accesstoken-overview.md @zengyawen @nianCode @nianCode @jinhaihw -zh-cn/application-dev/security/accesstoken-guidelines.md @zengyawen @nianCode @nianCode @jinhaihw -zh-cn/application-dev/security/permission-verify-guidelines.md @zengyawen @nianCode @nianCode @jinhaihw -zh-cn/application-dev/security/permission-list.md @zengyawen @zengyawen @nianCode @nianCode @jinhaihw +zh-cn/application-dev/security/accesstoken-overview.md @zengyawen @nianCode @shuqinglin2 @jinhaihw +zh-cn/application-dev/security/accesstoken-guidelines.md @zengyawen @nianCode @shuqinglin2 @jinhaihw +zh-cn/application-dev/security/permission-verify-guidelines.md @zengyawen @nianCode @shuqinglin2 @jinhaihw +zh-cn/application-dev/security/permission-list.md @zengyawen @shuqinglin2 zh-cn/application-dev/security/userauth-overview.md @zengyawen @gaoyong @niejiteng @jumozhanjiang zh-cn/application-dev/security/userauth-guidelines.md @zengyawen @gaoyong @niejiteng @jumozhanjiang zh-cn/application-dev/security/huks-overview.md @zengyawen @gaoyong @niejiteng @jumozhanjiang @@ -280,7 +280,7 @@ zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionCo zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone 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 @tangtiantian2021 @nan-xiansen @iceice1001 +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-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 @@ -334,7 +334,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 -zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids @@ -368,18 +368,18 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zhang-hai-feng @zengyawen zh-cn/application-dev/reference/apis/js-apis-huks.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-i18n.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 zh-cn/application-dev/reference/apis/js-apis-image.md @zhangqiang183 @zengyawen @chenyuheng @zxg-gitee -zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @mayunteng_1 @ningningW @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @mayunteng_1 @ningningW @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputevent.md @mayunteng_1 @ningningW @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @yuanxinying @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @yuanxinying @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputevent.md @yuanxinying @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 -zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-intl.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-keycode.md @mayunteng_1 @ningningW @cococoler @alien0208 -zh-cn/application-dev/reference/apis/js-apis-keyevent.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-keycode.md @yuanxinying @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-keyevent.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone @@ -389,7 +389,7 @@ zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xx zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-missionManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-nfcController.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @cheng_guohong @RayShih @cheng_guohong @quanli125 @@ -400,7 +400,7 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @littlejerry1 @R zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 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 -zh-cn/application-dev/reference/apis/js-apis-pointer.md @mayunteng_1 @ningningW @cococoler @alien0208 +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-privacyManager.md @nianCode @zengyawen @shuqinglin2 @jinhaihw zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone @@ -482,8 +482,8 @@ zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafan zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone -zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 -zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 @@ -521,7 +521,7 @@ zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @Buda-Liu @ningningW @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-cooperate.md @mayunteng_1 @ningningW @cococoler @alien0208 +zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy @@ -543,10 +543,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy -zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 -zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen diff --git a/README.md b/README.md index 602a868e0c5966d52b77eff891a6f32232c7d579..9351f7f58964229343c0dbfc3c9875e212a4a54f 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ This repository stores device and application development documents provided by - master: the latest version. - - OpenHarmony 3.2 Beta3. [Learn more](en/release-notes/OpenHarmony-v3.2-beta3.md) + - OpenHarmony 3.2 Beta5. [Learn more](en/release-notes/OpenHarmony-v3.2-beta5.md) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) @@ -34,7 +34,7 @@ This repository stores device and application development documents provided by ### Historical Stable Versions -OpenHarmony_v1.x_release: OpenHarmony v1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md) +OpenHarmony_v1.x_release: OpenHarmony 1.1.5 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.5-LTS.md) [More versions](en/release-notes/) @@ -51,6 +51,6 @@ You can evaluate available documents, make simple modifications, provide feedbac Excellent contributors will be awarded and the contributions will be publicized in the developer community. -- Mail list: docs@openharmony.io +- Mailing list: docs@openharmony.io - Zulip group: documentation_sig \ No newline at end of file diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md index 5fbc55f9a12d9c774f7a7295d68cb7b2659852cd..594fb355e417b047d93b1de9d413540a2c839190 100644 --- a/en/OpenHarmony-Overview.md +++ b/en/OpenHarmony-Overview.md @@ -183,7 +183,7 @@ For details about how to obtain the source code of OpenHarmony, see [Source Code ## Hands-On Tutorials -[Samples](https://gitee.com/openharmony/app_samples) +[Samples](https://gitee.com/openharmony/applications_app_samples) [Codelabs](https://gitee.com/openharmony/codelabs) diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index b9bc5bb92ed39b292ca4eede0023989364eb473c..650eaf0b956e544bd19e8892b0c6946a6839beb5 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -24,7 +24,7 @@ First thing first, familiarize yourself with the two cornerstone frameworks in O All applications should be developed on top of these frameworks. Then, equip yourself for developing the key features, with the following guidelines: -- [Common Event and Notification](notification/notification-brief.md) +- [Common Event and Notification](notification/notification-overview.md) - [Window Manager](windowmanager/window-overview.md) - [WebGL](webgl/webgl-overview.md) - [Media](media/audio-overview.md) diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 2a920300623358bc25f7256d6af8b957665bc600..efc515db54971c76432f02b5f409990ecbd767b7 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -19,6 +19,7 @@ - [ServiceExtensionAbility](serviceextensionability.md) - [DataShareExtensionAbility](datashareextensionability.md) - [FormExtensionAbility (Widget)](widget-development-stage.md) + - [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md) - [AbilityStage Component Container](abilitystage.md) - [Context](application-context-stage.md) - Want diff --git a/en/application-dev/application-models/accessibilityextensionability.md b/en/application-dev/application-models/accessibilityextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..4c912d5e58a1b8083ba1037cccf449dd953d245c --- /dev/null +++ b/en/application-dev/application-models/accessibilityextensionability.md @@ -0,0 +1,118 @@ +# AccessibilityExtensionAbility Development + +The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the **ExtensionAbility** framework. You can develop your accessibility applications by applying the **AccessibilityExtensionAbility** template to enhance usability. + +> **Environment Requirements** +> +> IDE: DevEco Studio 3.0 Beta3 (3.0.0.900) or later +> +> SDK: API version 9 or later +> +> Model: stage + +This document is organized as follows: + +- [Creating an AccessibilityExtAbility File](#creating-an-accessibility-extension-service) +- [Processing an Accessibility Event](#processing-an-accessibility-event) +- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services) +- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service) + +## Creating an Accessibility Extension Service + +You can create an accessibility extension service by creating a project from scratch or adding the service to an existing project. + +### Creating a Project + +Perform the following steps in DevEco Studio: +1. From the upper left corner of DevEco Studio, choose **File** > **New** > **Create Project**. +2. By following the project creation wizard, click the **OpenHarmony** tab, select the **Empty Ability** template, and then click **Next**. +3. Set **Project type** to **Application**, **Compile API** (or **Compile SDK**, depending on the version used) to **9**, and **Model** to **Stage**, and then click **Finish**. + +### Creating an AccessibilityExtAbility File + +To add an accessibility extension service to a project, create the **AccessibilityExtAbility** folder in the **ets** folder of the project, create the **AccessibilityExtAbility.ts** file in the new folder, and add the following code to the new file: + +```typescript +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'; + +class AccessibilityExtAbility extends AccessibilityExtensionAbility { + onConnect() { + console.log('AccessibilityExtAbility onConnect'); + } + + onDisconnect() { + console.log('AccessibilityExtAbility onDisconnect'); + } + + onAccessibilityEvent(accessibilityEvent) { + console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); + } +} + +export default AccessibilityExtAbility; +``` + +The APIs defined in the file are as follows. + +| API| Description| +| ---- | ---- | +| onConnect(): void | Called when a connection with the extension service is set up.| +| onDisconnect(): void | Called when the connection with the extension service is severed.| +| onAccessibilityEvent(event: AccessibilityEvent): void | Called when an accessibility event occurs| + +## Processing an Accessibility Event + +You can process the service logic for accessibility events in the **onAccessibilityEvent()** API. For details about the events, see [AccessibilityEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityevent). The following code snippet uses the **pageStateUpdate** event as an example. + +```typescript +onAccessibilityEvent(accessibilityEvent) { + console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); + if (accessibilityEvent.eventType === 'pageStateUpdate') { + console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate'); + // TODO: Develop custom logic. + } +} +``` +For an accessibility event, you can use the APIs of the [AccessibilityExtensionContext](../reference/apis/js-apis-inner-application-accessibilityExtensionContext.md) module to configure the concerned information, obtain root information, and inject gestures. + +You can also process physical key events in the accessibility extension service. For details, see [onKeyEvent](../reference/apis/js-apis-application-accessibilityExtensionAbility.md#accessibilityextensionabilityonkeyevent). + +## Declaring Capabilities of Accessibility Extension Services + +After developing the custom logic for an accessibility extension service, you must add the configuration information of the service to the corresponding module-level **module.json5** file in the project directory. In the file, the **srcEntrance** tag indicates the path to the accessibility extension service. Make sure the value of the **type** tag is fixed at **accessibility**. Otherwise, the connection to the service will fail. + +```json +"extensionAbilities": [ + { + "name": "AccessibilityExtAbility", + "srcEntrance": "./ets/AccessibilityExtAbility/AccessibilityExtAbility.ts", + "label": "$string:MainAbility_label", + "description": "$string:MainAbility_desc", + "type": "accessibility", + "metadata": [ + { + "name": "ohos.accessibleability", + "resource": "$profile:accessibility_config" + } + ] + } +] +``` +**accessibility_config** is the specific configuration of the accessibility extension service. You need to create the **accessibility_config.json** file in **resources/base/profile/** and declare the [capabilities](../reference/apis/js-apis-accessibility.md#capability) of the service in the file. +```json +{ + "accessibilityCapabilities": [ + "retrieve", + "gesture" + ] +} +``` +## Enabling a Custom Accessibility Extension Service + +To enable or disable an accessibility extension service, run the following command: +- To enable the service: **accessibility enable -a AccessibilityExtAbility -b com.example.demo -c rg** +- To disable the service: **accessibility disable -a AccessibilityExtAbility -b com.example.demo** + +In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve). + +If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed. diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index 85dfb9523ca117e691480bcbd2321b5fb3b22304..5c5aed302c6f8f570238fac6bd73c263840244d6 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -1,6 +1,6 @@ # Common action and entities Values -The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. +**action**: Action to take, such as viewing, sharing, and application details, by the caller. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ohos.want.action.viewData**, the ability that supports website viewing is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. **Common action Values** @@ -14,7 +14,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. -The [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) field specifies the additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. +**entities**: Category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want. You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. **Common entities Values** diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md index de9e29941b5ddcc9e29f62ddc039fb38b6bc54b6..bcf9b095464ba0110c35be9cfef44b078a091ffb 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -3,7 +3,8 @@ When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. -**Figure 1** Icons and labels + + **Figure 1** Icons and labels ![application-component-configuration-stage](figures/application-component-configuration-stage.png) @@ -14,11 +15,11 @@ When developing an application, you may need to configure certain tags to identi - **Configuring the application icon and label** - The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon. The application icon is usually displayed in an application list, for example, the application list in **Settings**. + You must configure an icon and label for an application on the stage model. - The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. + The application icon is specified by the **icon** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. The **icon** field must be set to the index of an image so that the image is displayed as the application icon. - The **icon** and **label** fields in the **app.json5** file are under **app**, as follows: + The application label is specified by the **label** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** module of the project. The **label** field specifies the application name displayed to users. It must be set to the index of a string resource. ```json { @@ -32,7 +33,9 @@ When developing an application, you may need to configure certain tags to identi - **Configuring the entry icon and label** - The entry icon and label are configured by specifying **icon** and **label** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon and label of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **action.system.home** to **actions** under **skills**. If the preceding fields are configured for multiple UIAbility components of an application, multiple icons and labels are displayed on the home screen, corresponding to their respective UIAbility component. + On the stage model, you can configure an entry icon and label for each application component. The entry icon and label are displayed on the home screen. + + The entry icon is configured by specifying **icon** under **abilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For example, if you want to display the icon of the UIAbility component on the home screen, add **entity.system.home** to **entities** and **ohos.want.action.home** to **actions** under **skills**. If this field is configured for multiple UIAbility components of an application, multiple icons are displayed on the home screen, corresponding to their respective UIAbility component. ```json { @@ -49,7 +52,7 @@ When developing an application, you may need to configure certain tags to identi "entity.system.home" ], "actions": [ - "action.system.home" + "ohos.want.action.home" ] } ], @@ -69,4 +72,3 @@ When developing an application, you may need to configure certain tags to identi - **Configuring the module permission** The **requestPermission** field in the [module.json5 file](../quick-start/module-configuration-file.md) is used to configure the permission information required by the module to access the protected part of the system or other applications. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. - diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index 4bb36b6640f4dc8f376bd6fabde58cc3e20b6aff..de07a3600a27b619f144a4f22223e17616f80805 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -10,11 +10,11 @@ ![context-inheritance](figures/context-inheritance.png) - The figure below illustrates the holding relationship of contexts. - + ![context-holding](figures/context-holding.png) - The following describes the information provided by different contexts. - - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more. + - [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -25,6 +25,10 @@ } } ``` + + > **NOTE** + > + > For details about how to obtain the context of a **UIAbility** instance on the page, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services. ```ts @@ -47,7 +51,7 @@ } } ``` - - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to ability lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage. + - [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md): application-level context. It provides APIs for subscribing to application component lifecycle changes, system memory changes, and system environment changes. The application-level context can be obtained from UIAbility, ExtensionAbility, and AbilityStage. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -179,13 +183,10 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] > To obtain the context of another application: > > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - > - > - This is a system API and cannot be called by third-party applications. - > > - This is a system API and cannot be called by third-party applications. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. - + ```ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -198,7 +199,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] } } ``` - - Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module. > **NOTE** @@ -206,9 +206,6 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] > To obtain the context of a specified module of another application: > > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - > - > - This is a system API and cannot be called by third-party applications. - > > - This is a system API and cannot be called by third-party applications. ```ts @@ -223,7 +220,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] } } ``` - + - Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module. ```ts diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md index 3e68e8ed857988dd21b7ca1ff5334de5990adea8..16854efb9236dc6bdc9fbe990c9cbe3581495633 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -50,7 +50,7 @@ The system matches the **want** parameter (including the **action**, **entities* ### Matching Rules of action in the want Parameter -The system matches the [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. +The system matches the **action** attribute in the **want** parameter passed by the caller against **actions** under **skills** of the abilities. - If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. @@ -62,12 +62,12 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m **Figure 1** Matching rules of action in the want parameter - ![want-action](figures/want-action.png) + ![want-action](figures/want-action.png) ### Matching Rules of entities in the want Parameter -The system matches the [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. +The system matches the **entities** attribute in the **want** parameter passed by the caller against **entities** under **skills** of the abilities. - If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. @@ -117,7 +117,7 @@ To simplify the description, **uri** and **type** passed in the **want** paramet Figure 4 Matching rules of uri and type in the want parameter -![want-uri-type2](figures/want-uri-type2.png) +![want-uri-type2](figures/want-uri-type2.png) ### Matching Rules of uri 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 3a6fa2646a37785d41793407d4803d60743342dd..fe22c3b33db46b5a353295582a5cc6a27f690d20 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -93,7 +93,7 @@ On device A, touch the **Start** button provided by the initiator application to } ``` -4. Set the target component parameters, and call **startAbility()** to start UIAbility or ServiceExtensionAbility. +4. Set the target component parameters, and call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility or ServiceExtensionAbility. ```ts let want = { @@ -382,68 +382,68 @@ The following describes how to implement multi-device collaboration through cros ```ts export default class MySequenceable { - num: number = 0 - str: string = "" + num: number = 0; + str: string = ""; constructor(num, string) { - this.num = num - this.str = string + this.num = num; + this.str = string; } marshalling(messageParcel) { - messageParcel.writeInt(this.num) - messageParcel.writeString(this.str) - return true + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; } unmarshalling(messageParcel) { - this.num = messageParcel.readInt() - this.str = messageParcel.readString() - return true + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; } } ``` 4. Implement **Callee.on** and **Callee.off**. - In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. - - ```ts - const TAG: string = '[CalleeAbility]' - const MSG_SEND_METHOD: string = 'CallSendMsg' - - function sendMsgCallback(data) { - console.info('CalleeSortFunc called') - - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, '') - data.readSequenceable(receivedData) - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) - - // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) - } - - export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback) - } catch (error) { - console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) - } - } - - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD) - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) - } - } - } - ``` - + In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. + + ```ts + const TAG: string = '[CalleeAbility]'; + const MSG_SEND_METHOD: string = 'CallSendMsg'; + + function sendMsgCallback(data) { + console.info('CalleeSortFunc called'); + + // Obtain the sequenceable data sent by the caller ability. + let receivedData = new MySequenceable(0, ''); + data.readSequenceable(receivedData); + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); + + // Process the data. + // Return the sequenceable data result to the caller ability. + return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); + } + + export default class CalleeAbility extends Ability { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback); + } catch (error) { + console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); + } + } + + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD); + } catch (error) { + console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); + } + } + } + ``` + 4. Obtain the caller object and access the callee ability. 1. Import the **UIAbility** module. @@ -458,8 +458,8 @@ The following describes how to implement multi-device collaboration through cros ```ts async onButtonGetRemoteCaller() { - var caller = undefined - var context = this.context + var caller = undefined; + var context = this.context; context.startAbilityByCall({ deviceId: getRemoteDeviceId(), @@ -467,16 +467,16 @@ The following describes how to implement multi-device collaboration through cros abilityName: 'CalleeAbility' }).then((data) => { if (data != null) { - caller = data - console.info('get remote caller success') + caller = data; + console.info('get remote caller success'); // Register the onRelease() listener of the caller ability. caller.onRelease((msg) => { - console.info(`remote caller onRelease is called ${msg}`) + console.info(`remote caller onRelease is called ${msg}`); }) - console.info('remote caller register OnRelease succeed') + console.info('remote caller register OnRelease succeed'); } }).catch((error) => { - console.error(`get remote caller failed with ${error}`) + console.error(`get remote caller failed with ${error}`); }) } ``` diff --git a/en/application-dev/application-models/mission-management-launch-type.md b/en/application-dev/application-models/mission-management-launch-type.md index 72b6dbf80df2628119ebcc29339ed7e4b70e9a50..267ed5011fe28cdc576e6caca85a526450110867 100644 --- a/en/application-dev/application-models/mission-management-launch-type.md +++ b/en/application-dev/application-models/mission-management-launch-type.md @@ -10,7 +10,7 @@ The following describes how the mission list manager manages the UIAbility insta **Figure 1** Missions and singleton mode ![mission-and-singleton](figures/mission-and-singleton.png) -- **standard**: Each time **startAbility()** is called, a UIAbility instance is created in the application process. +- **standard**: Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a **UIAbility** instance is created in the application process. **Figure 2** Missions and standard mode ![mission-and-standard](figures/mission-and-standard.png) @@ -30,4 +30,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility > **NOTE** > > The **specified** mode is supported in the stage model only. - diff --git a/en/application-dev/application-models/mission-management-overview.md b/en/application-dev/application-models/mission-management-overview.md index b6f6668f7ce56a9de0b5a3d0182b14ec189703c9..3346e8105deef0dce6dc785b7e88b10e2a4ce3e1 100644 --- a/en/application-dev/application-models/mission-management-overview.md +++ b/en/application-dev/application-models/mission-management-overview.md @@ -28,7 +28,7 @@ Missions are managed by system applications (such as home screen), rather than t - Switch a mission to the foreground. -A UIAbility instance corresponds to an independent mission. Therefore, when an application calls the **startAbility()** method to start a UIAbility, a mission is created. +A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created. To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). @@ -36,6 +36,8 @@ To call [missionManager](../reference/apis/js-apis-application-missionManager.md You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows: + + ```ts import missionManager from '@ohos.app.ability.missionManager' diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index c4ffdbd980fff4ce568115f92af884da06739ad2..d64d884b1e3021193f63445913886830218df6e1 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -1,5 +1,6 @@ # ServiceExtensionAbility + [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) is an ExtensionAbility component of the service type that provides extension capabilities related to background services. @@ -40,28 +41,24 @@ This feature applies only to system applications. [ServiceExtensionAbility](../r ![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) - **onCreate** - -This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. + This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. > **NOTE** -> + > > If a service has been created, starting it again does not trigger the **onCreate()** callback. - **onRequest** - -This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background. + This callback is triggered when another component calls the **startServiceExtensionAbility()** method to start the service. After being started, the service runs in the background. - **onConnect** - -This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC. + This callback is triggered when another component calls the **connectServiceExtensionAbility()** method to connect to the service. In this method, a remote proxy object (IRemoteObject) is returned, through which the client communicates with the server by means of RPC. - **onDisconnect** - -This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service. + This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service. - **onDestroy** diff --git a/en/application-dev/application-models/start-serviceability.md b/en/application-dev/application-models/start-serviceability.md index f3b0f6aeabc8a3ea35c1f6c390ec53239730443c..e07428f13a5ce3a3981b7881387dc8498f1380d1 100644 --- a/en/application-dev/application-models/start-serviceability.md +++ b/en/application-dev/application-models/start-serviceability.md @@ -27,7 +27,7 @@ async function startServiceAbility() { ``` -In the preceding code, **startAbility()** is used to start the ServiceAbility. +In the preceding code, [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is used to start the ServiceAbility. - If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility. diff --git a/en/application-dev/application-models/static-subscriber-extension-ability.md b/en/application-dev/application-models/static-subscriber-extension-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..ae6d9a80b7ab6c693d06e7bfe8bfb11b4db94ab8 --- /dev/null +++ b/en/application-dev/application-models/static-subscriber-extension-ability.md @@ -0,0 +1,107 @@ +# StaticSubscriberExtensionAbility Development + +## Scenario Description + +​The common event service provides two subscription modes: dynamic and static. In dynamic subscription mode, a subscriber calls an API during the running period to subscribe to common events. For details, see [Subscribing to Common Events](common-event-subscription.md). In static subscription mode, no common event subscription API is called. A common event is subscribed by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. A static subscriber is started once it receives a target event (for example, a power-on event) published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. **The static subscriber APIs are system APIs and can be used only by system applications that have passed the system-level power consumption review.** + + + +## How to Develop + +1. Prerequisites + + The application must meet the following requirements: + + The application is a system application. + + The application is developed using the full SDK. + + The application's power consumption has passed the system-level power consumption review. If you want to use static subscription in the debugging phase, add the bundle name of your application to the system configuration file **/etc/static_subscriber_config.json**. + + + +2. Declaring a Static Subscriber + + To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows: + + ```ts + import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' + + export default class StaticSubscriber extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log('onReceiveEvent, event:' + event.event); + } + } + ``` + + You can implement service logic in the **onReceiveEvent** callback. + + + +3. Project Configuration for a Static Subscriber + + After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows: + + ```ts + { + "module": { + ...... + "extensionAbilities": [ + { + "name": "StaticSubscriber", + "srcEntrance": "./ets/StaticSubscriber/StaticSubscriber.ts", + "description": "$string:StaticSubscriber_desc", + "icon": "$media:icon", + "label": "$string:StaticSubscriber_label", + "type": "staticSubscriber", + "visible": true, + "metadata": [ + { + "name": "ohos.extension.staticSubscriber", + "resource": "$profile:subscribe" + } + ] + } + ] + ...... + } + } + ``` + + Pay attention to the following fields in the JSON file: + + **srcEntrance**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2. + + **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**. + + **metadata**: level-2 configuration file information of the ExtensionAbility. The configuration information varies according to the ExtensionAbility type. Therefore, you must use different config files to indicate the specific configuration. The **metadata** field contains two keywords: **name** and **resource**. The **name** field indicates the ExtensionAbility type name. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. The **resource** field indicates the path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**. + + A level-2 configuration file pointed to by **metadata** must be in the following format: + + ```ts + { + "commonEvents": [ + { + "name": "xxx", + "permission": "xxx", + "events":[ + "xxx" + ] + } + ] + } + ``` + + If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows: + + **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**. + + **permission**: permission required by the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. + + **events**: list of subscribed target events + + + +## Samples + +For details about how to develop StaticSubscriberExtensionAbility, see [StaticSubscriber (ArkTS, API version 9, Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StaticSubscriber). diff --git a/en/application-dev/application-models/uiability-data-sync-with-ui.md b/en/application-dev/application-models/uiability-data-sync-with-ui.md index c0cabf26d08b00a53c9fe20779e4063c87894e6d..9ed8c8d6f3b307ef44097f1ff67e6dcf472f91a5 100644 --- a/en/application-dev/application-models/uiability-data-sync-with-ui.md +++ b/en/application-dev/application-models/uiability-data-sync-with-ui.md @@ -3,17 +3,16 @@ Based on the OpenHarmony application model, you can use any of the following ways to implement data synchronization between the UIAbility component and UI: -- EventHub: The [base class Context](application-context-stage.md) provides the EventHub capability. It is implemented based on the publish/subscribe (pub/sub) pattern. Your application subscribes to an event and when the event occurs, receives a notification. - -- globalThis: It is a global object accessible in the ArkTS engine instance. -- LocalStorage/AppStorage: See [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md). +- [Using EventHub for Data Synchronization](#using-eventhub-for-data-synchronization): The **EventHub** object is provided by the base class **Context**. Events are transferred using the publish/subscribe (pub/sub) pattern. Specifically, after subscribing to an event, your application will receive the event and process it accordingly when the event is published. +- [Using globalThis for Data Synchronization](#using-globalthis-for-data-synchronization): **globalThis** is a global object inside the ArkTS engine instance and can be accessed by components such as UIAbility, ExtensionAbility, and Page. +- [Using AppStorage or LocalStorage for Data Synchronization](#using-appstorage-or-localstorage-for-data-synchronization): ArkUI provides two application-level state management solutions: AppStorage and LocalStorage, which implement application- and UIAbility-level data synchronization, respectively. ## Using EventHub for Data Synchronization -[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism at the UIAbility or ExtensionAbility component level. Centered on the UIAbility or ExtensionAbility component, EventHub provides data communication capabilities for subscribing to, unsubscribing from, and triggering events. +[EventHub](../reference/apis/js-apis-inner-application-eventHub.md) provides an event mechanism for the UIAbility or ExtensionAbility component so that they can subscribe to, unsubscribe from, and trigger events. -Before using EventHub, you must obtain an EventHub object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. +Before using the APIs provided by **EventHub**, you must obtain an **EventHub** object, which is provided by the [base class Context](application-context-stage.md). This section uses EventHub as an example to describe how to implement data synchronization between the UIAbility component and the UI. 1. Call [eventHub.on()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubon) in the UIAbility in either of the following ways to register a custom event **event1**. @@ -81,17 +80,16 @@ Before using EventHub, you must obtain an EventHub object, which is provided by 4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event. ```ts - // context is the ability context of the UIAbility instance. + // context is the ability-level context of the UIAbility instance. this.context.eventHub.off('event1'); ``` ## Using globalThis for Data Synchronization - **globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization. - **Figure 1** Using globalThis for data synchronization +**Figure 1** Using globalThis for data synchronization ![globalThis1](figures/globalThis1.png) @@ -99,18 +97,18 @@ Before using EventHub, you must obtain an EventHub object, which is provided by The following describes how to use **globalThis** in three scenarios. Precautions are provided as well. - [Using globalThis Between UIAbility and Page](#using-globalthis-between-uiability-and-page) -- [Using globalThis Between UIAbility and UIAbility](##using-globalthis-between-uiability-and-uiability) +- [Using globalThis Between UIAbility and UIAbility](#using-globalthis-between-uiability-and-uiability) - [Use globalThis Between UIAbility and ExtensionAbility](#using-globalthis-between-uiability-and-extensionability) - [Precautions for Using globalThis](#precautions-for-using-globalthis) ### Using globalThis Between UIAbility and Page -You can use **globalThis** to bind attributes or methods to implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. +By binding attributes or methods to **globalThis**, you can implement data synchronization between the UIAbility component and UI. For example, if you bind the **want** parameter in the UIAbility component, you can use the **want** parameter information on the UI corresponding to the UIAbility component. -1. When **startAbility()** is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. +1. When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called to start a UIAbility instance, the **onCreate()** callback is invoked, and the **want** parameter can be passed in the callback. Therefore, you can bind the **want** parameter to **globalThis**. ```ts - import UIAbility from '@ohos.app.ability.UIAbility' + import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { onCreate(want, launch) { @@ -144,29 +142,29 @@ You can use **globalThis** to bind attributes or methods to implement data synch ### Using globalThis Between UIAbility and UIAbility -To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from AbilityB. +To implement data synchronization between two UIAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from UIAbilityB. -1. AbilityA stores a string and binds it to globalThis. +1. UIAbilityA stores a string and binds it to globalThis. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { + export default class UIAbilityA extends UIAbility { onCreate(want, launch) { - globalThis.entryAbilityStr = 'AbilityA'; // AbilityA stores the string "AbilityA" to globalThis. + globalThis.entryAbilityStr = 'UIAbilityA'; // UIAbilityA stores the string "UIAbilityA" to globalThis. // ... } } ``` -2. Obtain the data from AbilityB. +2. Obtain the data from UIAbilityB. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityB extends UIAbility { + export default class UIAbilityB extends UIAbility { onCreate(want, launch) { - // AbilityB reads the name from globalThis and outputs it. + // UIAbilityB reads name from globalThis and outputs it. console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); // ... } @@ -176,17 +174,17 @@ To implement data synchronization between two UIAbility components in the same a ### Using globalThis Between UIAbility and ExtensionAbility -To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in AbilityA and obtain the data from ServiceExtensionAbility. +To implement data synchronization between the UIAbility and ExtensionAbility components in the same application, you can bind data to **globalThis**. For example, you can save data in **globalThis** in UIAbilityA and obtain the data from ServiceExtensionAbility. -1. AbilityA stores a string and binds it to globalThis. +1. UIAbilityA stores a string and binds it to globalThis. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { + export default class UIAbilityA extends UIAbility { onCreate(want, launch) { - // AbilityA stores the string "AbilityA" to globalThis. - globalThis.entryAbilityStr = 'AbilityA'; + // UIAbilityA stores the string "UIAbilityA" to globalThis. + globalThis.entryAbilityStr = 'UIAbilityA'; // ... } } @@ -209,11 +207,11 @@ To implement data synchronization between the UIAbility and ExtensionAbility com ### Precautions for Using globalThis - **Figure 2** Precautions for globalThis +**Figure 2** Precautions for globalThis - ![globalThis2](figures/globalThis2.png) +![globalThis2](figures/globalThis2.png) -- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. +- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if UIAbilityA and UIAbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. - This problem does not occur in the FA model because each UIAbility component uses an independent engine. @@ -221,20 +219,20 @@ To implement data synchronization between the UIAbility and ExtensionAbility com The following provides an example to describe the object overwritten problem in the stage model. -1. In the AbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. +1. In the UIAbilityA file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis**. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { + export default class UIAbilityA extends UIAbility { onCreate(want, launch) { - globalThis.context = this.context; // AbilityA stores the context in globalThis. + globalThis.context = this.context; // UIAbilityA stores the context in globalThis. // ... } } ``` -2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability A. After the AbilityA instance is used, switch it to the background. +2. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityA. After the UIAbilityA instance is used, switch it to the background. ```ts @Entry @@ -254,21 +252,21 @@ The following provides an example to describe the object overwritten problem in } ``` -3. In the AbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the AbilityA file. +3. In the UIAbilityB file, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) is stored in **globalThis** and has the same name as that in the UIAbilityA file. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityB extends UIAbility { + export default class UIAbilityB extends UIAbility { onCreate(want, launch) { - // AbilityB overwrites the context stored by AbilityA in globalThis. + // UIAbilityB overwrites the context stored by UIAbilityA in globalThis. globalThis.context = this.context; // ... } } ``` -4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of Ability B. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in AbilityB. +4. Obtain and use [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) on the page of UIAbilityB. The obtained **globalThis.context** is the value of [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) in UIAbilityB. ```ts @Entry @@ -288,27 +286,27 @@ The following provides an example to describe the object overwritten problem in } ``` -5. Switch the AbilityB instance to the background and switch the AbilityA instance to the foreground. In this case, AbilityA will not enter the **onCreate()** lifecycle again. +5. Switch the UIAbilityB instance to the background and switch the UIAbilityA instance to the foreground. In this case, UIAbilityA will not enter the **onCreate()** lifecycle again. ```ts import UIAbility from '@ohos.app.ability.UIAbility' - export default class AbilityA extends UIAbility { - onCreate(want, launch) { // AbilityA will not enter this lifecycle. + export default class UIAbilityA extends UIAbility { + onCreate(want, launch) { // UIAbilityA will not enter this lifecycle. globalThis.context = this.context; // ... } } ``` -6. When the page of AbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of AbilityB instead of AbilityA. An error occurs. +6. When the page of UIAbilityA is displayed, the obtained **globalThis.context** is [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) of UIAbilityB instead of UIAbilityA. An error occurs. ```ts @Entry @Component struct Index { onPageShow() { - let ctx = globalThis.context; // The context in globalThis is the context of AbilityB. + let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB. let permissions=['com.example.permission']; ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown. console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); @@ -320,3 +318,7 @@ The following provides an example to describe the object overwritten problem in } } ``` + +## Using AppStorage or LocalStorage for Data Synchronization + +ArkUI provides AppStorage and LocalStorage to implement application- and UIAbility-level data synchronization, respectively. Both solutions can be used to manage the application state, enhance application performance, and improve user experience. The AppStorage is a global state manager and is applicable when multiple UIAbilities share the same state data. The LocalStorage is a local state manager that manages state data used inside a single UIAbility. They help you control the application state more flexibly and improve the maintainability and scalability of applications. For details, see [State Management of Application-Level Variables](../quick-start/arkts-state-mgmt-application-level.md). 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 5efbe34173812ad54246c7da17258f9118de1be5..ac3c18e36de67e66e496a92da2269c063503ce7e 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -26,7 +26,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. You are required to start FuncAbility from EntryAbility. -1. In EntryAbility, call **startAbility()** to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting 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; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting 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; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts let wantInfo = { @@ -62,21 +62,27 @@ Assume that your application has two UIAbility components: EntryAbility and Func } ``` -3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. +3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. ```ts - // context is the ability context of the UIAbility instance to stop. + // context is the ability-level context of the UIAbility instance to stop. this.context.terminateSelf((err) => { // ... }); ``` + + > **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) to stop all processes of the application. ## Starting UIAbility in the Same Application and Obtaining the Return Result When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility. -1. In EntryAbility, call **startAbilityForResult()** 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, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-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, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts let wantInfo = { @@ -96,7 +102,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned }) ``` -2. Call **terminateSelfWithResult()** to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. +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 const RESULT_CODE: number = 1001; @@ -111,13 +117,13 @@ When starting FuncAbility from EntryAbility, you want the result to be returned }, }, } - // context is the ability context of the callee UIAbility. + // context is the ability-level context of the callee UIAbility. this.context.terminateSelfWithResult(abilityResult, (err) => { // ... }); ``` -3. After FuncAbility stops itself, EntryAbility uses the **startAbilityForResult()** method to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. +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 the preceding value. ```ts const RESULT_CODE: number = 1001; @@ -145,11 +151,11 @@ There are two ways to start **UIAbility**: [explicit and implicit](want-overview - Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter. -- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When the **startAbility()** method is called, the **want** parameter specifies a series of parameters such as [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction). **entities** provides additional type information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. +- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the want parameter specifies a series of parameters such as **entities** and **actions**. **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application. This section 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 of each UIAbility component, configure [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. +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 { @@ -196,13 +202,13 @@ This section describes how to start the UIAbility of another application through ``` The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. - + ![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png) -3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. +3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). ```ts - // context is the ability context of the UIAbility instance to stop. + // context is the ability-level context of the UIAbility instance to stop. this.context.terminateSelf((err) => { // ... }); @@ -211,9 +217,9 @@ This section describes how to start the UIAbility of another application through ## Starting UIAbility of Another Application and Obtaining the Return Result -If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use the **startAbilityForResult()** method. An example scenario is that the main application needs to start a third-party payment application and obtain the payment result. +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 the main application needs to start a third-party payment application and obtain the payment result. -1. In the **module.json5** file of the UIAbility corresponding to the payment application, set [entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity) and [actions](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction) under **skills**. +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 { @@ -239,7 +245,7 @@ If you want to obtain the return result when using implicit Want to start the UI } ``` -2. Call the **startAbilityForResult()** method to start the UIAbility of the payment application. Include **entities** and **actions** of the caller'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 caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. +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 caller'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 caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. ```ts let wantInfo = { @@ -259,7 +265,7 @@ If you want to obtain the return result when using implicit Want to start the UI }) ``` -3. After the payment is finished, call the **terminateSelfWithResult()** method to stop the payment UIAbility and return the **abilityResult** parameter. +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 const RESULT_CODE: number = 1001; @@ -274,13 +280,13 @@ If you want to obtain the return result when using implicit Want to start the UI }, }, } - // context is the ability context of the callee UIAbility. + // context is the ability-level context of the callee UIAbility. this.context.terminateSelfWithResult(abilityResult, (err) => { // ... }); ``` -4. Receive the information returned by the payment application in the callback of the **startAbilityForResult()** method. The value of **RESULT_CODE** must be the same as that returned by **terminateSelfWithResult()**. +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 const RESULT_CODE: number = 1001; @@ -443,7 +449,7 @@ Ability call is usually used in the following scenarios: The following figure shows the ability call process. -**Figure 1** Ability call process +Figure 1 Ability call process ![call](figures/call.png) @@ -490,24 +496,23 @@ For the callee ability, implement the callback to receive data and the methods t Set **launchType** of the callee ability to **singleton** in the **module.json5** file. -| JSON Field| Description| -| -------- | -------- | -| "launchType" | Ability launch type. Set this parameter to **singleton**.| + | JSON Field| Description| + | -------- | -------- | + | "launchType" | Ability launch type. Set this parameter to **singleton**.| -An example of the ability configuration is as follows: + An example of the ability configuration is as follows: - - ```json - "abilities":[{ - "name": ".CalleeAbility", - "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", - "launchType": "singleton", - "description": "$string:CalleeAbility_desc", - "icon": "$media:icon", - "label": "$string:CalleeAbility_label", - "visible": true - }] - ``` + ```json + "abilities":[{ + "name": ".CalleeAbility", + "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts", + "launchType": "singleton", + "description": "$string:CalleeAbility_desc", + "icon": "$media:icon", + "label": "$string:CalleeAbility_label", + "visible": true + }] + ``` 2. Import the **UIAbility** module. @@ -519,7 +524,6 @@ An example of the ability configuration is as follows: The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. - ```ts export default class MySequenceable { num: number = 0 @@ -548,7 +552,6 @@ An example of the ability configuration is as follows: The time to register a listener for the callee ability 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 ability and deregistered in **onDestroy**. After receiving sequenceable 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: - ```ts const TAG: string = '[CalleeAbility]'; const MSG_SEND_METHOD: string = 'CallSendMsg'; @@ -598,7 +601,6 @@ An example of the ability configuration is as follows: The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. - ```ts // Register the onRelease() listener of the caller ability. private regOnRelease(caller) { diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index 876f0a4e3e6e89665adefa23b9cbf1544c2a782e..1ce771daf195a09250a5fde05e0ce5a7acc60355 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -3,17 +3,16 @@ ## Definition and Usage of Want -[Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. It is used as a parameter of **startAbility()** to specify the startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. For example, when UIAbilityA starts UIAbilityB and needs to transfer some data to UIAbilityB, it can use Want to transfer the data. +[Want](../reference/apis/js-apis-app-ability-want.md) is an object that transfers information between application components. It is often used as a parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). For example, when UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use the **want** parameter in **startAbility()** to transfer the data. **Figure 1** Want usage - -![usage-of-want](figures/usage-of-want.png) +![usage-of-want](figures/usage-of-want.png) ## Types of Want -- **Explicit Want**: A type of Want with **abilityName** and **bundleName** specified when starting an ability. - When there is an explicit object to process the request, the target ability can be started by specifying the bundle name and ability name in Want. Explicit Want is usually used to start a known ability. +- **Explicit Want**: If **abilityName** and **bundleName** are specified when starting an ability, explicit Want is used. + Explicit Want is usually used to start a known target ability in the same application. The target ability is started by specifying **bundleName** of the application where the target ability is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target ability. ```ts let wantInfo = { @@ -23,8 +22,8 @@ } ``` -- **Implicit Want**: A type of Want with **abilityName** unspecified when starting the ability. - Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request. +- **Implicit Want**: If **abilityName** is not specified when starting the ability, implicit Want is used. + Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select. ```ts diff --git a/en/application-dev/application-models/widget-development-stage.md b/en/application-dev/application-models/widget-development-stage.md index 3e542956072a31fbc8dbca097ae264dfe8ebfc5f..73635fbc05c5e11cc0cc72857ccbcc7648bfa451 100644 --- a/en/application-dev/application-models/widget-development-stage.md +++ b/en/application-dev/application-models/widget-development-stage.md @@ -100,7 +100,7 @@ The widget provider development based on the [stage model](stage-model-developme - [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **module.json5** and profile configuration file. -- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. +- [Persistently Storing Widget Data](#persistently-storing-widget-data): This operation is a form of widget data exchange. - [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. @@ -597,3 +597,13 @@ The following is an example: }; ``` +## Restrictions + +To minimize the abuse of **FormExtensionAbility** by third-party applications, the following APIs cannot be invoked in **FormExtensionAbility**: + +- @ohos.ability.particleAbility.d.ts +- @ohos.backgroundTaskManager.d.ts +- @ohos.resourceschedule.backgroundTaskManager.d.ts +- @ohos.multimedia.camera.d.ts +- @ohos.multimedia.audio.d.ts +- @ohos.multimedia.media.d.ts diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index a43407aa5643f6a7d0265ca88c6234120e904d72..1f25dccf2a36f3bbedb5728291e8e11b3292476e 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -40,7 +40,7 @@ There are two roles in **DataShare**: - **onCreate** - Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server. + Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server. - **insert** @@ -64,11 +64,11 @@ There are two roles in **DataShare**: - **normalizeUri** - Converts the URI provided by the client to the URI used by the server. This API can be overridden as required. + Converts the URI provided by the client to the URI used by the server. - **denormalizeUri** - Converts the URI used by the server to the initial URI passed by the client. This API can be overridden as required. + Converts the URI used by the server to the initial URI passed by the client. Before implementing a **DataShare** service, create a **DataShareExtensionAbility** object in the DevEco Studio project as follows: @@ -76,7 +76,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit 2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**. -3. In the **DataShareAbility.ts** file, import the **DataShareExtensionAbility** and other dependencies. +3. In the **DataShareAbility.ts** file, import **DataShareExtensionAbility** and other dependencies. ```ts import Extension from '@ohos.application.DataShareExtensionAbility'; @@ -85,9 +85,9 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. +4. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. -6. 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. +5. 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. ```ts const DB_NAME = "DB00.db"; @@ -95,13 +95,13 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + TBL_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; - + let rdbStore; let result; - + export default class DataShareExtAbility extends Extension { private rdbStore_; - + // Override onCreate(). onCreate(want, callback) { result = this.context.cacheDir + '/datashare.txt'; @@ -114,12 +114,12 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); }); - if (callbakc) { + if (callback) { callback(); } }); } - + // Override query(). query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { @@ -143,17 +143,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit }; ``` -7. Define **DataShareExtensionAbility** in **module.json5**. +6. Define **DataShareExtensionAbility** in **module.json5**. - | Field| Description | - | ------------ | ------------------------------------------------------------ | - | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | - | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| - | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | - | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| + | Field | Description | Mandatory | + | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | Yes | + | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | Yes | + | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | Yes | + | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | Yes | + | "metadata" | Configuration for silent access, including the **name** and **resource** fields.
The **name** field identifies the configuration, which has a fixed value of **ohos.extension.dataShare**.
The **resource** field has a fixed value of **$profile:data_share_config**, which indicates that the profile name is **data_share_config.json**. | **metadata** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute). | **module.json5 example** - + ```json "extensionAbilities": [ { @@ -163,10 +164,44 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit "description": "$string:description_datashareextability", "type": "dataShare", "uri": "datashare://com.samples.datasharetest.DataShare", - "visible": true + "visible": true, + "metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}] } ] ``` + + **data_share_config.json Description** + + | Field | Description | Mandatory | + | ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | "tableConfig" | Label configuration. | Yes | + | "uri" | Range for which the configuration takes effect. The URI supports the following formats in descending order by priority:
- **\***: indicates all databases and tables.
- **datashare:///{bundleName\}/{moduleName\}/{storeName\}**: specifies a database.
- **datashare:///{bundleName\}/{moduleName\}/{storeName\}/{tableName\}**: specifies a table.
If URIs of different formats are configured, only the URI with higher priority takes effect. | Yes | + | "crossUserMode" | Whether data is shared by multiple users. The value **1** means to share data between multiple users, and the value **2** means the opposite. | **crossUserMode** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute). | + | "writePermission" | Write permission required for silent access. | No | + | "readPermission" | Read permission required for silent access. | No | + + **data_share_config.json Example** + + ```json + "tableConfig": [ + { + "uri": "*", + "writePermission": "ohos.permission.xxx" + }, + { + "uri": "datashare:///com.acts.datasharetest/entry/DB00", + "crossUserMode": 1, + "writePermission": "ohos.permission.xxx", + "readPermission": "ohos.permission.xxx" + }, + { + "uri": "datashare:///com.acts.datasharetest/entry/DB00/TBL00", + "crossUserMode": 2 + } + ] + ``` + + ### Data Consumer Application Development @@ -182,7 +217,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ```ts // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). - let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); + let dseUri = ('datashare:///com.samples.datasharetest.DataShare'); ``` 3. Create a **DataShareHelper** instance. @@ -211,18 +246,18 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit let valArray = ['*']; // Insert a piece of data. dsHelper.insert(dseUri, valuesBucket, (err, data) => { - console.log("dsHelper insert result: " + data); + console.log('dsHelper insert result: ' + data); }); // Update data. dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { - console.log("dsHelper update result: " + data); + console.log('dsHelper update result: ' + data); }); // Query data. dsHelper.query(dseUri, predicates, valArray, (err, data) => { - console.log("dsHelper query result: " + data); + console.log('dsHelper query result: ' + data); }); // Delete data. dsHelper.delete(dseUri, predicates, (err, data) => { - console.log("dsHelper delete result: " + data); + console.log('dsHelper delete result: ' + data); }); ``` diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index 5d1bcb0e289ac4fde9c70fc6d0097fdeee287b5d..dcbc34b48912020e0a7c6e0c987ce5de1d0b75c8 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -19,7 +19,7 @@ Call **createDistributedObject()** to create a distributed data object instance. | Bundle Name| API| Description| | -------- | -------- | -------- | -| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the distributed data object to set.
- **DistributedObject**: returns the distributed data object created. | +| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the distributed data object to create.
- **DistributedObject**: returns the distributed data object created.| ### Generating a Session ID @@ -91,10 +91,9 @@ The following example shows how to implement distributed data object synchroniza ```js import distributedObject from '@ohos.data.distributedDataObject'; ``` - 2. Apply for the permission. - Add the permissions required (FA model) to the **config.json** file. + Add the required permission (FA model) to the **config.json** file. ```json { @@ -112,18 +111,43 @@ The following example shows how to implement distributed data object synchroniza This permission must also be granted by the user when the application is started for the first time. ```js + // FA model import featureAbility from '@ohos.ability.featureAbility'; - + function grantPermission() { console.info('grantPermission'); let context = featureAbility.getContext(); context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { - console.info(`result.requestCode=${result.requestCode}`) - + console.info(`requestPermissionsFromUser CallBack`); + }) console.info('end grantPermission'); } - + + grantPermission(); + ``` + + ```ts + // Stage model + import UIAbility from '@ohos.app.ability.UIAbility'; + + let context = null; + + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + context = this.context; + } + } + + function grantPermission() { + let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { + console.info('success: ${data}'); + }).catch((error) => { + console.error('failed: ${error}'); + }); + } + grantPermission(); ``` @@ -139,10 +163,10 @@ The following example shows how to implement distributed data object synchroniza }); let sessionId = distributedObject.genSessionId(); ``` - + 4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects. - -```js + + ```js // Local object let localObject = distributedObject.createDistributedObject({ name: "jack", @@ -164,7 +188,7 @@ The following example shows how to implement distributed data object synchroniza // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. remoteObject.setSessionId(sessionId); ``` - + 5. Observe the data changes of the 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 the data changes. ```js @@ -202,33 +226,29 @@ The following example shows how to implement distributed data object synchroniza localObject.parent.mother = "mom"; ``` -7. Access the distributed data object. - - Obtain the distributed data object attributes, which are the latest data on the network. +7. Access the distributed data object.
Obtain the distributed data object attributes, which are the latest data on the network. ```js -console.info("name " + localObject["name"]); + 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. ```js -// Unregister the specified data change callback. + // Unregister the specified data change callback. localObject.off("change", changeCallback); // Unregister all data change callbacks. localObject.off("change"); ``` - 9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. - -```js + + ```js function statusCallback(sessionId, networkId, status) { this.response += "status changed " + sessionId + " " + status + " " + networkId; } localObject.on("status", this.statusCallback); ``` - + 10. Save a distributed data object and delete it. ```js @@ -247,20 +267,16 @@ console.info("name " + localObject["name"]); console.info("revokeSave failed."); }); ``` - -11. Unsubscribe from the status changes of the distributed data object. - - You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered. +11. Unsubscribe from the status changes of this 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 -// Unregister the specified status change callback. + // Unregister the specified status change callback. localObject.off("status", this.statusCallback); // Unregister all status change callbacks. localObject.off("status"); ``` - 12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object. ```js -localObject.setSessionId(""); + localObject.setSessionId(""); ``` diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 4d54d3de270712d876971053eebbce8665561ec9..728e66f064bf79635a0ca18640d00c6713c7edc8 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -37,14 +37,14 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th - **Updating Data** - Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. + Call **update()** to pass the new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. **Table 3** API for updating data | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. | + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data.| - **Deleting Data** @@ -55,7 +55,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class | API | Description | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | - | RdbStore | delete(predicates: RdbPredicates): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.
- **predicates**: conditions for deleting data. | + | RdbStore | delete(predicates: RdbPredicates): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.
- **predicates**: conditions for deleting data.| - **Querying Data** @@ -201,76 +201,81 @@ You can obtain the distributed table name for a remote device based on the local FA model: ```js - import data_rdb from '@ohos.data.relationalStore' + import relationalStore from '@ohos.data.relationalStore' import featureAbility from '@ohos.ability.featureAbility' + var store; + // Obtain the context. - let context = featureAbility.getContext() + let context = featureAbility.getContext(); const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + securityLevel: relationalStore.SecurityLevel.S1 + }; // Assume that the current RDB store version is 3. - data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - // When an RDB store is created, the default version is 0. - if (rdbStore.version == 0) { - rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) - // Set the RDB store version. The input parameter must be an integer greater than 0. - rdbStore.version = 3 - } + relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + // When an RDB store is created, the default version is 0. + if (store.version == 0) { + store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null); + // Set the RDB store version. The input parameter must be an integer greater than 0. + store.version = 3; + } - // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. - if (rdbStore.version != 3 && rdbStore.version == 1) { - // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) - rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) - rdbStore.version = 2 - } + // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. + if (store.version != 3 && store.version == 1) { + // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) + store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null); + store.version = 2; + } - // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. - if (rdbStore.version != 3 && rdbStore.version == 2) { - // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) - rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) - rdbStore.version = 3 - } + // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. + if (store.version != 3 && store.version == 2) { + // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) + store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null); + store.version = 3; + } }) ``` Stage model: ```ts - import data_rdb from '@ohos.data.relationalStore' + import relationalStore from '@ohos.data.relationalStore' import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { - const STORE_CONFIG = { - name: "rdbstore.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + var store; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 + }; - // Assume that the current RDB store version is 3. - data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { - // When an RDB store is created, the default version is 0. - if (rdbStore.version == 0) { - rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null) - // Set the RDB store version. The input parameter must be an integer greater than 0. - rdbStore.version = 3 - } + // Assume that the current RDB store version is 3. + relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + // When an RDB store is created, the default version is 0. + if (store.version == 0) { + store.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null); + // Set the RDB store version. The input parameter must be an integer greater than 0. + store.version = 3; + } - // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. - if (rdbStore.version != 3 && rdbStore.version == 1) { - // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) - rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null) - rdbStore.version = 2 - } + // When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2. + if (store.version != 3 && store.version == 1) { + // version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score) + store.executeSql("ALTER TABLE student ADD COLUMN score REAL", null); + store.version = 2; + } - // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. - if (rdbStore.version != 3 && rdbStore.version == 2) { - // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) - rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null) - rdbStore.version = 3 - } - }) + // When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3. + if (store.version != 3 && store.version == 2) { + // version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score) + store.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null); + store.version = 3; + } + }) } } ``` @@ -284,23 +289,24 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let u8 = new Uint8Array([1, 2, 3]) - const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - let insertPromise = rdbStore.insert("test", valueBucket) + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }; + let insertPromise = store.insert("test", valueBucket); ``` ```js // Use a transaction to insert data. - beginTransaction() try { - let u8 = new Uint8Array([1, 2, 3]) - const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } - let insertPromise1 = rdbStore.insert("test", valueBucket1) - let insertPromise2 = rdbStore.insert("test", valueBucket2) - commit() - } catch (e) { - rollBack() + store.beginTransaction(); + let u8 = new Uint8Array([1, 2, 3]); + const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }; + let promise = store.insert("test", valueBucket); + promise.then(() => { + store.commit(); + }) + } catch (err) { + console.error(`Transaction failed, err: ${err}`); + store.rollBack(); } ``` @@ -315,17 +321,17 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let predicates = new data_rdb.RdbPredicates("test"); - predicates.equalTo("name", "Tom") - let promisequery = rdbStore.query(predicates) + let predicates = new relationalStore.RdbPredicates("test"); + predicates.equalTo("name", "Tom"); + let promisequery = store.query(predicates); promisequery.then((resultSet) => { - resultSet.goToFirstRow() - const id = resultSet.getLong(resultSet.getColumnIndex("id")) - const name = resultSet.getString(resultSet.getColumnIndex("name")) - const age = resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) - resultSet.close() + resultSet.goToFirstRow(); + const id = resultSet.getLong(resultSet.getColumnIndex("id")); + const name = resultSet.getString(resultSet.getColumnIndex("name")); + const age = resultSet.getLong(resultSet.getColumnIndex("age")); + const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")); + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")); + resultSet.close(); }) ``` @@ -335,9 +341,9 @@ You can obtain the distributed table name for a remote device based on the local ```json "requestPermissions": - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } ``` (2) Obtain the required permissions. @@ -351,13 +357,13 @@ You can obtain the distributed table name for a remote device based on the local ```js let context = featureAbility.getContext(); context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { - console.info(`result.requestCode=${result.requestCode}`) + console.info(`result.requestCode=${result.requestCode}`); }) - let promise = rdbStore.setDistributedTables(["test"]) + let promise = store.setDistributedTables(["test"]); promise.then(() => { - console.info("setDistributedTables success.") + console.info(`setDistributedTables success.`); }).catch((err) => { - console.info("setDistributedTables failed.") + console.error(`setDistributedTables failed, ${err}`); }) ``` @@ -372,16 +378,16 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let predicate = new data_rdb.RdbPredicates('test') - predicate.inDevices(['12345678abcde']) - let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) + let predicate = new relationalStore.RdbPredicates('test'); + predicate.inDevices(['12345678abcde']); + let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicate); promise.then((result) => { - console.log('sync done.') - for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + 'status=' + result[i][1]) - } + console.info(`sync done.`); + for (let i = 0; i < result.length; i++) { + console.info(`device=${result[i][0]}, status=${result[i][1]}`); + } }).catch((err) => { - console.log('sync failed') + console.error(`sync failed, err: ${err}`); }) ``` @@ -395,15 +401,15 @@ You can obtain the distributed table name for a remote device based on the local ```js function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + device[i] + 'data changed') - } + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } } try { - rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.log('register observer failed') + console.error(`register observer failed, err: ${err}`); } ``` @@ -416,8 +422,24 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); - let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) + import deviceManager from '@ohos.distributedHardware.deviceManager' + + let deviceIds = []; + deviceManager.createDeviceManager('bundleName', (err, value) => { + if (!err) { + let devManager = value; + if (devManager != null) { + // Obtain device IDs. + let devices = devManager.getTrustedDeviceListSync(); + for (let i = 0; i < devices.length; i++) { + deviceIds[i] = devices[i].deviceId; + } + } + } + }) + + let tableName = store.obtainDistributedTableName(deviceIds[0], "test"); + let resultSet = store.querySql("SELECT * FROM " + tableName); ``` 8. Query data of a remote device. @@ -429,19 +451,19 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let rdbPredicate = new data_rdb.RdbPredicates('employee') - predicates.greaterThan("id", 0) - let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + let rdbPredicate = new relationalStore.RdbPredicates('employee'); + predicates.greaterThan("id", 0) ; + let promiseQuery = store.remoteQuery('12345678abcde', 'employee', rdbPredicate); promiseQuery.then((resultSet) => { - while (resultSet.goToNextRow()) { - let idx = resultSet.getLong(0); - let name = resultSet.getString(1); - let age = resultSet.getLong(2); - console.info(idx + " " + name + " " + age); - } - resultSet.close(); + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); + console.info(`indx: ${idx}, name: ${name}, age: ${age}`); + } + resultSet.close(); }).catch((err) => { - console.info("failed to remoteQuery, err: " + err) + console.error(`failed to remoteQuery, err: ${err}`); }) ``` @@ -452,11 +474,11 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let promiseBackup = rdbStore.backup("dbBackup.db") + let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(() => { - console.info('Backup success.') + console.info(`Backup success.`); }).catch((err) => { - console.info('Backup failed, err: ' + err) + console.error(`Backup failed, err: ${err}`); }) ``` @@ -465,10 +487,10 @@ You can obtain the distributed table name for a remote device based on the local The sample code is as follows: ```js - let promiseRestore = rdbStore.restore("dbBackup.db") + let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(() => { - console.info('Restore success.') + console.info(`Restore success.`); }).catch((err) => { - console.info('Restore failed, err: ' + err) + console.error(`Restore failed, err: ${err}`); }) ``` diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md index 69fca5fb8177eddc65ddfc0ffade70350446a8a1..d8d93e847c73e5c6eb1e96604a17bd456b010162 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md @@ -36,5 +36,5 @@ Currently you can have access to statistics on the application usage, and the no Deregister the callback for application group changes. ## Required Permissions -- Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**. -- This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**. +- Before calling the following system APIs, you must request the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **isIdleState**, **queryBundleEvents**, **queryBundleStatsInfos**, **queryBundleStatsInfoByInterval**, **queryDeviceEventStats**, **queryNotificationEventStats**, **queryAppGroup(bundleName)**, **setAppGroup**, **registerAppGroupCallBack**, **unregisterAppGroupCallBack**, **queryModuleUsageRecords**, and **queryModuleUsageRecords(maxnum)**. +- You do not need to request this permission before calling **queryCurrentBundleEvents** and **queryAppGroup()**, which are third-party APIs. diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md index 45255f18ee313ad96d072e42f620b219315a8adf..82027e91a9c15b1fd1b62a8c5ef4cddc2f9c0ef3 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md @@ -225,7 +225,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; } ``` -7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured. A third-party application can only check the idle status of itself. +7. Check whether the application specified by **bundleName** is in the idle state. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured. ```js import usageStatistics from '@ohos.resourceschedule.usageStatistics' @@ -531,4 +531,4 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; } catch (error) { console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); } - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/device/Readme-EN.md b/en/application-dev/device/Readme-EN.md index 6e7fd27fd4506a487faeac457371c7c015a6b771..abf5154a8caa1473367960eea7b9118598ce706a 100644 --- a/en/application-dev/device/Readme-EN.md +++ b/en/application-dev/device/Readme-EN.md @@ -1,19 +1,19 @@ # Device -- USB Service - - [USB Service Overview](usb-overview.md) - - [USB Service Development](usb-guidelines.md) - Location - [Location Service Development](location-guidelines.md) -- Sensor - - [Sensor Overview](sensor-overview.md) - - [Sensor Development](sensor-guidelines.md) -- Vibrator - - [Vibrator Overview](vibrator-overview.md) - - [Vibrator Development](vibrator-guidelines.md) - Multimodal Input - [Input Device Development](inputdevice-guidelines.md) - [Mouse Pointer Development](pointerstyle-guidelines.md) +- Sensor + - [Sensor Overview](sensor-overview.md) + - [Sensor Development](sensor-guidelines.md) - Update Service - [Sample Server Overview](sample-server-overview.md) - [Sample Server Development](sample-server-guidelines.md) +- USB Service + - [USB Service Overview](usb-overview.md) + - [USB Service Development](usb-guidelines.md) +- Vibrator + - [Vibrator Overview](vibrator-overview.md) + - [Vibrator Development](vibrator-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/file-management/medialibrary-album-guidelines.md b/en/application-dev/file-management/medialibrary-album-guidelines.md index f03e11cf3cbc0e94737d3a66214f72dfb0a47ba3..0fa043bad49b51aff526198137550f5079bd4349 100644 --- a/en/application-dev/file-management/medialibrary-album-guidelines.md +++ b/en/application-dev/file-management/medialibrary-album-guidelines.md @@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**. ```ts async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const path = await media.getPublicDirectory(DIR_IMAGE); - // myAlbum is the path for storing the new file and the name of the new album. - media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { - if (fileAsset != undefined) { - console.info('createAlbum successfully, message = ' + fileAsset); - } else { - console.info('createAlbum failed, message = ' + err); - } - }); + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_IMAGE); + // myAlbum is the path for storing the new file and the name of the new album. + media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { + if (fileAsset === undefined) { + console.error('createAlbum failed, message = ' + err); + } else { + console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset)); + } + }); } ``` @@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**. ```ts async function example() { - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let albumList = await media.getAlbums(AlbumNoArgsfetchOp); - let album = albumList[0]; - album.albumName = 'newAlbum'; - // Void callback. - album.commitModify().then(function() { - console.info("albumRename successfully"); - }).catch(function(err){ - console.info("albumRename failed with error: " + err); - }); + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let albumList = await media.getAlbums(AlbumNoArgsfetchOp); + let album = albumList[0]; + album.albumName = 'newAlbum'; + // Void callback. + album.commitModify().then(() => { + console.info("albumRename successfully"); + }).catch((err) => { + console.error("albumRename failed with error: " + err); + }); } ``` diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md index 7e4a1cdaff6cbd76995b295d5f4606f54c35913e..4c7e2ecd4db6723a66930e624bd4b36b556330d1 100644 --- a/en/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi ```ts async function example(){ - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; - const dicResult = await media.getPublicDirectory(DIR_CAMERA); - if (dicResult == 'Camera/') { - console.info('mediaLibraryTest : getPublicDirectory passed'); - } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); - } + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; + const dicResult = await media.getPublicDirectory(DIR_CAMERA); + if (dicResult == 'Camera/') { + console.info('mediaLibraryTest : getPublicDirectory passed'); + } else { + console.error('mediaLibraryTest : getPublicDirectory failed'); + } } ``` @@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. -You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. +You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. **Prerequisites** - You have obtained a **MediaLibrary** instance. -- You have granted the permission **ohos.permission.WRITE_MEDIA**. -- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. +- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**. +- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary. +- The **testFile.txt** file has been created and contains content. **How to Develop** -1. Call [context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. +1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. -3. Call **fileio.open** to open the file in the sandbox. +3. Call **fs.open** to open the file in the sandbox. 4. Call **fileAsset.open** to open the file in the public directory. -5. Call **fileio.copyfile** to copy the file. -6. Call **fileAsset.close** and **fileio.close** to close the file. +5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file. +6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file. **Example 1: Copying Files from the Public Directory to the Sandbox** ```ts async function copyPublic2Sandbox() { + try { const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context); - let sandboxDirPath = globalThis.context.filesDir; + let sandboxDirPath = context.filesDir; let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?', - selectionArgs: ['testFile.txt'], + selections: fileKeyObj.DISPLAY_NAME + '= ?', + selectionArgs: ['testFile.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fileAsset = await fetchResult.getFirstObject(); let fdPub = await fileAsset.open('rw'); - let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); - await fileio.copyFile(fdPub, fdSand); + let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + await fs.copyFile(fdPub, fdSand.fd); await fileAsset.close(fdPub); - await fileio.close(fdSand); + await fs.close(fdSand.fd); - let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); - console.log('content read from sandbox file: ', content_sand) + let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt'); + console.info('content read from sandbox file: ', content_sand) + } catch (err) { + console.info('[demo] copyPublic2Sandbox fail, err: ', err); + } } ``` @@ -107,81 +112,81 @@ async function copyPublic2Sandbox() { ```ts async function copySandbox2Public() { - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let sandboxDirPath = globalThis.context.filesDir; - - let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; - const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); - try { - let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); - console.info('createFile successfully, message = ' + fileAsset); - } catch (err) { - console.info('createFile failed, message = ' + err); - } - try { - let fileKeyObj = mediaLibrary.FileKey; - let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?', - selectionArgs: ['testFile02.txt'], - }; - let fetchResult = await media.getFileAssets(fileAssetFetchOp); - var fileAsset = await fetchResult.getFirstObject(); - } catch (err) { - console.info('file asset get failed, message = ' + err); - } - let fdPub = await fileAsset.open('rw'); - let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); - await fileio.copyFile(fdSand, fdPub); - await fileio.close(fdPub); - await fileio.close(fdSand); - let fdPubRead = await fileAsset.open('rw'); - try { - let arrayBuffer = new ArrayBuffer(4096); - await fileio.read(fdPubRead, arrayBuffer); - var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); - fileAsset.close(fdPubRead); - } catch (err) { - console.log('read text failed, message = ', err); - } - console.log('content read from public file: ', content_pub); + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let sandboxDirPath = context.filesDir; + + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); + try { + let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); + console.info('createFile successfully, message = ' + fileAsset); + } catch (err) { + console.error('createFile failed, message = ' + err); + } + try { + let fileKeyObj = mediaLibrary.FileKey; + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?', + selectionArgs: ['testFile02.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + var fileAsset = await fetchResult.getFirstObject(); + } catch (err) { + console.error('file asset get failed, message = ' + err); + } + let fdPub = await fileAsset.open('rw'); + let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE); + await fs.copyFile(fdSand.fd, fdPub); + await fileAsset.close(fdPub); + await fs.close(fdSand.fd); + let fdPubRead = await fileAsset.open('rw'); + try { + let arrayBuffer = new ArrayBuffer(4096); + await fs.read(fdPubRead, arrayBuffer); + var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); + fileAsset.close(fdPubRead); + } catch (err) { + console.error('read text failed, message = ', err); + } + console.info('content read from public file: ', content_pub); } ``` ### Reading and Writing a File -You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. +You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file. **Prerequisites** - You have obtained a **MediaLibrary** instance. -- You have granted the permission **ohos.permission.WRITE_MEDIA**. -- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. +- You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**. +- You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary. **How to Develop** 1. Create a file. - ```ts - async function example() { - let mediaType = mediaLibrary.MediaType.FILE; - let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const path = await media.getPublicDirectory(DIR_DOCUMENTS); - media.createAsset(mediaType, "testFile.text", path).then (function (asset) { - console.info("createAsset successfully:" + JSON.stringify(asset)); - }).catch(function(err){ - console.info("createAsset failed with error: " + err); - }); - } - ``` +```ts +async function example() { + let mediaType = mediaLibrary.MediaType.FILE; + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_DOCUMENTS); + media.createAsset(mediaType, "testFile.text", path).then((asset) => { + console.info("createAsset successfully:" + JSON.stringify(asset)); + }).catch((err) => { + console.error("createAsset failed with error: " + err); + }); +} +``` 2. Call **FileAsset.open** to open the file. -3. Call **fileio.write** to write a string to the file. +3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file. -4. Call **fileio.read** to read the file and save the data read in an array buffer. +4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer. 5. Convert the array buffer to a string. @@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ```ts async function writeOnlyPromise() { - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey; - let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?', - selectionArgs: ['testFile.txt'], - }; - let fetchResult = await media.getFileAssets(fileAssetFetchOp); - let fileAsset = await fetchResult.getFirstObject(); - console.info('fileAssetName: ', fileAsset.displayName); - - try { - let fd = await fileAsset.open('w'); - console.info('file descriptor: ', fd); - await fileio.write(fd, "Write file test content."); - await fileAsset.close(fd); - } catch (err) { - console.info('write file failed, message = ', err); - } + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?', + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAssetName: ', fileAsset.displayName); + + try { + let fd = await fileAsset.open('w'); + console.info('file descriptor: ', fd); + await fs.write(fd, "Write file test content."); + await fileAsset.close(fd); + } catch (err) { + console.error('write file failed, message = ', err); + } } ``` @@ -217,28 +222,28 @@ async function writeOnlyPromise() { ```ts async function readOnlyPromise() { - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey; - let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , - selectionArgs: ['testFile.txt'], - }; - let fetchResult = await media.getFileAssets(fileAssetFetchOp); - let fileAsset = await fetchResult.getFirstObject(); - console.info('fileAssetName: ', fileAsset.displayName); - - try { - let fd = await fileAsset.open('r'); - let arrayBuffer = new ArrayBuffer(4096); - await fileio.read(fd, arrayBuffer); - let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); - globalThis.fileContent = fileContent; - globalThis.fileName = fileAsset.displayName; - console.info('file content: ', fileContent); - await fileAsset.close(fd); - } catch (err) { - console.info('read file failed, message = ', err); - } + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAssetName: ', fileAsset.displayName); + + try { + let fd = await fileAsset.open('r'); + let arrayBuffer = new ArrayBuffer(4096); + await fs.read(fd, arrayBuffer); + let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); + globalThis.fileContent = fileContent; + globalThis.fileName = fileAsset.displayName; + console.info('file content: ', fileContent); + await fileAsset.close(fd); + } catch (err) { + console.error('read file failed, message = ', err); + } } ``` diff --git a/en/application-dev/file-management/medialibrary-overview.md b/en/application-dev/file-management/medialibrary-overview.md index 481a87c8a103fafe4f496d76b3163e7a03f9d28c..f7e0ab9ac4772a7770b1e2bc9f6b63845cb654b5 100644 --- a/en/application-dev/file-management/medialibrary-overview.md +++ b/en/application-dev/file-management/medialibrary-overview.md @@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application 1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). - ```json - { - "module": { - "requestPermissions": [ - { - "name": "ohos.permission.MEDIA_LOCATION", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "EntryAbility" - ], - "when": "always" - } - }, - { - "name": "ohos.permission.READ_MEDIA", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "EntryAbility" - ], - "when": "always" - } - }, - { - "name": "ohos.permission.WRITE_MEDIA", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "EntryAbility" - ], - "when": "always" - } - } - ] - } - } - ``` +```json +{ + "module": { + "requestPermissions": [ + { + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.READ_MEDIA", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.WRITE_MEDIA", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "always" + } + } + ] + } +} +``` 2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; - - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - let list : Array = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; - let permissionRequestResult; - let atManager = abilityAccessCtrl.createAtManager(); - atManager.requestPermissionsFromUser(this.context, list, (err, result) => { - if (err) { - console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); - } else { - permissionRequestResult=result; - console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); - } - }); - } - } - ``` +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + let list : Array = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; + let permissionRequestResult; + let 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)); + } + }); + } +} +``` diff --git a/en/application-dev/file-management/medialibrary-resource-guidelines.md b/en/application-dev/file-management/medialibrary-resource-guidelines.md index dea130ff3de563a904684d021a7d8f7f9b514c83..7d120ec9a4fa9fd38ba92be97ee7fdd5a6f33816 100644 --- a/en/application-dev/file-management/medialibrary-resource-guidelines.md +++ b/en/application-dev/file-management/medialibrary-resource-guidelines.md @@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.IMAGE; - let option = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + fetchFileResult.getFirstObject().then((fileAsset) => { + console.log('getFirstObject.displayName : ' + fileAsset.displayName); + for (let i = 1; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }).catch((err) => { + console.error('Failed to get next object: ' + err); + }); + } + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); } ``` ### Querying Media Assets with the Specified Date -The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. +The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions. To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. @@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let option = { - selections: fileKeyObj.DATE_ADDED + '= ?', - selectionArgs: ['2022-8-5'], - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + let fileKeyObj = mediaLibrary.FileKey; + let option = { + selections: fileKeyObj.DATE_ADDED + '> ?', + selectionArgs: ['2022-8-5'], + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + fetchFileResult.getFirstObject().then((fileAsset) => { + console.info('getFirstObject.displayName : ' + fileAsset.displayName); + for (let i = 1; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }).catch((err) => { + console.error('Failed to get next object: ' + err); + }); + } + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); } ``` @@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order** ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.IMAGE; - let option = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + fetchFileResult.getFirstObject().then((fileAsset) => { + console.info('getFirstObject.displayName : ' + fileAsset.displayName); + for (let i = 1; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject().then((fileAsset) => { + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }).catch((err) => { + console.error('Failed to get next object: ' + err); + }); + } + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); } ``` @@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.IMAGE; - let option = { - selections: fileKeyObj.ALBUM_NAME + '= ?', - selectionArgs: ['myAlbum'], - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const fetchFileResult = await media.getFileAssets(option); - for (let i = 0; i < fetchFileResult.getCount(); i++) { - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); - }) - } + let fileKeyObj = mediaLibrary.FileKey; + let option = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs: ['myAlbum'], + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + if (albumList.length > 0) { + fetchFileResult.getFirstObject().then((album) => { + console.info('getFirstObject.displayName : ' + album.albumName); + }).catch((err) => { + console.error('Failed to get first object: ' + err); + }); + } else { + console.info('getAlbum list is: 0'); + } } ``` ## Obtaining Images and Videos in an Album You can obtain media assets in an album in either of the following ways: - - Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). - Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. @@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**. 1. Create a retrieval condition for obtaining the target **Album** instance. - ```ts - let fileKeyObj = mediaLibrary.FileKey; - let AlbumNoArgsFetchOp = { - selections: fileKeyObj.ALBUM_NAME + '= ?', - selectionArgs:['New Album 1'] - } - ``` +```ts +let fileKeyObj = mediaLibrary.FileKey; +let AlbumNoArgsFetchOp = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'] +} +``` 2. Create a retrieval condition for obtaining videos in the target album. - ```ts - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.VIDEO; - let imagesFetchOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - } - ``` +```ts +let fileKeyObj = mediaLibrary.FileKey; +let videoType = mediaLibrary.MediaType.VIDEO; +let videoFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [videoType.toString()], +} +``` 3. Call **Album.getFileAssets** to obtain the videos in the target album. @@ -188,28 +195,28 @@ Complete sample code: ```ts async function getCameraImagePromise() { - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let imagesFetchOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - } - let AlbumNoArgsFetchOp = { - selections: fileKeyObj.ALBUM_NAME + '= ?', - selectionArgs:['New Album 1'] - } - - let albumList = await media.getAlbums(AlbumNoArgsFetchOp); - if (albumList.length > 0) { - const album = albumList[0]; - let fetchFileResult = await album.getFileAssets(imagesFetchOp); - let count = fetchFileResult.getCount(); - console.info("get mediaLibrary IMAGE number", count); - } else { - console.info('getAlbum list is: 0'); - } + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let videoType = mediaLibrary.MediaType.VIDEO; + let videoFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [videoType.toString()], + } + let AlbumNoArgsFetchOp = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'] + } + + let albumList = await media.getAlbums(AlbumNoArgsFetchOp); + if (albumList.length > 0) { + const album = albumList[0]; + let fetchFileResult = await album.getFileAssets(videoFetchOp); + let count = fetchFileResult.getCount(); + console.info("get mediaLibrary VIDEO number", count); + } else { + console.info('getAlbum list is: 0'); + } } ``` @@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ```ts async function getFirstThumbnailPromise() { - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey; - let imageType = mediaLibrary.MediaType.IMAGE; - let imagesFetchOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - } - - let size = { width: 720, height: 720 }; - const fetchFileResult = await media.getFileAssets(imagesFetchOp); - if (fetchFileResult != undefined) { - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size).then((pixelMap) => { - pixelMap.getImageInfo().then((info) => { - console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); - }).catch((err) => { - console.info("getImageInfo failed with error:" + err); - }); - }).catch((err) => { - console.info("getImageInfo failed with error:" + err); - }); - } else { - console.info("get image failed with error"); - } + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + + let size = { width: 720, height: 720 }; + const fetchFileResult = await media.getFileAssets(imagesFetchOp); + if (fetchFileResult === undefined) { + console.error("get image failed with error"); + return; + } else { + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size).then((pixelMap) => { + pixelMap.getImageInfo().then((info) => { + console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); + }).catch((err) => { + console.error("getImageInfo failed with error: " + err); + }); + }).catch((err) => { + console.error("getImageInfo failed with error: " + err); + }); + } } ``` @@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type. ```ts async function example() { - let mediaType = mediaLibrary.MediaType.FILE; - let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const path = await media.getPublicDirectory(DIR_DOCUMENTS); - media.createAsset(mediaType, "testFile.text", path).then ((asset) => { - console.info("createAsset successfully:"+ JSON.stringify(asset)); - }).catch((err) => { - console.info("createAsset failed with error:"+ err); - }); + let mediaType = mediaLibrary.MediaType.FILE; + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_DOCUMENTS); + media.createAsset(mediaType, "testFile.text", path).then((asset) => { + console.info("createAsset successfully:"+ JSON.stringify(asset)); + }).catch((err) => { + console.error("createAsset failed with error: " + err); + }); } ``` @@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.FILE; - let option = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const fetchFileResult = await media.getFileAssets(option); - let asset = await fetchFileResult.getFirstObject(); - if (asset == undefined) { - console.error('asset not exist'); - return; - } - // Void callback. - asset.trash(true).then(() => { - console.info("trash successfully"); - }).catch((err) => { - console.info("trash failed with error: " + err); - }); + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset === undefined) { + console.error('asset not exist'); + return; + } + // Void callback. + asset.trash(true).then(() => { + console.info("trash successfully"); + }).catch((err) => { + console.error("trash failed with error: " + err); + }); } ``` @@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch - You have obtained a **MediaLibrary** instance. - You have granted the permission **ohos.permission.WRITE_MEDIA**. -The following describes how to rename the first file in the result set as **newtitle.text**. +The following describes how to rename the first file in the result set as **newImage.jpg**. **How to Develop** @@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.FILE; - let option = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - }; - const context = getContext(this); - let media = mediaLibrary.getMediaLibrary(context); - const fetchFileResult = await media.getFileAssets(option); - let asset = await fetchFileResult.getFirstObject(); - if (asset == undefined) { - console.error('asset not exist'); + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + let media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset === undefined) { + console.error('asset not exist'); + return; + } + asset.displayName = 'newImage.jpg'; + // Void callback. + asset.commitModify((err) => { + if (err) { + console.error('fileRename Failed '); return; } - asset.displayName = 'newImage.jpg'; - // Void callback. - asset.commitModify((err) => { - if (err) { - console.error('fileRename Failed '); - return; - } - console.log('fileRename successful.'); - }); + console.info('fileRename successful.'); + }); } ``` diff --git a/en/application-dev/media/remote-camera.md b/en/application-dev/media/remote-camera.md index e35950e73b1993b8a446f75e3007a80e4bbaff19..d7bf710279c1504cd9703eca9af7cf5433cb3dac 100644 --- a/en/application-dev/media/remote-camera.md +++ b/en/application-dev/media/remote-camera.md @@ -5,7 +5,7 @@ You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording. ## How to Develop -Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). +Connect your calculator to a distributed device. Your calculator will call **getSupportedCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **cameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). @@ -24,15 +24,11 @@ import media from '@ohos.multimedia.media' import featureAbility from '@ohos.ability.featureAbility' // Create a CameraManager object. -let cameraManager -await camera.getCameraManager(globalThis.Context, (err, manager) => { - if (err) { - console.error('Failed to get the CameraManager instance ${err.message}'); - return; - } - console.log('Callback returned with the CameraManager instance'); - cameraManager = manager -}) +let cameraManager = camera.getCameraManager(globalThis.Context) +if (!cameraManager) { + console.error("camera.getCameraManager error") + return; +} // Register a callback to listen for camera status changes and obtain the updated camera status information. cameraManager.on('cameraStatus', (cameraStatusInfo) => { @@ -41,16 +37,12 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => { }) // Obtain the camera list. -let cameraArray let remoteCamera -await cameraManager.getCameras((err, cameras) => { - if (err) { - console.error('Failed to get the cameras. ${err.message}'); - return; - } - console.log('Callback returned with an array of supported cameras: ' + cameras.length); - cameraArray = cameras -}) +let cameraArray = cameraManager.getSupportedCameras(); +if (cameraArray.length <= 0) { + console.error("cameraManager.getSupportedCameras error") + return; +} for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. @@ -58,15 +50,16 @@ for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type. if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) { - remoteCamera = cameraArray[cameraIndex].cameraId + remoteCamera = cameraArray[cameraIndex] } } // Create a camera input stream. let cameraInput -await cameraManager.createCameraInput(remoteCamera).then((input) => { - console.log('Promise returned with the CameraInput instance'); - cameraInput = input -}) +try { + cameraInput = cameraManager.createCameraInput(remoteCamera); +} catch () { + console.error('Failed to createCameraInput errorCode = ' + error.code); +} ``` For details about the subsequent steps, see [Camera Development](./camera.md). diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index 5113c413d523b9d58363b78ac94ba42cc1954e9d..4448869d84d51b0fb17836e69af14ad28433f395 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -4,9 +4,7 @@ OpenHarmony applications use JavaScript (JS) when calling native APIs. The nativ ## How to Develop -The DevEco Studio has a default project that uses NAPIs. - -You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development. +The DevEco Studio has a default project that uses NAPIs. You can choose **File** > **New** > **Create Project** to create a **Native C++** project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development. You can import the native .so that contains the JS processing logic. For example, **import hello from 'libhello.so'** to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the **hello** object of the application to call the native capability. @@ -19,7 +17,10 @@ You can import the native .so that contains the JS processing logic. For example ### .so Naming Rules -Each module has a .so file. For example, if the module name is **hello**, name the .so file **libhello.so**. The **nm_modname** field in **napi_module** must be **hello**, which is the same as the module name. The sample code for importing the .so file is **import hello from 'libhello.so'**. +The .so file names must comply with the following rules: + +* Each module has a .so file. +* The **nm_modname** field in **napi_module** must be the same as the module name. For example, if the module name is **hello**, name the .so file **libhello.so**. The sample code for importing the .so file is **import hello from 'libhello.so'**. ### JS Objects and Threads diff --git a/en/application-dev/notification/notification-enable.md b/en/application-dev/notification/notification-enable.md index 12aa4f41eb1570d707b4c65310cefe6aa45e1b17..4b0ecd303d8f13b3f7ba4f43364ddd53ffadc1d7 100644 --- a/en/application-dev/notification/notification-enable.md +++ b/en/application-dev/notification/notification-enable.md @@ -44,6 +44,6 @@ For details about the APIs, see [@ohos.notificationManager](../reference/apis/js notificationManager.requestEnableNotification().then(() => { console.info(`[ANS] requestEnableNotification success`); }).catch((err) => { - console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`); + console.error(`[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); }); ``` diff --git a/en/application-dev/notification/notification-subscription.md b/en/application-dev/notification/notification-subscription.md index a633a2bb955bcf877fbe4befb8b40ad103d7e7e6..c62b65a25c4d80b37610449e6309e05ef259893f 100644 --- a/en/application-dev/notification/notification-subscription.md +++ b/en/application-dev/notification/notification-subscription.md @@ -74,7 +74,7 @@ The major APIs for notification subscription are described as follows. For detai ```ts notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. if (err) { - console.error(`[ANS] failed to subscribe, error[${err}]`); + console.error(`[ANS] subscribe failed, code is ${err.code}, message is ${err.message}`); return; } console.info(`[ANS] subscribeTest success : + ${data}`); diff --git a/en/application-dev/notification/notification-with-wantagent.md b/en/application-dev/notification/notification-with-wantagent.md index d8f0321d28738749d6ed6073e49f26181c22e706..47275ecabeed338cfb67cff44cb39c325498e0ff 100644 --- a/en/application-dev/notification/notification-with-wantagent.md +++ b/en/application-dev/notification/notification-with-wantagent.md @@ -5,6 +5,7 @@ A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsu Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered. **Figure 1** Publishing a notification with a WantAgent object + ![notification-with-wantagent](figures/notification-with-wantagent.png) @@ -14,11 +15,11 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ | Name| Description| | -------- | -------- | -| getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void | Creates a **WantAgent** object.| -| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void | Triggers a **WantAgent** object.| -| cancel(agent: WantAgent, callback: AsyncCallback<void>): void | Cancels a **WantAgent** object.| -| getWant(agent: WantAgent, callback: AsyncCallback<Want>): void | Obtains a **WantAgent** object.| -| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void | Checks whether two **WantAgent** objects are equal. | +|getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void | Creates a **WantAgent** object.| +|trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void | Triggers a **WantAgent** object.| +|cancel(agent: WantAgent, callback: AsyncCallback<void>): void | Cancels a **WantAgent** object.| +|getWant(agent: WantAgent, callback: AsyncCallback<Want>): void | Obtains a **WantAgent** object.| +|equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void | Checks whether two **WantAgent** objects are equal.| ## How to Develop @@ -95,7 +96,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ```typescript // Create a NotificationRequest object. - let notificationRequest = { + let notificationRequest: notificationManager.NotificationRequest = { content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { @@ -111,7 +112,7 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ notificationManager.publish(notificationRequest, (err) => { if (err) { - console.error(`[ANS] failed to publish, error[${err}]`); + console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); return; } console.info(`[ANS] publish success`); diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md index de430008e3048532e9afea94d83a62dd2f8342c1..d79f09578a0dc58b0aa53e45b68264f85e67e2c2 100644 --- a/en/application-dev/notification/progress-bar-notification.md +++ b/en/application-dev/notification/progress-bar-notification.md @@ -5,12 +5,11 @@ The progress notification is a commonly used notification type, mainly used to d In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data. - ## Available APIs | Name| Description| | -------- | -------- | -| isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.
Only the progress-type template is supported.| +| isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result. For details, see [isSupportTemplate()](../reference/apis/js-apis-notificationManager.md#notificationmanagerissupporttemplate).
Only the progress-type template is supported.| ## How to Develop @@ -31,17 +30,18 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. // ... }).catch((err) => { - console.error(`[ANS] isSupportTemplate failed, error[${err}]`); + console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`); }); ``` > **NOTE** > > Proceed with the step below only when the specified template is supported. + 4. Create a **NotificationRequest** object and publish a progress notification. ```ts - let notificationRequest = { + let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -61,7 +61,7 @@ In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#n // Publish the notification. notificationManager.publish(notificationRequest, (err) => { if (err) { - console.error(`[ANS] failed to publish, error[${err}]`); + console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); return; } console.info(`[ANS] publish success `); diff --git a/en/application-dev/notification/text-notification.md b/en/application-dev/notification/text-notification.md index ddbc5478cee37208da33d2acecb71417deaccdc2..a9d9bdaaaccc731f0e7cec7e3f7a7e74a3aa41d6 100644 --- a/en/application-dev/notification/text-notification.md +++ b/en/application-dev/notification/text-notification.md @@ -45,7 +45,7 @@ The following table describes the APIs for notification publishing. You specify - A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes. ```ts - let notificationRequest = { + let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification @@ -59,10 +59,10 @@ The following table describes the APIs for notification publishing. You specify notificationManager.publish(notificationRequest, (err) => { if (err) { - console.error(`[ANS] failed to publish, error[${err}]`); + console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); return; } - console.info(`[ANS] publish success`); + console.info(`[ANS] publish success.`); }); ``` @@ -71,7 +71,7 @@ The following table describes the APIs for notification publishing. You specify - In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively. ```ts - let notificationRequest = { + let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification @@ -89,10 +89,10 @@ The following table describes the APIs for notification publishing. You specify // Publish the notification. notificationManager.publish(notificationRequest, (err) => { if (err) { - console.error(`[ANS] failed to publish, error[${err}]`); + console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); return; } - console.info(`[ANS] publish success`); + console.info(`[ANS] publish success.`); }); ``` @@ -101,7 +101,7 @@ The following table describes the APIs for notification publishing. You specify - In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively. ```ts - let notificationRequest = { + let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification @@ -118,7 +118,7 @@ The following table describes the APIs for notification publishing. You specify // Publish the notification. notificationManager.publish(notificationRequest, (err) => { if (err) { - console.error(`[ANS] failed to publish, error[${err}]`); + console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); return; } console.info(`[ANS] publish success`); @@ -131,7 +131,7 @@ The following table describes the APIs for notification publishing. You specify ```ts let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. - let notificationRequest = { + let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, @@ -149,10 +149,10 @@ The following table describes the APIs for notification publishing. You specify // Publish the notification. notificationManager.publish(notificationRequest, (err) => { if (err) { - console.error(`[ANS] failed to publish, error[${err}]`); + console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); return; } - console.info(`[ANS] publish success `); + console.info(`[ANS] publish success.`); }); ``` diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md index 19e6d16258b06b5a2f613a01061fc6a683488ee2..f68ec8ee66f92910e0f11c4a8b705bfd7bbfd08d 100644 --- a/en/application-dev/quick-start/app-configuration-file.md +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -13,12 +13,10 @@ This document gives an overview of the **app.json5** configuration file. To star "icon": "$media:app_icon", "label": "$string:app_name", "description": "$string:description_application", - "distributedNotificationEnabled": true, "minAPIVersion": 9, "targetAPIVersion": 9, "apiReleaseType": "Release", "debug": false, - "entityType": "media", "car": { "minAPIVersion": 8, } @@ -46,9 +44,8 @@ As shown above, the **app.json5** file contains several tags. | minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)| | targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.
- **Canary**: indicates a restricted release.
- **Beta**: indicates a publicly released beta version.
- **Release**: indicates a publicly released official version.
The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| -| distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.
- **true**: Distributed notification is enabled.
- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)| -| entityType | Type of the application. The options are as follows:
- game
- media
- communication
- news
- travel
- utility
- shopping
- education
- kids
- business
- photography
- unspecified| String| Yes (initial value: **"unspecified"**)| -| multiProjects | Whether the application supports joint development of multiple projects.
- **true**: The application supports joint development of multiple projects.
- **false**: The application does not support joint development of multiple projects.| Boolean| Yes (initial value: **false**)| +| multiProjects | Whether the application supports joint development of multiple projects.
- **true**: The application supports joint development of multiple projects.
- **false**: The application does not support joint development of multiple projects. For details about multi-project development, see [Multi-Project Build](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-building-overview-0000001263360495-V3#section71471033104216).| Boolean| Yes (initial value: **false**)| +| assanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.
- **true**: ASan is enabled.
- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)| | tablet | Tablet-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | tv | TV-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| diff --git a/en/application-dev/quick-start/arkts-state-mgmt-application-level.md b/en/application-dev/quick-start/arkts-state-mgmt-application-level.md index 8e1bfd1a19ae568b5db641fb83b1b37e49eeb9c5..08626199bcf5259791b6b571c7ca0c0f9cc35d70 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-application-level.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-application-level.md @@ -123,7 +123,7 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { // storage is passed to the loadContent API as a parameter. - windowStage.loadContent('pages/index', this.storage) + windowStage.loadContent('pages/Index', this.storage) } onWindowStageDestroy() { @@ -143,7 +143,7 @@ export default class EntryAbility extends UIAbility { The **@Component** decorated component obtains data. ```ts -// index.ets +// Index.ets let storage = LocalStorage.GetShared() @Entry(storage) diff --git a/en/application-dev/quick-start/arkts-state-mgmt-page-level.md b/en/application-dev/quick-start/arkts-state-mgmt-page-level.md index 19326001c088a85dee94f3beaff4676db604c4f3..a3a6ec898f89a3cc0f5e9d292eec1f1d53cb93bd 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-page-level.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-page-level.md @@ -494,7 +494,7 @@ struct CompA { this.updateTotal() } - updateTotal(): number { + updateTotal(): void { let sum = 0; this.shopBasket.forEach((i) => { sum += i diff --git a/en/application-dev/quick-start/figures/hap-release.png b/en/application-dev/quick-start/figures/hap-release.png index 527cefcf7e466e105f74065c3d8b59b18802d94b..9c7692a87e3975e01d125893fd276c247743c4e8 100644 Binary files a/en/application-dev/quick-start/figures/hap-release.png and b/en/application-dev/quick-start/figures/hap-release.png differ diff --git a/en/application-dev/quick-start/multi-hap-build-view.md b/en/application-dev/quick-start/multi-hap-build-view.md index 3266828fdbda2b969668410a98ce4b64cce54411..a2c2a530ce1e4edbb4681ff1400398f997c23daa 100644 --- a/en/application-dev/quick-start/multi-hap-build-view.md +++ b/en/application-dev/quick-start/multi-hap-build-view.md @@ -3,25 +3,27 @@ DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below. + **Figure 1** Multi-HAP build view - **Figure 1** Multi-HAP build view ![hap-multi-view](figures/hap-multi-view.png) 1. Development view in DevEco Studio - - AppScope folder - - [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number. + - **AppScope** folder + + - **[app.json5](app-configuration-file.md)**: stores application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number. - **resources** folder: stores application icon resources and application name string resources. - - **NOTE** - - The folder is automatically generated by DevEco Studio and its name cannot be changed. - - The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module directories. Otherwise, DevEco Studio reports an error. - - Entry- or feature-type module directories (the names are customizable) - - You implement service logic of your application in these module directories. In this example, the module folders are **entry.hap** and **feature.hap**. - - **resources** directory: stores the resources used by the module. + + **NOTE** + + - The folder is automatically generated by DevEco Studio and its name cannot be changed. + - The file names in the **AppScope** folder cannot be the same as those in the entry- or feature-type module folder. Otherwise, an error will be reported. + - **entry** or **feature** folder (whose name is customizable) + - A module folder created by the developer by following the creation wizard of DevEco Studio. It stores the service logic implementation of the application. Multiple module folders can be created. In the preceding figure, **entry** and **feature** are two created module folders. + - **resources** folder: stores the resources used by the module. - **ets** folder: stores the service logic. - - [module.json5](module-configuration-file.md): module configuration, such as the module name, entry code path of the module, and component information. - + - **[module.json5](module-configuration-file.md)**: stores module configuration, such as the module name, entry code path of the module, and component information. + 2. View after build and packaging - After a module is built, a HAP file for deployment is generated. Each module corresponds to a HAP file. - The **module.json** file in the HAP file is composed of the **app.json5** and **module.json5** files in the development view. 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 ec688879ebb61ceb595feb974f2276d700479ef5..b4587f2c2125c526b86bfa0646af4b1fcbc9e9d3 100644 --- a/en/application-dev/quick-start/multi-hap-release-deployment.md +++ b/en/application-dev/quick-start/multi-hap-release-deployment.md @@ -6,32 +6,40 @@ Below is the process of developing, debugging, releasing, and deploying multiple ![hap-release](figures/hap-release.png) ## Development -You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules. +You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules as needed and develop services in respective modules. ## Debugging -You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files. +After building code into one or more HAP files and installing or updating these HAP files, you can debug them by using the methods: * Using DevEco Studio for debugging Follow the instructions in [Debugging Configuration](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section10491183521520). -* Using [hdc_std](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) for debugging +* Using [hdc](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) (which can be obtained in the **toolchains** directory of the OpenHarmony SDK) for debugging + + Before debugging HAP files, install or update them using either of the methods: + + 1. Use hdc to install and update the HAP files. + + When specifying the HAP files, use the paths of the files on the operating system, for example, Windows. - You can obtain the hdc_std tool from the **toolchains** directory of the SDK. When using this tool to install an HAP file, the HAP file path is the one on the operating platform. In this example, the Windows operating platform is used. The command reference is as follows: ``` // Installation and update: Multiple file paths can be specified. - hdc_std install C:\entry.hap C:\feature.hap + hdc install C:\entry.hap C:\feature.hap // The execution result is as follows: install bundle successfully. // Uninstall - hdc_std uninstall com.example.myapplication + hdc uninstall com.example.myapplication // The execution result is as follows: uninstall bundle successfully. ``` + + 2. Run the hdc shell command, and then use the Bundle Manager (bm) tool to install and update the HAP files. -* Using [Bundle Manager (bm)](../../application-dev/tools/bm-tool.md) for debugging - - When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows: + When specifying the HAP files, use the paths of the files on the real device. The sample code is as follows: + ``` + // Run the hdc shell command before using the bm tool. + hdc shell // Installation and update: Multiple file paths can be specified. bm install -p /data/app/entry.hap /data/app/feature.hap // The execution result is as follows: @@ -41,6 +49,8 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca // The execution result is as follows: uninstall bundle successfully. ``` + After the HAP files are installed or updated, you can debug them by following the instructions in [Ability Assistant](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/tools/aa-tool.md/). + ## Release 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. diff --git a/en/application-dev/quick-start/multi-hap-rules.md b/en/application-dev/quick-start/multi-hap-rules.md index 34b7824cb62b7e1ca73232faa9f58685df2077ac..7c2675325cfecd0bfd5a6e5595c947daa8e8085d 100644 --- a/en/application-dev/quick-start/multi-hap-rules.md +++ b/en/application-dev/quick-start/multi-hap-rules.md @@ -1,14 +1,14 @@ # Multi-HAP Usage Rules -- The App Pack cannot be directly installed on the device. It is only a unit that is released to AppGallery. +- The App Pack cannot be directly installed on a device. It is only used to be released to the application market. - All HAP files in the App Pack must share the same **bundleName** value in the configuration files. - All HAP files in the App Pack must share the same **versionCode** value in the configuration files. -- In an application, each type of device supports only one HAP of the entry type. Each application can contain zero, one, or more HAP files of the feature type. +- In an App Pack, each type of device supports only one HAP file of the entry type and zero, one, or more HAP files of the feature type. -- Each HAP file in the App Pack must have **moduleName** configured. The **moduleName** value corresponding to all HAP files of the same device type must be unique. +- Each HAP file in the App Pack must have **moduleName** configured. Among HAP files of the same device type, the **moduleName** value must be unique. -- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of all HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, you must ensure that their signing certificates are the same. Otherwise, the installation will fail. +- The signing certificates of all HAP files in the same application must be the same. Applications are released to the application market in the form of App Pack after being signed. Before distribution, the application market splits an App Pack into HAP files and resigns them to ensure the consistency of HAP file signing certificates. Before installing HAP files on a device through the CLI or DevEco Studio for debugging, ensure that their signing certificates are the same. Otherwise, the installation will fail. diff --git a/en/application-dev/quick-start/start-with-ets-fa.md b/en/application-dev/quick-start/start-with-ets-fa.md index 197765c3119690c7529469daa85a045d7c2853fd..23709abc5c2ba7e9b14ef9f396e9731a9f94e136 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -5,7 +5,7 @@ > > To use ArkTS, your DevEco Studio must be V3.0.0.601 Beta1 or later. > -> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. +> For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. ## Creating an ArkTS Project diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index 3bf9d124a666b0ad057310b21e1bf3b52cdf5505..d9527e8fe83bf0173e688296c5cab2e8aff651b8 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -5,7 +5,7 @@ > > To use ArkTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. > -> For best possible results, use [DevEco Studio V3.1.0.100](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. +> For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio) for your development. ## Creating an ArkTS Project diff --git a/en/application-dev/quick-start/start-with-js-fa.md b/en/application-dev/quick-start/start-with-js-fa.md index ad648638defddada7565cc34b2172c67d3050765..7e1123d97f8af188bbb97849551cd6a499042a9f 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -3,7 +3,7 @@ > **NOTE** > -> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. +> For best possible results, use [DevEco Studio 3.1 Beta1](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. ## Creating a JavaScript Project diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 460528d796ced76bd7f37e96f939ffe4cad850a1..beda646d6607e1fe890c64a226950a17759f1831 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -19,16 +19,7 @@ - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](js-apis-application-staticSubscriberExtensionAbility.md) - Stage Model (To Be Deprecated Soon) - - [@ohos.application.Ability (Ability)](js-apis-application-ability.md) - - [@ohos.application.AbilityConstant (AbilityConstant)](js-apis-application-abilityConstant.md) - - [@ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-application-abilityLifecycleCallback.md) - - [@ohos.application.AbilityStage (AbilityStage)](js-apis-application-abilityStage.md) - - [@ohos.application.context (Context)](js-apis-application-context.md) - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md) - - [@ohos.application.ExtensionAbility (ExtensionAbility)](js-apis-application-extensionAbility.md) - - [@ohos.application.FormExtension (FormExtension)](js-apis-application-formExtension.md) - - [@ohos.application.ServiceExtensionAbility (ServiceExtensionAbility)](js-apis-application-serviceExtensionAbility.md) - - [@ohos.application.StartOptions (StartOptions)](js-apis-application-startOptions.md) - FA Model - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) @@ -41,6 +32,7 @@ - [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md) - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md) - [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md) + - [@ohos.app.ability.dialogRequest (dialogRequest)](js-apis-app-ability-dialogRequest.md) - [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md) - [@ohos.app.ability.missionManager (missionManager)](js-apis-app-ability-missionManager.md) - [@ohos.app.ability.quickFixManager (quickFixManager)](js-apis-app-ability-quickFixManager.md) @@ -60,7 +52,6 @@ - [@ohos.application.appManager (appManager)](js-apis-application-appManager.md) - [@ohos.application.Configuration (Configuration)](js-apis-application-configuration.md) - [@ohos.application.ConfigurationConstant (ConfigurationConstant)](js-apis-application-configurationConstant.md) - - [@ohos.application.errorManager (ErrorManager)](js-apis-application-errorManager.md) - [@ohos.application.formBindingData (formBindingData)](js-apis-application-formBindingData.md) - [@ohos.application.formError (FormError)](js-apis-application-formError.md) - [@ohos.application.formHost (FormHost)](js-apis-application-formHost.md) @@ -83,7 +74,6 @@ - [context](js-apis-inner-app-context.md) - [processInfo](js-apis-inner-app-processInfo.md) - application - - [AbilityContext](js-apis-ability-context.md) - [abilityDelegator](js-apis-inner-application-abilityDelegator.md) - [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) - [abilityMonitor](js-apis-inner-application-abilityMonitor.md) @@ -110,10 +100,11 @@ - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) - [ProcessData](js-apis-inner-application-processData.md) - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) - - [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md) + - [ProcessInformation](js-apis-inner-application-processInformation.md) - [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) - [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) - [shellCmdResult](js-apis-inner-application-shellCmdResult.md) + - [WindowExtensionContext](js-apis-inner-application-windowExtensionContext.md) - wantAgent - [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md) - [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) @@ -124,10 +115,12 @@ - [continuationResult](js-apis-continuation-continuationResult.md) - Common Event and Notification + - [System Common Events](commonEventManager-definitions.md) - [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md) - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md) + - [System Common Events (To Be Deprecated Soon)](commonEvent-definitions.md) - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md) - application @@ -152,7 +145,6 @@ - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [metadata](js-apis-bundleManager-metadata.md) - - [packInfo](js-apis-bundleManager-packInfo.md) - [permissionDef](js-apis-bundleManager-permissionDef.md) - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) @@ -185,13 +177,14 @@ - [@ohos.i18n (Internationalization)](js-apis-i18n.md) - [@ohos.intl (Internationalization)](js-apis-intl.md) - [@ohos.resourceManager (Resource Manager)](js-apis-resource-manager.md) -- Resource Scheduling +- Background Tasks - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) + - Security - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) @@ -223,10 +216,11 @@ - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md) - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md) + - [@ohos.file.storageStatistics (Application Storage Statistics)](js-apis-file-storage-statistics.md) + - [@ohos.file.volumeManager (Volume Management)](js-apis-file-volumemanager.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - - [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md) - - [@ohos.volumeManager (Volume Management)](js-apis-volumemanager.md) + - Telephony Service - [@ohos.contact (Contacts)](js-apis-contact.md) - [@ohos.telephony.call (Call)](js-apis-call.md) @@ -278,7 +272,7 @@ - [@ohos.InputMethodSubtype (Input Method Subtype)](js-apis-inputmethod-subtype.md) - [@ohos.pasteboard (Pasteboard)](js-apis-pasteboard.md) - [@ohos.screenLock (Screenlock)](js-apis-screen-lock.md) - - [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md) + - [@ohos.systemDateTime (System Time and Time Zone)](js-apis-system-date-time.md) - [@ohos.systemTimer (System Timer)](js-apis-system-timer.md) - [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md) - [@ohos.web.webview (Webview)](js-apis-webview.md) @@ -286,6 +280,9 @@ - [Timer](js-apis-timer.md) - application - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) + - imf + - [InputMethodCommon](js-apis-inputmethod-InputMethodCommon.md) + - Device Management - [@ohos.batteryInfo (Battery Information)](js-apis-battery-info.md) - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) @@ -310,7 +307,7 @@ - [@ohos.settings (Data Item Settings)](js-apis-settings.md) - [@ohos.stationary (Device Status Awareness Framework)](js-apis-stationary.md) - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - - [@ohos.systemParameterV9 (System Parameter)](js-apis-system-parameterV9.md) + - [@ohos.systemParameterEnhance (System Parameter)](js-apis-system-parameterEnhance.md) - [@ohos.thermal (Thermal Management)](js-apis-thermal.md) - [@ohos.update (Update)](js-apis-update.md) - [@ohos.usbManager (USB Management)](js-apis-usbManager.md) @@ -321,10 +318,11 @@ - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - Custom Management - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) - - [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md) - - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md) + - [@ohos.enterprise.deviceControl (Device Control Management)](js-apis-enterprise-deviceControl.md) + - [@ohos.enterprise.deviceInfo (Device Information Management)](js-apis-enterprise-deviceInfo.md) + - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](js-apis-EnterpriseAdminExtensionAbility.md) - Language Base Class Library - [@ohos.buffer (Buffer)](js-apis-buffer.md) @@ -371,6 +369,8 @@ - [@ohos.reminderAgent (Reminder Agent)](js-apis-reminderAgent.md) - [@ohos.statfs (statfs)](js-apis-statfs.md) - [@ohos.systemParameter (System Parameter)](js-apis-system-parameter.md) + - [@ohos.systemTime (System Time and Time Zone)](js-apis-system-time.md) + - [@ohos.usb (USB Management)](js-apis-usb-deprecated.md) - [@ohos.usbV9 (USB Management)](js-apis-usb.md) - [@system.app (Application Context)](js-apis-system-app.md) - [@system.battery (Battery Information)](js-apis-system-battery.md) diff --git a/en/application-dev/reference/apis/commonEventManager-definitions.md b/en/application-dev/reference/apis/commonEventManager-definitions.md index 9c1d2081d8a631b8f5b963924d66dc5aa688eb99..3701910204a1a924986d9d6ff8ae144886cc5856 100644 --- a/en/application-dev/reference/apis/commonEventManager-definitions.md +++ b/en/application-dev/reference/apis/commonEventManager-definitions.md @@ -921,3 +921,7 @@ Indicates that the SPN displayed has been updated. Indicates the result of applying a quick fix to the application. - Value: **usual.event.QUICK_FIX_APPLY_RESULT** - Required subscriber permissions: none +## COMMON_EVENT_HTTP_PROXY_CHANGE10+ +Indicates that the HTTP proxy configuration has changed. +- Value: **usual.event.HTTP_PROXY_CHANGE** +- Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 5908fc527c4d6f1c1a3391671a0ac9dcc4b41d6f..f537fc5fe11a199afab4821b29b199499faa6c97 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1230,7 +1230,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ----------------------- | | info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ability is enabled, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -1603,7 +1603,7 @@ bundle.getNameForUid(uid, (err, data) => { ## bundle.getAbilityIcon8+ deprecated -> This API is deprecated since API version 9. You are advised to use [bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon) instead. +> This API is deprecated since API version 9. You are advised to use [resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9) instead. getAbilityIcon(bundleName: string, abilityName: string): Promise\; @@ -1646,7 +1646,7 @@ bundle.getAbilityIcon(bundleName, abilityName) ## bundle.getAbilityIcon8+ deprecated -> This API is deprecated since API version 9. You are advised to use [bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon) instead. +> This API is deprecated since API version 9. You are advised to use [resourceManager.getMediaContent](js-apis-resource-manager.md#getmediacontent9) instead. getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; diff --git a/en/application-dev/reference/apis/js-apis-ability-ability.md b/en/application-dev/reference/apis/js-apis-ability-ability.md index 37bf04c704a91f0580fddf99b14f9f52fb94d683..fe5b7cfde18961802383469c3d2558f8c8381f67 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -10,7 +10,7 @@ The **Ability** module provides all level-2 module APIs for developers to export ## Modules to Import ```ts -import ability from '@ohos.ability.ability' +import ability from '@ohos.ability.ability'; ``` **System capability**: SystemCapability.Ability.AbilityBase diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md deleted file mode 100644 index d345bbb9db0739da16156ecfc0bd4fe344989149..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ /dev/null @@ -1,1921 +0,0 @@ -# AbilityContext - -The **AbilityContext** module, inherited from **Context**, implements the context for abilities. - -This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box. - -> **NOTE** -> -> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module can be used only in the stage model. - -## Usage - -Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. - -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -let context = undefined; -class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - context = this.context; - } -} -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.| -| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.| -| config | [Configuration](js-apis-application-configuration.md) | Yes| No| Configuration information.| - -## AbilityContext.startAbility - -startAbility(want: Want, callback: AsyncCallback<void>): void; - -Starts an ability. This API uses an asynchronous callback to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - bundleName: "com.example.myapplication", - abilityName: "MyAbility" - }; - - try { - this.context.startAbility(want, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbility - -startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; - -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbility(want, options, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startAbility - -startAbility(want: Want, options?: StartOptions): Promise<void>; - -Starts an ability. This API uses a promise to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - bundleName: "com.example.myapplication", - abilityName: "MyAbility" - }; - var options = { - windowMode: 0, - }; - - try { - this.context.startAbility(want, options) - .then((data) => { - // Carry out normal service processing. - console.log('startAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; - -Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - - try { - this.context.startAbilityForResult(want, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + - result.resultCode) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; - -Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var options = { - windowMode: 0, - }; - - try { - this.context.startAbilityForResult(want, options, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + - result.resultCode) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; - -Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| - - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - bundleName: "com.example.myapplication", - abilityName: "MyAbility" - }; - var options = { - windowMode: 0, - }; - - try { - this.context.startAbilityForResult(want, options) - .then((result) => { - // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startAbilityForResultWithAccount - -startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; - -Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)\> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - - try { - this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbilityForResultWithAccount - -startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; - -Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbilityForResultWithAccount - -startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; - -Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityForResultWithAccount(want, accountId, options) - .then((result) => { - // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` -## AbilityContext.startServiceExtensionAbility - -startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; - -Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - - try { - this.context.startServiceExtensionAbility(want, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startServiceExtensionAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startServiceExtensionAbility - -startServiceExtensionAbility(want: Want): Promise\; - -Starts a ServiceExtensionAbility. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - - try { - this.context.startServiceExtensionAbility(want) - .then((data) => { - // Carry out normal service processing. - console.log('startServiceExtensionAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startServiceExtensionAbilityWithAccount - -startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; - -Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - - try { - this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startServiceExtensionAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startServiceExtensionAbilityWithAccount - -startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; - -Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - - try { - this.context.startServiceExtensionAbilityWithAccount(want, accountId) - .then((data) => { - // Carry out normal service processing. - console.log('startServiceExtensionAbilityWithAccount succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` -## AbilityContext.stopServiceExtensionAbility - -stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; - -Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - - try { - this.context.startAbility(want, (error) => { - if (error.code != 0) { - console.log("start ability fail, err: " + JSON.stringify(err)); - } - }) - - this.context.stopServiceExtensionAbility(want, (error) => { - if (error.code != 0) { - // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('stopServiceExtensionAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.stopServiceExtensionAbility - -stopServiceExtensionAbility(want: Want): Promise\; - -Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - - try { - this.context.startAbility(want, (error) => { - if (error.code != 0) { - console.log("start ability fail, err: " + JSON.stringify(err)); - } - }) - - this.context.stopServiceExtensionAbility(want) - .then((data) => { - // Carry out normal service processing. - console.log('stopServiceExtensionAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.stopServiceExtensionAbilityWithAccount - -stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; - -Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - - try { - this.context.startAbilityWithAccount(want, accountId, (error) => { - if (error.code != 0) { - console.log("start ability fail, err: " + JSON.stringify(err)); - } - }) - - this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { - if (error.code) { - // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('stopServiceExtensionAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.stopServiceExtensionAbilityWithAccount - -stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; - -Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - - try { - this.context.startAbilityWithAccount(want, accountId, (error) => { - if (error.code != 0) { - console.log("start ability fail, err: " + JSON.stringify(err)); - } - }) - - this.context.stopServiceExtensionAbilityWithAccount(want, accountId) - .then((data) => { - // Carry out normal service processing. - console.log('stopServiceExtensionAbilityWithAccount succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.terminateSelf - -terminateSelf(callback: AsyncCallback<void>): void; - -Terminates this ability. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - this.context.terminateSelf((error) => { - if (error.code) { - // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('terminateSelf succeed'); - }); - ``` - - -## AbilityContext.terminateSelf - -terminateSelf(): Promise<void>; - -Terminates this ability. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - this.context.terminateSelf().then((data) => { - // Carry out normal service processing. - console.log('terminateSelf succeed'); - }).catch((error) => { - // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - ``` - - -## AbilityContext.terminateSelfWithResult - -terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; - -Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" - } - var resultCode = 100; - // AbilityResult information returned to the caller. - var abilityResult = { - want, - resultCode - } - - try { - this.context.terminateSelfWithResult(abilityResult, (error) => { - if (error.code) { - // Process service logic errors. - console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('terminateSelfWithResult succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.terminateSelfWithResult - -terminateSelfWithResult(parameter: AbilityResult): Promise<void>; -Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - - -**Example** - - ```ts - var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" - } - var resultCode = 100; - // AbilityResult information returned to the caller. - var abilityResult = { - want, - resultCode - } - - try { - this.context.terminateSelfWithResult(abilityResult) - .then((data) => { - // Carry out normal service processing. - console.log('terminateSelfWithResult succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.connectServiceExtensionAbility - -connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; - -Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Parameters for the connection.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Result code of the ability connection.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } - } - - var connection = null; - try { - connection = this.context.connectServiceExtensionAbility(want, options); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.connectServiceExtensionAbilityWithAccount - -connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; - -Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability with the account ID specified. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Parameters for the connection.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Result code of the ability connection.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } - } - - var connection = null; - try { - connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.disconnectServiceExtensionAbility - -disconnectServiceExtensionAbility(connection: number): Promise\; - -Disconnects a connection. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| connection | number | Yes| Result code of the ability connection.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - // connection is the return value of connectServiceExtensionAbility. - var connection = 1; - - try { - this.context.disconnectServiceExtensionAbility(connection) - .then((data) => { - // Carry out normal service processing. - console.log('disconnectServiceExtensionAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.disconnectServiceExtensionAbility - -disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; - -Disconnects a connection. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| connection | number | Yes| Result code of the ability connection.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - // connection is the return value of connectServiceExtensionAbility. - var connection = 1; - - try { - this.context.disconnectServiceExtensionAbility(connection, (error) => { - if (error.code) { - // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('disconnectServiceExtensionAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startAbilityByCall - -startAbilityByCall(want: Want): Promise<Caller>; - -Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<Caller> | Promise used to return the caller object to communicate with.| - -**Example** - - Start an ability in the background. - - ```ts - var caller = undefined; - - // Start an ability in the background by not passing parameters. - var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "EntryAbility", - deviceId: "" - }; - - try { - this.context.startAbilityByCall(wantBackground) - .then((obj) => { - // Carry out normal service processing. - caller = obj; - console.log('startAbilityByCall succeed'); - }).catch((error) => { - // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - Start an ability in the foreground. - - ```ts - var caller = undefined; - - // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. - var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "EntryAbility", - deviceId: "", - parameters: { - "ohos.aafwk.param.callAbilityToForeground": true - } - }; - - try { - this.context.startAbilityByCall(wantForeground) - .then((obj) => { - // Carry out normal service processing. - caller = obj; - console.log('startAbilityByCall succeed'); - }).catch((error) => { - // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.startAbilityWithAccount - -startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; - -Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - - try { - this.context.startAbilityWithAccount(want, accountId, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbilityWithAccount - -startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; - -Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityWithAccount(want, accountId, options, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - - -## AbilityContext.startAbilityWithAccount - -startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; - -Starts an ability with the account ID specified. This API uses a promise to return the result. - -Observe the following when using this API: - - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. - - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | If the input parameter is not valid parameter. | - -For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - -**Example** - - ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityWithAccount(want, accountId, options) - .then((data) => { - // Carry out normal service processing. - console.log('startAbilityWithAccount succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } - ``` - -## AbilityContext.setMissionLabel - -setMissionLabel(label: string, callback:AsyncCallback<void>): void; - -Sets a label for this ability in the mission. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| label | string | Yes| Label of the ability to set.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```ts - this.context.setMissionLabel("test",(result) => { - console.log('setMissionLabel result:' + JSON.stringify(result)); - }); - ``` - - -## AbilityContext.setMissionLabel - -setMissionLabel(label: string): Promise<void>; - -Sets a label for this ability in the mission. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| label | string | Yes| Label of the ability to set.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - - ```ts - this.context.setMissionLabel("test").then(() => { - console.log('success'); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` -## AbilityContext.setMissionIcon - -setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; - -Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Example** - - ```ts - import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { - size: { - height: 100, - width: 100 - } - }; - image.createPixelMap(color, initializationOptions) - .then((data) => { - imagePixelMap = data; - }) - .catch((err) => { - console.log('--------- createPixelMap fail, err: ---------', err) - }); - this.context.setMissionIcon(imagePixelMap, (err) => { - console.log('---------- setMissionIcon fail, err: -----------', err); - }) - ``` - - -## AbilityContext.setMissionIcon - -setMissionIcon(icon: image.PixelMap): Promise\; - -Sets an icon for this ability in the mission. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - - ```ts - import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { - size: { - height: 100, - width: 100 - } - }; - image.createPixelMap(color, initializationOptions) - .then((data) => { - imagePixelMap = data; - }) - .catch((err) => { - console.log('--------- createPixelMap fail, err: ---------', err) - }); - this.context.setMissionIcon(imagePixelMap) - .then(() => { - console.log('-------------- setMissionIcon success -------------'); - }) - .catch((err) => { - console.log('-------------- setMissionIcon fail, err: -------------', err); - }); - ``` -## AbilityContext.restoreWindowStage - -restoreWindowStage(localStorage: LocalStorage) : void; - -Restores the window stage data for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| localStorage | LocalStorage | Yes| Storage used to store the restored window stage.| - -**Example** - - ```ts - var storage = new LocalStorage(); - this.context.restoreWindowStage(storage); - ``` - -## AbilityContext.isTerminating - -isTerminating(): boolean; - -Checks whether this ability is in the terminating state. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean| The value **true** means that the ability is in the terminating state, and **false** means the opposite.| - -**Example** - - ```ts - var isTerminating = this.context.isTerminating(); - console.log('ability state :' + isTerminating); - ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md index f1301ad877dcf5a0bd2fec5ad5be10452ee88716..8a0b0ad7dd28d300aefd6d263cc41618071e011f 100644 --- a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -1,4 +1,4 @@ -# @ohos.ability.dataUriUtils (dataUriUtils) +# @ohos.ability.dataUriUtils (DataUriUtils) The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module. @@ -35,7 +35,7 @@ Obtains the ID attached to the end of a given URI. **Example** ```ts -let id = dataUriUtils.getId("com.example.dataUriUtils/1221"); +let id = dataUriUtils.getId('com.example.dataUriUtils/1221'); ``` @@ -66,9 +66,9 @@ Attaches an ID to the end of a given URI. ```ts let id = 1122; let uri = dataUriUtils.attachId( - "com.example.dataUriUtils", + 'com.example.dataUriUtils', id, -) +); ``` @@ -96,7 +96,7 @@ Deletes the ID from the end of a given URI. **Example** ```ts -let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") +let uri = dataUriUtils.deleteId('com.example.dataUriUtils/1221'); ``` @@ -127,7 +127,7 @@ Updates the ID in a given URI. ```ts let id = 1122; let uri = dataUriUtils.updateId( - "com.example.dataUriUtils/1221", + 'com.example.dataUriUtils/1221', id -) +); ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md index dc0e8ae8928a9191f70b555e84a3f58b09e4b876..143a2344a935a013e664bde170ef615e0f6acfba 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -9,7 +9,7 @@ The **ErrorCode** module defines the error codes that may be returned when an ab ## Modules to Import ```ts -import errorCode from '@ohos.ability.errorCode' +import errorCode from '@ohos.ability.errorCode'; ``` ## ErrorCode diff --git a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md index b527edfcf7911fec83b4e8d5a01a2761772e95f1..836f07ef61ee7b5801fe86b3dbbaed72c017e466 100644 --- a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -41,24 +41,24 @@ Observe the following when using this API: ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbility( { want: { - action: "", - entities: [""], - type: "", + action: '', + entities: [''], + type: '', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.myapplication", + deviceId: '', + bundleName: 'com.example.myapplication', /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.myapplication.secondAbility", - uri: "" + abilityName: 'com.example.myapplication.secondAbility', + uri: '' }, }, (err, data) => { - console.info("startAbility err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('startAbility err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); } ); ``` @@ -94,24 +94,24 @@ Observe the following when using this API: ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbility( { want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.myapplication", + deviceId: '', + bundleName: 'com.example.myapplication', /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.myapplication.secondAbility", - uri: "" + abilityName: 'com.example.myapplication.secondAbility', + uri: '' }, } ).then((data) => { - console.info("startAbility data: " + JSON.stringify(data)); + console.info('startAbility data: ${JSON.stringify(data)}'); }); ``` @@ -145,8 +145,8 @@ Observe the following when using this API: ```ts import featureAbility from '@ohos.ability.featureAbility'; -var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); ``` @@ -154,7 +154,10 @@ var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. The following situations may be possible for a started ability: + - Normally, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability. The result is returned to the caller. + - If an exception occurs, for example, the ability is killed, an exception message, in which **resultCode** is **-1**, is returned to the caller. + - If different applications call this API to start an ability that uses the sington mode and then call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -174,24 +177,24 @@ Observe the following when using this API: ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbilityForResult( { want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.myapplication", + deviceId: '', + bundleName: 'com.example.myapplication', /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.myapplication.secondAbility", - uri:"" + abilityName: 'com.example.myapplication.secondAbility', + uri:'' }, }, (err, data) => { - console.info("startAbilityForResult err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('startAbilityForResult err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); } ); ``` @@ -200,7 +203,10 @@ featureAbility.startAbilityForResult( startAbilityForResult(parameter: StartAbilityParameter): Promise\ -Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. +Starts an ability. This API uses a promise to return the result when the ability is terminated. The following situations may be possible to an ability after it is started: + - Normally, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability. The result is returned to the caller. + - If an exception occurs, for example, the ability is killed, an exception message, in which **resultCode** is **-1**, is returned to the caller. + - If different applications call this API to start an ability that uses the sington mode and then call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability, the normal result is returned to the last caller, and an exception message, in which **resultCode** is **-1**, is returned to others. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -225,35 +231,35 @@ Observe the following when using this API: ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.startAbilityForResult( { want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.myapplication", + deviceId: '', + bundleName: 'com.example.myapplication', /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.myapplication.secondAbility", - uri:"", + abilityName: 'com.example.myapplication.secondAbility', + uri:'', parameters: { mykey0: 1111, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "xxxxxxxxxxxxxxxxxxxxxx", + mykey2: '[1, 2, 3]', + mykey3: 'xxxxxxxxxxxxxxxxxxxxxx', mykey4: [1, 15], mykey5: [false, true, false], - mykey6: ["aaaaaa", "bbbbb", "ccccccccccc"], + mykey6: ['aaaaaa', 'bbbbb', 'ccccccccccc'], mykey7: true, }, }, }, ).then((data) => { - console.info("startAbilityForResult data: " + JSON.stringify(data)); + console.info('startAbilityForResult data: ${JSON.stringify(data)}'); }); ``` @@ -276,35 +282,35 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.terminateSelfWithResult( { resultCode: 1, want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.myapplication", + deviceId: '', + bundleName: 'com.example.myapplication', /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.myapplication.secondAbility", - uri:"", + abilityName: 'com.example.myapplication.secondAbility', + uri:'', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [1, 15], mykey5: [false, true, false], - mykey6: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey7: true, } }, }, (err) => { - console.info("err: " + JSON.stringify(err)) + console.error('err: ${JSON.stringify(err)}'); } ); ``` @@ -333,35 +339,35 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe ```ts import featureAbility from '@ohos.ability.featureAbility'; -import wantConstant from '@ohos.ability.wantConstant'; +import wantConstant from '@ohos.app.ability.wantConstant'; featureAbility.terminateSelfWithResult( { resultCode: 1, want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.myapplication", + deviceId: '', + bundleName: 'com.example.myapplication', /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.myapplication.secondAbility", - uri:"", + abilityName: 'com.example.myapplication.secondAbility', + uri:'', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [1, 15], mykey5: [false, true, false], - mykey6: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey7: true, } }, } ).then((data) => { - console.info("==========================>terminateSelfWithResult=======================>"); + console.info('==========================>terminateSelfWithResult=======================>'); }); ``` @@ -384,7 +390,7 @@ Checks whether the main window of this ability has the focus. This API uses an a ```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus((err, data) => { - console.info("hasWindowFocus err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('hasWindowFocus err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -407,7 +413,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr ```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus().then((data) => { - console.info("hasWindowFocus data: " + JSON.stringify(data)); + console.info('hasWindowFocus data: ${JSON.stringify(data)}'); }); ``` @@ -430,7 +436,7 @@ Obtains the Want corresponding to the ability to start. This API uses an asynchr ```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant((err, data) => { - console.info("getWant err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getWant err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -453,7 +459,7 @@ Obtains the Want corresponding to the ability to start. This API uses a promise ```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant().then((data) => { - console.info("getWant data: " + JSON.stringify(data)); + console.info('getWant data: ${JSON.stringify(data)}'); }); ``` @@ -475,9 +481,9 @@ Obtains the application context. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext() +let context = featureAbility.getContext(); context.getBundleName((err, data) => { - console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getBundleName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -501,7 +507,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf( (err) => { - console.info("err: " + JSON.stringify(err)) + console.error('err: ${JSON.stringify(err)}'); } ) ``` @@ -525,7 +531,7 @@ Terminates this ability. This API uses a promise to return the result. ```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf().then((data) => { - console.info("==========================>terminateSelf=======================>"); + console.info('==========================>terminateSelf=======================>'); }); ``` @@ -562,19 +568,19 @@ Observe the following when using this API: import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); + console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}'); } function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) + console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}') } function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) + console.log('featureAbilityTest ConnectAbility onFailed errCode : ${code}') } -var connectId = featureAbility.connectAbility( +let connectId = featureAbility.connectAbility( { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "com.ix.ServiceAbility.ServiceAbilityA", + deviceId: '', + bundleName: 'com.ix.ServiceAbility', + abilityName: 'com.ix.ServiceAbility.ServiceAbilityA', }, { onConnect: onConnectCallback, @@ -605,18 +611,18 @@ Disconnects this ability from a specific ServiceAbility. This API uses an asynch import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); + console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}'); } function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) + console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) + console.log('featureAbilityTest ConnectAbility onFailed errCode : ${code}'); } -var connectId = featureAbility.connectAbility( +let connectId = featureAbility.connectAbility( { - bundleName: "com.ix.ServiceAbility", - abilityName: "com.ix.ServiceAbility.ServiceAbilityA", + bundleName: 'com.ix.ServiceAbility', + abilityName: 'com.ix.ServiceAbility.ServiceAbilityA', }, { onConnect: onConnectCallback, @@ -624,11 +630,10 @@ var connectId = featureAbility.connectAbility( onFailed: onFailedCallback, }, ); -var result = featureAbility.disconnectAbility(connectId, - (error) => { - console.log('featureAbilityTest DisConnectJsSameBundleName result errCode : ' + error.code) - }, -); + +featureAbility.disconnectAbility(connectId, (err) => { + console.error('featureAbilityTest disconnectAbility err: ${JSON.stringify(err)}'); +}); ``` ## featureAbility.disconnectAbility7+ @@ -657,18 +662,18 @@ Disconnects this ability from a specific ServiceAbility. This API uses a promise import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); + console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}'); } function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) + console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) + console.log('featureAbilityTest ConnectAbility onFailed errCode : ${code}'); } -var connectId = featureAbility.connectAbility( +let connectId = featureAbility.connectAbility( { - bundleName: "com.ix.ServiceAbility", - abilityName: "com.ix.ServiceAbility.ServiceAbilityA", + bundleName: 'com.ix.ServiceAbility', + abilityName: 'com.ix.ServiceAbility.ServiceAbilityA', }, { onConnect: onConnectCallback, @@ -678,9 +683,9 @@ var connectId = featureAbility.connectAbility( ); featureAbility.disconnectAbility(connectId).then((data) => { - console.log('data : ' + data); + console.log('data: ${data)}'; }).catch((error)=>{ - console.log('featureAbilityTest result errCode : ' + error.code); + console.error('featureAbilityTest result errCode : ${error.code}'); }); ``` @@ -703,7 +708,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous ```ts featureAbility.getWindow((err, data) => { - console.info("getWindow err: " + JSON.stringify(err) + "data: " + typeof(data)); + console.info('getWindow err: ${JSON.stringify(err)}, data: ${typeof(data)}'); }); ``` @@ -725,7 +730,7 @@ Obtains the window corresponding to this ability. This API uses a promise to ret ```ts featureAbility.getWindow().then((data) => { - console.info("getWindow data: " + typeof(data)); + console.info('getWindow data: ${typeof(data)}'); }); ``` @@ -745,8 +750,8 @@ featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED | ---------------------------------------- | ---- | ---------------------------------------- | | WINDOW_MODE_UNDEFINED7+ | 0 | The PageAbility is in an undefined window display mode.| | WINDOW_MODE_FULLSCREEN7+ | 1 | The PageAbility is in full screen mode. | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The PageAbility is displayed in the primary window when it is in split-screen mode.| -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The PageAbility is displayed in the secondary window when it is in split-screen mode.| +| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The left screen in horizontal direction or the upper screen in vertical direction is the primary window.| +| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The right screen in horizontal direction or the lower screen in vertical direction is the secondary window.| | WINDOW_MODE_FLOATING7+ | 102 | The PageAbility is displayed in floating window mode.| @@ -766,9 +771,9 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY | Name | Value | Description | | ---------------------------- | --------------- | ---------------------------------------- | -| BOUNDS_KEY7+ | "abilityBounds" | Ability window size.| -| WINDOW_MODE_KEY7+ | "windowMode" | Ability window display mode.| -| DISPLAY_ID_KEY7+ | "displayId" | Display device ID.| +| BOUNDS_KEY7+ | 'abilityBounds' | Ability window size.| +| WINDOW_MODE_KEY7+ | 'windowMode' | Ability window display mode.| +| DISPLAY_ID_KEY7+ | 'displayId' | Display device ID.| ## ErrorCode diff --git a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md index 846aefcd37eff322c5d5aa215bad3f812da6ed4d..d4c5a739a80f7976f1581454423cc8c4d824035d 100644 --- a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -14,7 +14,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat ## Modules to Import ```ts -import particleAbility from '@ohos.ability.particleAbility' +import particleAbility from '@ohos.ability.particleAbility'; ``` ## particleAbility.startAbility @@ -40,27 +40,27 @@ Observe the following when using this API: **Example** ```ts -import particleAbility from '@ohos.ability.particleAbility' -import wantConstant from '@ohos.ability.wantConstant' +import particleAbility from '@ohos.ability.particleAbility'; +import wantConstant from '@ohos.ability.wantConstant'; particleAbility.startAbility( { want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.Data", - abilityName: "EntryAbility", - uri: "" + deviceId: '', + bundleName: 'com.example.Data', + abilityName: 'EntryAbility', + uri: '' }, }, (error, result) => { - console.log('particleAbility startAbility errCode:' + error + 'result:' + result) + console.error('particleAbility startAbility errCode: ${JSON.stringify(error)}, result: ${JSON.stringify(result)}'); }, -) +); ``` ## particleAbility.startAbility @@ -91,25 +91,25 @@ Observe the following when using this API: **Example** ```ts -import particleAbility from '@ohos.ability.particleAbility' -import wantConstant from '@ohos.ability.wantConstant' +import particleAbility from '@ohos.ability.particleAbility'; +import wantConstant from '@ohos.ability.wantConstant'; particleAbility.startAbility( { want: { - action: "action.system.home", - entities: ["entity.system.home"], - type: "MIMETYPE", + action: 'action.system.home', + entities: ['entity.system.home'], + type: 'MIMETYPE', flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - deviceId: "", - bundleName: "com.example.Data", - abilityName: "EntryAbility", - uri: "" + deviceId: '', + bundleName: 'com.example.Data', + abilityName: 'EntryAbility', + uri: '' }, }, ).then((data) => { - console.info("particleAbility startAbility"); + console.info('particleAbility startAbility'); }); ``` @@ -130,13 +130,13 @@ Terminates this ParticleAbility. This API uses an asynchronous callback to retur **Example** ```ts -import particleAbility from '@ohos.ability.particleAbility' +import particleAbility from '@ohos.ability.particleAbility'; particleAbility.terminateSelf( (error, result) => { - console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) + console.log('particleAbility terminateSelf errCode: ${JSON.stringify(error)}, result: ${JSON.stringify(result)}'); } -) +); ``` ## particleAbility.terminateSelf @@ -156,10 +156,10 @@ Terminates this ParticleAbility. This API uses a promise to return the result. **Example** ```ts -import particleAbility from '@ohos.ability.particleAbility' +import particleAbility from '@ohos.ability.particleAbility'; particleAbility.terminateSelf().then((data) => { - console.info("particleAbility terminateSelf"); + console.info('particleAbility terminateSelf'); }); ``` @@ -194,10 +194,10 @@ Observe the following when using this API: **Example** ```ts -import particleAbility from '@ohos.ability.particleAbility' +import particleAbility from '@ohos.ability.particleAbility'; -var uri = ""; -particleAbility.acquireDataAbilityHelper(uri) +let uri = ''; +particleAbility.acquireDataAbilityHelper(uri); ``` @@ -228,17 +228,17 @@ import wantAgent from '@ohos.app.ability.wantAgent'; function callback(err, data) { if (err) { - console.error("Operation failed cause: " + JSON.stringify(err)); + console.error('Operation failed cause: ${JSON.stringify(err)}'); } else { - console.info("Operation succeeded"); + console.info('Operation succeeded'); } } let wantAgentInfo = { wants: [ { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -248,8 +248,8 @@ let wantAgentInfo = { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { let basicContent = { - title: "title", - text: "text" + title: 'title', + text: 'text' }; let notificationContent = { contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -298,8 +298,8 @@ import wantAgent from '@ohos.app.ability.wantAgent'; let wantAgentInfo = { wants: [ { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -309,8 +309,8 @@ let wantAgentInfo = { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { let basicContent = { - title: "title", - text: "text" + title: 'title', + text: 'text' }; let notificationContent = { contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -322,9 +322,9 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { }; let id = 1; particleAbility.startBackgroundRunning(id, request).then(() => { - console.info("Operation succeeded"); + console.info('Operation succeeded'); }).catch((err) => { - console.error("Operation failed cause: " + JSON.stringify(err)); + console.error('Operation failed cause: ${JSON.stringify(err)}'); }); }); @@ -351,9 +351,9 @@ import particleAbility from '@ohos.ability.particleAbility'; function callback(err, data) { if (err) { - console.error("Operation failed cause: " + JSON.stringify(err)); + console.error('Operation failed cause: ${JSON.stringify(err)}'); } else { - console.info("Operation succeeded"); + console.info('Operation succeeded'); } } @@ -381,9 +381,9 @@ Requests to cancel a continuous task from the system. This API uses a promise to import particleAbility from '@ohos.ability.particleAbility'; particleAbility.cancelBackgroundRunning().then(() => { - console.info("Operation succeeded"); + console.info('Operation succeeded'); }).catch((err) => { - console.error("Operation failed cause: " + JSON.stringify(err)); + console.error('Operation failed cause: ${JSON.stringify(err)}'); }); ``` @@ -413,25 +413,25 @@ Observe the following when using this API: **Example** ```ts -import particleAbility from '@ohos.ability.particleAbility' -import rpc from '@ohos.rpc' +import particleAbility from '@ohos.ability.particleAbility'; +import rpc from '@ohos.rpc'; function onConnectCallback(element, remote) { - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); + console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}'); } function onDisconnectCallback(element) { - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) + console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code) { - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) + console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}'); } -var connId = particleAbility.connectAbility( +let connId = particleAbility.connectAbility( { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + bundleName: 'com.ix.ServiceAbility', + abilityName: 'ServiceAbilityA', }, { onConnect: onConnectCallback, @@ -441,9 +441,9 @@ var connId = particleAbility.connectAbility( ); particleAbility.disconnectAbility(connId).then((data) => { - console.log(" data: " + data); + console.log(' data: ${data}'); }).catch((error) => { - console.log('particleAbilityTest result errCode : ' + error.code) + console.log('particleAbilityTest result errCode : ${error.code}'); }); ``` @@ -468,21 +468,21 @@ import particleAbility from '@ohos.ability.particleAbility'; import rpc from '@ohos.rpc'; function onConnectCallback(element, remote) { - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); + console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}'); } function onDisconnectCallback(element) { - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) + console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code) { - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) + console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}'); } -var connId = particleAbility.connectAbility( +let connId = particleAbility.connectAbility( { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + bundleName: 'com.ix.ServiceAbility', + abilityName: 'ServiceAbilityA', }, { onConnect: onConnectCallback, @@ -492,8 +492,7 @@ var connId = particleAbility.connectAbility( ); particleAbility.disconnectAbility(connId, (err) => { - console.log("particleAbilityTest disconnectAbility err====>" - + ("json err=") + JSON.stringify(err)); + console.log('particleAbilityTest disconnectAbility err: ${JSON.stringify(err)}'); }); ``` @@ -519,21 +518,21 @@ import particleAbility from '@ohos.ability.particleAbility'; import rpc from '@ohos.rpc'; function onConnectCallback(element, remote) { - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); + console.log('ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}'); } function onDisconnectCallback(element) { - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) + console.log('ConnectAbility onDisconnect element.deviceId : ${element.deviceId}'); } function onFailedCallback(code) { - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) + console.log('particleAbilityTest ConnectAbility onFailed errCode : ${code}'); } -var connId = particleAbility.connectAbility( +let connId = particleAbility.connectAbility( { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + bundleName: 'com.ix.ServiceAbility', + abilityName: 'ServiceAbilityA', }, { onConnect: onConnectCallback, @@ -543,9 +542,9 @@ var connId = particleAbility.connectAbility( ); particleAbility.disconnectAbility(connId).then((data) => { - console.log(" data: " + data); + console.log(' data: ${data}'); }).catch((error) => { - console.log('particleAbilityTest result errCode : ' + error.code) + console.log('particleAbilityTest result errCode : ${error.code}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 87b52688c5bec0a80bc44d9c8dcba63fe00283f2..776faa162b5178cec3bf003aedc018c17ab17084 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. **action** specifies the | INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | | INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. | | ACTION_FILE_SELECT7+ | ohos.action.fileSelect | Action of selecting a file. | -| PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. | +| PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. The value must be an array of the string type. | | ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | | ACTION_APP_ACCOUNT_AUTH 9+ | account.appAccount.action.auth | Action of providing the authentication service. | | ACTION_MARKET_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index febd683936b841caf9b7b44511ee18370761ca42..3aaf9f11af2349900af865eb977f493bec8c343b 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -37,10 +37,10 @@ Creates an **Animator** object. ```js let options = { duration: 1500, - easing: 'friction', + easing: "friction", delay: 0, - fill: 'forwards', - direction: 'normal', + fill: "forwards", + direction: "normal", iterations: 3, begin: 200.0, end: 400.0 @@ -80,10 +80,10 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro ```js let options = { duration: 1500, - easing: 'friction', + easing: "friction", delay: 0, - fill: 'forwards', - direction: 'normal', + fill: "forwards", + direction: "normal", iterations: 3, begin: 200.0, end: 400.0 @@ -99,7 +99,7 @@ try { play(): void -Plays this animation. +Plays this animation. The animation retains the previous playback state. For example, if the animation is set to **reverse** and paused, it will remain in **reverse** when resumed. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -247,16 +247,16 @@ Defines animator options. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | -| duration | number | Yes | Duration for playing the animation, in milliseconds. The default value is **0**. | -| easing | string | Yes | Animation interpolation curve. The default value is **ease**. | -| delay | number | Yes | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. | -| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed.| -| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode. The default value is **normal**. | -| iterations | number | Yes | Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times. | -| begin | number | Yes | Start point of the animation interpolation. The default value is 0. | -| end | number | Yes | End point of animation interpolation. The default value is 1. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| duration | number | Yes | Duration for playing the animation, in milliseconds. | +| easing | string | Yes | Animation interpolation curve. Only the following values are supported:
**"linear"**: The animation speed keeps unchanged.
**"ease"**: The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.
**"ease-in"**: The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.
**"ease-out"**: The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.
**"ease-in-out"**: The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.
**"fast-out-slow-in"**: The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).
**"linear-out-slow-in"**: The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).
**"friction"**: The animation uses the damping cubic-bezier curve (0.2, 0.0, 0.2, 1.0).
**"extreme-deceleration"**: The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).
**"rhythm"**: The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).
**"sharp"**: The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).
**"smooth"**: The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).
**cubic-bezier(x1, y1, x2, y2)**: The animation uses the defined cubic-bezier curve, where the value of the input parameters must range from 0 to 1.
**steps(number, step-position)**: The animation uses a step curve. The **number** must be set and only an integer is supported. **step-position** is optional. It can be set to **start** or **end**. The default value is **end**.| +| delay | number | Yes | Animation delay duration, in milliseconds. Value **0** means that there is no delay. | +| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed.
**"none"**: No style is applied to the target before or after the animation is executed.
**"forwards"**: The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed.
**"backwards"**: The animation uses the value defined in the first key frame during the **animation-delay**. When **animation-direction** is set to **normal** or **alternate**, the value in the **from** key frame is used. When **animation-direction** is set to **reverse** or **alternate-reverse**, the value in the **to** key frame is used.
**"both"**: The animation follows the **forwards** and **backwards** rules.| +| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode.
**"normal"**: plays the animation in forward loop mode.
**"reverse"**: plays the animation in reverse loop mode.
**"alternate"**: plays the animation in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction.
**"alternate-reverse"**: plays the animation in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction.| +| iterations | number | Yes | Number of times that the animation is played. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.
**NOTE**
If this parameter is set to a negative value other than **-1**, the value is invalid. In this case, the animation is played once.| +| begin | number | Yes | Start point of the animation interpolation. | +| end | number | Yes | End point of animation interpolation. | ## Example @@ -280,10 +280,10 @@ export default { onInit() { let options = { duration: 1500, - easing: 'friction', + easing: "friction", delay: 0, - fill: 'forwards', - direction: 'normal', + fill: "forwards", + direction: "normal", iterations: 2, begin: 200.0, end: 400.0 @@ -293,9 +293,9 @@ export default { Show() { let options1 = { duration: 1500, - easing: 'friction', + easing: "friction", delay: 0, - fill: 'forwards', + fill: "forwards", direction: "normal", iterations: 2, begin: 0, @@ -336,10 +336,10 @@ struct AnimatorTest { let _this = this this.backAnimator = animator.create({ duration: 2000, - easing: 'ease', + easing: "ease", delay: 0, - fill: 'none', - direction: 'normal', + fill: "none", + direction: "normal", iterations: 1, begin: 100, end: 200 @@ -444,10 +444,10 @@ struct AnimatorTest { this.flag = false this.backAnimator.reset({ duration: 5000, - easing: 'ease-in', + easing: "ease-in", delay: 0, - fill: 'none', - direction: 'normal', + fill: "none", + direction: "normal", iterations: 4, begin: 100, end: 300 @@ -513,10 +513,10 @@ This API is deprecated since API version 9. You are advised to use [create9 ```js let options = { duration: 1500, - easing: 'friction', + easing: "friction", delay: 0, - fill: 'forwards', - direction: 'normal', + fill: "forwards", + direction: "normal", iterations: 3, begin: 200.0, end: 400.0, diff --git a/en/application-dev/reference/apis/js-apis-app-ability-ability.md b/en/application-dev/reference/apis/js-apis-app-ability-ability.md index cfa11ddc30560c1ffa6a03eb8efccb8ea60b6d5b..fba8cc01ca919dbb62cb0187256ae010511a7d88 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-ability.md @@ -28,7 +28,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyUIAbility extends UIAbility { onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + console.log('onConfigurationUpdate, config: ${JSON.stringify(config)}'); } } ``` @@ -55,7 +55,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyUIAbility extends UIAbility { onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); + console.log('onMemoryLevel, level: ${JSON.stringify(level)}'); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md index 766636a7c7d4cda38cb2b71395fd3f2575e2f784..62d38c714940a754e566bbdebadac2e3fcbccec2 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -48,7 +48,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyAbility extends UIAbility { onCreate(want, launchParam) { if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) { - console.log("The ability has been started by the way of startAbility."); + console.log('The ability has been started by the way of startAbility.'); } } } @@ -74,7 +74,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyAbility extends UIAbility { onCreate(want, launchParam) { if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) { - console.log("The ability has exit last because the ability was not responding."); + console.log('The ability has exit last because the ability was not responding.'); } } } @@ -110,20 +110,22 @@ Enumerates the window modes in which an ability can be displayed at startup. It **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Value| Description | | --- | --- | --- | | WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. | | WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. | -| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. | -| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | +| WINDOW_MODE_SPLIT_PRIMARY | 100 | The left screen in horizontal direction or the upper screen in vertical direction is the primary window. | +| WINDOW_MODE_SPLIT_SECONDARY | 101 | The right screen in horizontal direction or the lower screen in vertical direction is the secondary window. | | WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| **Example** ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; let option = { windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN @@ -131,9 +133,9 @@ let option = { // Ensure that the context is obtained. this.context.startAbility(want, option).then(()={ - console.log("Succeed to start ability."); + console.log('Succeed to start ability.'); }).catch((error)=>{ - console.log("Failed to start ability with error: " + JSON.stringify(error)); + console.log('Failed to start ability with error: ${JSON.stringify(error)}'); }); ``` @@ -157,7 +159,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyAbility extends UIAbility { onMemoryLevel(level) { if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) { - console.log("The memory of device is critical, please release some memory."); + console.log('The memory of device is critical, please release some memory.'); } } } @@ -209,7 +211,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class MyAbility extends UIAbility { onSaveState(reason, wantParam) { if (reason === AbilityConstant.StateType.CONTINUATION) { - console.log("Save the ability data when the ability continuation."); + console.log('Save the ability data when the ability continuation.'); } return AbilityConstant.OnSaveResult.ALL_AGREE; } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index 5cfa437047868a9183ae4bb4f41ff42eec47f5d7..fe6bec9f550bef9bdeb6a3c61c8a1c5adc810f10 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -49,16 +49,16 @@ import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; abilityDelegator.startAbility(want, (err) => { - if (err.code !== 0) { - console.log("Success start ability."); + if (!err || err.code === 0) { + console.log('Success start ability.'); } else { - console.log("Failed start ability, error: " + JSON.stringify(err)); + console.log('Failed start ability, error: ${JSON.stringify(err)}'); } -}) +}); ``` ## AbilityDelegatorRegistry.getArguments @@ -81,8 +81,8 @@ Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let args = AbilityDelegatorRegistry.getArguments(); -console.info("getArguments bundleName:" + args.bundleName); -console.info("getArguments parameters:" + JSON.stringify(args.parameters)); -console.info("getArguments testCaseNames:" + args.testCaseNames); -console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +console.info('getArguments bundleName: ${args.bundleName}'); +console.info('getArguments parameters: ${JSON.stringify(args.parameters)}'); +console.info('getArguments testCaseNames: ${args.testCaseNames}'); +console.info('getArguments testRunnerClassName: ${args.testRunnerClassName}'); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md index 84be19350707fee37328ff8040b2986588afd2f8..df7b07b2d0303bf9310cfdd354d50b1db9239ece 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -11,7 +11,7 @@ The **AbilityLifecycleCallback** module defines the callbacks to receive lifecyc ## Modules to Import ```ts -import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; +import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; ``` @@ -25,15 +25,15 @@ Called when an ability is created. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| **Example** ```ts let abilityLifecycleCallback = { onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate."); + console.log('AbilityLifecycleCallback onAbilityCreate.'); } }; ``` @@ -48,16 +48,16 @@ Called when the window stage of an ability is created. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| **Example** ```ts let abilityLifecycleCallback = { onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate."); + console.log('AbilityLifecycleCallback onWindowStageCreate.'); } }; ``` @@ -72,16 +72,16 @@ Called when the window stage of an ability gains focus. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| **Example** ```ts let abilityLifecycleCallback = { onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive."); + console.log('AbilityLifecycleCallback onWindowStageActive.'); } }; ``` @@ -96,16 +96,16 @@ Called when the window stage of an ability loses focus. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| **Example** ```ts let abilityLifecycleCallback = { onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive."); + console.log('AbilityLifecycleCallback onWindowStageInactive.'); } }; ``` @@ -120,16 +120,16 @@ Called when the window stage of an ability is destroyed. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| **Example** ```ts let abilityLifecycleCallback = { onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy."); + console.log('AbilityLifecycleCallback onWindowStageDestroy.'); } }; ``` @@ -144,15 +144,15 @@ Called when an ability is destroyed. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| **Example** ```ts let abilityLifecycleCallback = { onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy."); + console.log('AbilityLifecycleCallback onAbilityDestroy.'); } }; ``` @@ -167,15 +167,15 @@ Called when an ability is switched from the background to the foreground. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| **Example** ```ts let abilityLifecycleCallback = { onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground."); + console.log('AbilityLifecycleCallback onAbilityForeground.'); } }; ``` @@ -190,15 +190,15 @@ Called when an ability is switched from the foreground to the background. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| **Example** ```ts let abilityLifecycleCallback = { onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground."); + console.log('AbilityLifecycleCallback onAbilityBackground.'); } }; ``` @@ -213,15 +213,15 @@ Called when an ability is continued on another device. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| **Example** ```ts let abilityLifecycleCallback = { onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue."); + console.log('AbilityLifecycleCallback onAbilityContinue.'); } }; ``` @@ -232,52 +232,52 @@ let abilityLifecycleCallback = { MyFirstAbility.ts ```ts -import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; -import AbilityStage from "@ohos.app.ability.AbilityStage"; +import AbilityLifecycleCallback from '@ohos.app.ability.AbilityLifecycleCallback'; +import AbilityStage from '@ohos.app.ability.AbilityStage'; import UIAbility from '@ohos.app.ability.UIAbility'; // Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured. let abilityLifecycleCallback = { onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate."); + console.log('AbilityLifecycleCallback onAbilityCreate.'); }, onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate."); + console.log('AbilityLifecycleCallback onWindowStageCreate.'); }, onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive."); + console.log('AbilityLifecycleCallback onWindowStageActive.'); }, onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive."); + console.log('AbilityLifecycleCallback onWindowStageInactive.'); }, onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy."); + console.log('AbilityLifecycleCallback onWindowStageDestroy.'); }, onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy."); + console.log('AbilityLifecycleCallback onAbilityDestroy.'); }, onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground."); + console.log('AbilityLifecycleCallback onAbilityForeground.'); }, onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground."); + console.log('AbilityLifecycleCallback onAbilityBackground.'); }, onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue."); + console.log('AbilityLifecycleCallback onAbilityContinue.'); } }; export default class MyFirstAbility extends UIAbility { onCreate() { - console.log("MyAbilityStage onCreate"); + console.log('MyAbilityStage onCreate'); // 1. Obtain applicationContext through the context attribute. let applicationContext = this.context.getApplicationContext(); // 2. Register the listener for the ability lifecycle changes through the applicationContext object. try { - globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + globalThis.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback); + console.log('registerAbilityLifecycleCallback number: ${JSON.stringify(lifecycleId)}'); } catch (paramError) { - console.log("error: " + paramError.code + " ," + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } } } @@ -285,17 +285,17 @@ export default class MyFirstAbility extends UIAbility { MySecondAbility.ts ```ts -import UIAbility from "ohos.app.ability.UIAbility"; +import UIAbility from 'ohos.app.ability.UIAbility'; export default class MySecondAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - // 3. Deregister the listener for the environment changes through the applicationContext object. - applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => { - if (error.code != 0) { - console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error)); + // 3. Deregister the listener for the ability lifecycle changes through the applicationContext object. + applicationContext.off('abilityLifecycle', globalThis.lifecycleId, (error) => { + if (error && error.code !== 0) { + console.log('unregisterAbilityLifecycleCallback fail, error: ${JSON.stringify(error)}'); } else { - console.log("unregisterAbilityLifecycleCallback success."); + console.log('unregisterAbilityLifecycleCallback success.'); } }); } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md index f7f9c49a4cdf1c9e8c92ad8b7c8bd977df525477..786b63cbf302cfe869c6b81eab65096fd5cc2517 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -24,6 +24,7 @@ Enumerates the ability states. This enum can be used together with [AbilityRunni | Name| Value| Description| | -------- | -------- | -------- | | INITIAL | 0 | The ability is in the initial state.| +| FOCUS | 2 | The ability has the focus.| | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | | FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | @@ -63,22 +64,21 @@ const config = { language: 'Zh-Hans', // Simplified Chinese. colorMode: COLOR_MODE_LIGHT, // Light theme. direction: DIRECTION_VERTICAL, // Vertical direction. - screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. displayId: 1, // The application is displayed on the display with ID 1. hasPointerDevice: true, // A pointer device is connected. }; try { abilityManager.updateConfiguration(config, (err) => { - if (err.code !== 0) { - console.log("updateConfiguration fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('updateConfiguration fail, err: ${JSON.stringify(err)}'); } else { - console.log("updateConfiguration success."); + console.log('updateConfiguration success.'); } - }) + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) - + ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -121,7 +121,7 @@ const config = { language: 'Zh-Hans', // Simplified Chinese. colorMode: COLOR_MODE_LIGHT, // Light theme. direction: DIRECTION_VERTICAL, // Vertical direction. - screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + screenDensity: SCREEN_DENSITY_SDPI, // The screen pixel density is 'sdpi'. displayId: 1, // The application is displayed on the display with ID 1. hasPointerDevice: true, // A pointer device is connected. }; @@ -130,11 +130,10 @@ try { abilityManager.updateConfiguration(config).then(() => { console.log('updateConfiguration success.'); }).catch((err) => { - console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); - }) + console.log('updateConfiguration fail, err: ${JSON.stringify(err)}'); + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) - + ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -169,15 +168,14 @@ import abilityManager from '@ohos.app.ability.abilityManager'; try { abilityManager.getAbilityRunningInfos((err, data) => { - if (err.code !== 0) { - console.log("getAbilityRunningInfos fail, error: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('getAbilityRunningInfos fail, error: ${JSON.stringify(err)}'); } else { - console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)); + console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}'); } }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) - + ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -185,7 +183,7 @@ try { getAbilityRunningInfos(): Promise\> -Obtains the ability running information. This API uses a promise to return the result. +Obtains the UIAbility running information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -195,7 +193,7 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback.| +| Promise\> | Promise used to return the API call result and the UIAbility running information. You can perform error handling or custom processing in this callback.| **Error codes** @@ -212,13 +210,12 @@ import abilityManager from '@ohos.app.ability.abilityManager'; try { abilityManager.getAbilityRunningInfos().then((data) => { - console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)) + console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log("getAbilityRunningInfos fail, err: " + JSON.stringify(err)); + console.log('getAbilityRunningInfos fail, err: ${JSON.stringify(err)}'); }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) - + ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -256,15 +253,14 @@ let upperLimit = 10; try { abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => { - if (err.code !== 0) { - console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}'); } else { - console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}'); } }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) - + ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -307,13 +303,12 @@ let upperLimit = 10; try { abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { - console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); - }) + console.log('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}'); + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) - + ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -345,10 +340,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import abilityManager from '@ohos.app.ability.abilityManager'; abilityManager.getTopAbility((err, data) => { - if (err.code !== 0) { - console.log("getTopAbility fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('getTopAbility fail, err: ${JSON.stringify(err)}'); } else { - console.log("getTopAbility success, data: " + JSON.stringify(data)); + console.log('getTopAbility success, data: ${JSON.stringify(data)}'); } }); ``` @@ -381,8 +376,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import abilityManager from '@ohos.app.ability.abilityManager'; abilityManager.getTopAbility().then((data) => { - console.log("getTopAbility success, data: " + JSON.stringify(data)); + console.log('getTopAbility success, data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log("getTopAbility fail, err: " + JSON.stringify(err)); -}) + console.log('getTopAbility fail, err: ${JSON.stringify(err)}'); +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md index 50feb82791f8992894641a296d6cb831fdc86680..89dc8c251534c355a0dca5d122b72d070a7ef460 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md @@ -30,7 +30,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; class MyAbilityStage extends AbilityStage { onCreate() { - console.log("MyAbilityStage.onCreate is called"); + console.log('MyAbilityStage.onCreate is called'); } } ``` @@ -63,8 +63,8 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; class MyAbilityStage extends AbilityStage { onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; + console.log('MyAbilityStage.onAcceptWant called'); + return 'com.example.test'; } } ``` @@ -91,7 +91,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; class MyAbilityStage extends AbilityStage { onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, language:' + config.language); + console.log('onConfigurationUpdate, language: ${config.language}'); } } ``` @@ -117,7 +117,7 @@ import AbilityStage from '@ohos.app.ability.AbilityStage'; class MyAbilityStage extends AbilityStage { onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); + console.log('onMemoryLevel, level: ${JSON.stringify(level)}'); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md index 840a395eac9e17558918dd7466aa9e0b178b1c4d..419680548f17ca6bb59830ab4a540065e31067a9 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -40,12 +40,12 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.isRunningInStabilityTest((err, flag) => { - if (err.code !== 0) { - console.log("isRunningInStabilityTest faile, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}'); } else { - console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); + console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); } -}) +}); ``` @@ -77,9 +77,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.isRunningInStabilityTest().then((flag) => { - console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); + console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); }).catch((error) => { - console.log("error:" + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -112,9 +112,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.isRamConstrainedDevice().then((data) => { - console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); + console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log("error:" + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -146,12 +146,12 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.isRamConstrainedDevice((err, data) => { - if (err.code !== 0) { - console.log("isRamConstrainedDevice faile, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}'); } else { - console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); + console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); } -}) +}); ``` ## appManager.getAppMemorySize @@ -182,9 +182,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.getAppMemorySize().then((data) => { - console.log("The size of app memory is:" + JSON.stringify(data)); + console.log('The size of app memory is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log("error:" + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -216,17 +216,17 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.getAppMemorySize((err, data) => { - if (err.code !== 0) { - console.log("getAppMemorySize faile, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('getAppMemorySize fail, err: ${JSON.stringify(err)}'); } else { - console.log("The size of app memory is:" + JSON.stringify(data)); + console.log('The size of app memory is: ${JSON.stringify(data)}'); } -}) +}); ``` -## appManager.getProcessRunningInformation +## appManager.getRunningProcessInformation -getProcessRunningInformation(): Promise\>; +getRunningProcessInformation(): Promise\>; Obtains information about the running processes. This API uses a promise to return the result. @@ -234,13 +234,11 @@ Obtains information about the running processes. This API uses a promise to retu **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Return value** | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| +| Promise\> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| **Error codes** @@ -255,16 +253,16 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import appManager from '@ohos.app.ability.appManager'; -appManager.getProcessRunningInformation().then((data) => { - console.log("The process running information is:" + JSON.stringify(data)); +appManager.getRunningProcessInformation().then((data) => { + console.log('The running process information is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log("error:" + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` -## appManager.getProcessRunningInformation9+ +## appManager.getRunningProcessInformation9+ -getProcessRunningInformation(callback: AsyncCallback\>): void; +getRunningProcessInformation(callback: AsyncCallback\>): void; Obtains information about the running processes. This API uses an asynchronous callback to return the result. @@ -272,13 +270,11 @@ Obtains information about the running processes. This API uses an asynchronous c **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Type| Description| | -------- | -------- | -|AsyncCallback\> | Callback used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| +|AsyncCallback\> | Callback used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| **Error codes** @@ -293,18 +289,18 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import appManager from '@ohos.app.ability.appManager'; -appManager.getProcessRunningInformation((err, data) => { - if (err.code !== 0) { - console.log("getProcessRunningInformation faile, err: " + JSON.stringify(err)); +appManager.getRunningProcessInformation((err, data) => { + if (err && err.code !== 0) { + console.log('getRunningProcessInformation fail, err: ${JSON.stringify(err)}'); } else { - console.log("The process running information is:" + JSON.stringify(data)); + console.log('The process running information is: ${JSON.stringify(data)}'); } -}) +}); ``` ## appManager.on -on(type: "applicationState", observer: ApplicationStateObserver): number; +on(type: 'applicationState', observer: ApplicationStateObserver): number; Registers an observer to listen for the state changes of all applications. @@ -318,7 +314,7 @@ Registers an observer to listen for the state changes of all applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| type | string | Yes| Type of the API to call. It is fixed at **'applicationState'**.| | observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| **Return value** @@ -356,7 +352,7 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; try { const observerId = appManager.on('applicationState', applicationStateObserver); console.log(`[appManager] observerCode: ${observerId}`); @@ -367,7 +363,7 @@ try { ## appManager.on -on(type: "applicationState", observer: ApplicationStateObserver, bundleNameList: Array\): number; +on(type: 'applicationState', observer: ApplicationStateObserver, bundleNameList: Array\): number; Registers an observer to listen for the state changes of a specified application. @@ -381,7 +377,7 @@ Registers an observer to listen for the state changes of a specified application | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| type | string | Yes| Type of the API to call. It is fixed at **'applicationState'**.| | observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| | bundleNameList | `Array` | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| @@ -420,10 +416,10 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; let bundleNameList = ['bundleName1', 'bundleName2']; try { - const observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); console.log(`[appManager] observerCode: ${observerId}`); } catch (paramError) { console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); @@ -432,7 +428,7 @@ try { ## appManager.off -off(type: "applicationState", observerId: number, callback: AsyncCallback\): void; +off(type: 'applicationState', observerId: number, callback: AsyncCallback\): void; Deregisters the application state observer. This API uses an asynchronous callback to return the result. @@ -446,7 +442,7 @@ Deregisters the application state observer. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| type | string | Yes| Type of the API to call. It is fixed at **'applicationState'**.| | observerId | number | Yes| Digital code of the observer.| | callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| @@ -482,10 +478,10 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; let bundleNameList = ['bundleName1', 'bundleName2']; try { - observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); console.log(`[appManager] observerCode: ${observerId}`); } catch (paramError) { console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); @@ -493,22 +489,22 @@ try { // 2. Deregister the application state observer. function unregisterApplicationStateObserverCallback(err) { - if (err.code !== 0) { - console.log("unregisterApplicationStateObserverCallback faile, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}'); } else { - console.log("unregisterApplicationStateObserverCallback success."); + console.log('unregisterApplicationStateObserverCallback success.'); } } try { - appManager.off("applicationState", observerId, unregisterApplicationStateObserverCallback); + appManager.off('applicationState', observerId, unregisterApplicationStateObserverCallback); } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` ## appManager.off -off(type: "applicationState", observerId: number): Promise\; +off(type: 'applicationState', observerId: number): Promise\; Deregisters the application state observer. This API uses an asynchronous callback to return the result. @@ -522,7 +518,7 @@ Deregisters the application state observer. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| type | string | Yes| Type of the API to call. It is fixed at **'applicationState'**.| | observerId | number | Yes| Digital code of the observer.| **Return value** @@ -563,10 +559,10 @@ let applicationStateObserver = { onProcessStateChanged(processData) { console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } -} +}; let bundleNameList = ['bundleName1', 'bundleName2']; try { - observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); console.log(`[appManager] observerCode: ${observerId}`); } catch (paramError) { console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); @@ -574,13 +570,13 @@ try { // 2. Deregister the application state observer. try { - appManager.off("applicationState", observerId).then((data) => { - console.log("unregisterApplicationStateObserver success, data: " + JSON.stringify(data)); + appManager.off('applicationState', observerId).then((data) => { + console.log('unregisterApplicationStateObserver success, data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log("unregisterApplicationStateObserver faile, err: " + JSON.stringify(err)); - }) + console.log('unregisterApplicationStateObserver fail, err: ${JSON.stringify(err)}'); + }); } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -616,16 +612,16 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; function getForegroundApplicationsCallback(err, data) { - if (err.code !== 0) { - console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}'); } else { - console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data)); + console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}'); } } try { appManager.getForegroundApplications(getForegroundApplicationsCallback); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -661,10 +657,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error import appManager from '@ohos.app.ability.appManager'; appManager.getForegroundApplications().then((data) => { - console.log("getForegroundApplications success, data: " + JSON.stringify(data)); + console.log('getForegroundApplications success, data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log("getForegroundApplications fail, err: " + JSON.stringify(err)); -}) + console.log('getForegroundApplications fail, err: ${JSON.stringify(err)}'); +}); ``` ## appManager.killProcessWithAccount @@ -703,12 +699,12 @@ let bundleName = 'bundleName'; let accountId = 0; try { appManager.killProcessWithAccount(bundleName, accountId).then(() => { - console.log("killProcessWithAccount success"); + console.log('killProcessWithAccount success'); }).catch((err) => { - console.log("killProcessWithAccount fail, err: " + JSON.stringify(err)); - }) + console.error('killProcessWithAccount fail, err: ${JSON.stringify(err)}'); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.error('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -749,10 +745,10 @@ import appManager from '@ohos.app.ability.appManager'; let bundleName = 'bundleName'; let accountId = 0; function killProcessWithAccountCallback(err, data) { - if (err.code !== 0) { - console.log("killProcessWithAccountCallback fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}'); } else { - console.log("killProcessWithAccountCallback success."); + console.log('killProcessWithAccountCallback success.'); } } appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); @@ -792,16 +788,16 @@ import appManager from '@ohos.app.ability.appManager'; let bundleName = 'bundleName'; function killProcessesByBundleNameCallback(err, data) { - if (err.code !== 0) { - console.log("killProcessesByBundleNameCallback fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}'); } else { - console.log("killProcessesByBundleNameCallback success."); + console.log('killProcessesByBundleNameCallback success.'); } } try { appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -845,12 +841,12 @@ import appManager from '@ohos.app.ability.appManager'; let bundleName = 'bundleName'; try { appManager.killProcessesByBundleName(bundleName).then((data) => { - console.log("killProcessesByBundleName success."); + console.log('killProcessesByBundleName success.'); }).catch((err) => { - console.log("killProcessesByBundleName fail, err: " + JSON.stringify(err)); - }) + console.log('killProcessesByBundleName fail, err: ${JSON.stringify(err)}'); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -888,16 +884,16 @@ import appManager from '@ohos.app.ability.appManager'; let bundleName = 'bundleName'; function clearUpApplicationDataCallback(err, data) { - if (err) { - console.log("clearUpApplicationDataCallback fail, err: " + JSON.stringify(err)); + if (err && err.code !== 0) { + console.log('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}'); } else { - console.log("clearUpApplicationDataCallback success."); + console.log('clearUpApplicationDataCallback success.'); } } try { appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -941,12 +937,12 @@ import appManager from '@ohos.app.ability.appManager'; let bundleName = 'bundleName'; try { appManager.clearUpApplicationData(bundleName).then((data) => { - console.log("clearUpApplicationData success."); + console.log('clearUpApplicationData success.'); }).catch((err) => { - console.log("clearUpApplicationData fail, err: " + JSON.stringify(err)); - }) + console.log('clearUpApplicationData fail, err: ${JSON.stringify(err)}'); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md index e066ac119344842ffce617fd7934efa3712d895f..5a07867e6f5c28213e5cc48b07ef6a0958eb9426 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -18,13 +18,12 @@ Enumerates the application restart flags. This enum is used as an input paramete **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| ALWAYS_RESTART | 0 | The application is restarted in all cases.| -| CPP_CRASH_NO_RESTART | 0x0001 | The application is not restarted in the case of CPP_CRASH.| -| JS_CRASH_NO_RESTART | 0x0002 | The application is not restarted in the case of JS_CRASH.| -| APP_FREEZE_NO_RESTART | 0x0004 | The application is not restarted in the case of APP_FREEZE.| -| NO_RESTART | 0xFFFF | The application is not restarted in any case.| +| Name | Value | Description | +| ---------- | ---- | ---------- | +| ALWAYS_RESTART | 0 | The application is restarted in all cases.| +| RESTART_WHEN_JS_CRASH | 0x0001 | The application is restarted in the case of JS_CRASH.| +| RESTART_WHEN_APP_FREEZE | 0x0002 | The application is restarted in the case of APP_FREEZE.| +| NO_RESTART | 0xFFFF | The application is not restarted in any case.| ## appRecovery.SaveOccasionFlag @@ -69,9 +68,8 @@ Enables application recovery. ```ts import appRecovery from '@ohos.app.ability.appRecovery'; import AbilityStage from '@ohos.app.ability.AbilityStage'; -import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MyAbility extends UIAbility { +export default class MyAbilityStage extends AbilityStage { onCreate() { appRecovery.enableAppRecovery( appRecovery.RestartFlag::ALWAYS_RESTART, @@ -99,15 +97,15 @@ import errorManager from '@ohos.app.ability.errorManager'; let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) + console.log('onUnhandledException, errorMsg: ', errorMsg); appRecovery.restartApp(); } }; try { - errorManager.on("error", observer); + errorManager.on('error', observer); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -133,14 +131,14 @@ import errorManager from '@ohos.app.ability.errorManager'; let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) + console.log('onUnhandledException, errorMsg: ', errorMsg); appRecovery.saveAppState(); } }; try { - errorManager.on("error", observer); + errorManager.on('error', observer); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md index 5cc9b61b90fb3072aacf530fdaee0ae2633f7ac0..497867de9df35f93bc04b818a305e32b3a5dee3a 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-common.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-common.md @@ -10,7 +10,7 @@ The **Common** module provides all level-2 module APIs for developers to export. ## Modules to Import ```ts -import common from '@ohos.app.ability.common' +import common from '@ohos.app.ability.common'; ``` **System capability**: SystemCapability.Ability.AbilityBase @@ -24,16 +24,15 @@ import common from '@ohos.app.ability.common' | Context | [Context](js-apis-inner-application-context.md) | Level-2 module **Context**.| | ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Level-2 module **ExtensionContext**.| | FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.| -| AreaMode | [AreaMode](#areamode) | Enumerated values of **AreaMode**.| +| ServiceExtensionContext | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Level-2 module **ServiceExtensionContext**.| | EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.| -| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | Level-2 module **PermissionRequestResult**.| | PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | Level-2 module **PacMap**.| | AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| | ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.| **Example** ```ts -import common from '@ohos.app.ability.common' +import common from '@ohos.app.ability.common'; let uiAbilityContext: common.UIAbilityContext; let abilityStageContext: common.AbilityStageContext; @@ -42,21 +41,8 @@ let baseContext: common.BaseContext; let context: common.Context; let extensionContext: common.ExtensionContext; let formExtensionContext: common.FormExtensionContext; -let areaMode: common.AreaMode; let eventHub: common.EventHub; -let permissionRequestResult: common.PermissionRequestResult; let pacMap: common.PacMap; let abilityResult: common.AbilityResult; let connectOptions: common.ConnectOptions; ``` - -## AreaMode - -Enumerates the data encryption levels. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| --------------- | ---- | --------------- | -| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on. | -| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md index 388761074dd2e6e53e2ca4ee621a6875f292996a..bf4f5afd632fa2fd0b7c380e3781a854c7676460 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -1,25 +1,19 @@ # @ohos.app.ability.Configuration (Configuration) -The **Configuration** module defines environment change information. +The **Configuration** module defines environment change information. **Configuration** is an interface definition and is used only for field declaration. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import - -```ts -import Configuration from '@ohos.app.ability.Configuration'; -``` - **System capability**: SystemCapability.Ability.AbilityBase - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | language | string | Yes| Yes| Language of the application, for example, **zh**.| -| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| +| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode. The default value is **COLOR_MODE_LIGHT**. The options are as follows:
- **COLOR_MODE_NOT_SET**: The color mode is not set.
- **COLOR_MODE_LIGHT**: light mode.
- **COLOR_MODE_DARK**: dark mode.| +| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation. The options are as follows:
- **DIRECTION_NOT_SET**: The screen orientation is not set.
- **DIRECTION_HORIZONTAL**: horizontal direction.
- **DIRECTION_VERTICAL**: vertical direction.| +| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Pixel density of the screen. The options are as follows:
- **SCREEN_DENSITY_NOT_SET**: The pixel density is not set.
- **SCREEN_DENSITY_SDPI**: 120.
- **SCREEN_DENSITY_MDPI**: 160.
- **SCREEN_DENSITY_LDPI**: 240.
- **SCREEN_DENSITY_XLDPI**: 320.
- **SCREEN_DENSITY_XXLDPI**: 480.
- **SCREEN_DENSITY_XXXLDPI**: 640.| | displayId | number | Yes| No| ID of the display where the application is located.| | hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| @@ -34,7 +28,7 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let envCallback = { onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; let colorMode = config.colorMode; let direction = config.direction; @@ -45,10 +39,10 @@ export default class EntryAbility extends UIAbility { }; try { let applicationContext = this.context.getApplicationContext(); - let callbackId = applicationContext.on("environment", envCallback); - console.log("callbackId: " + callbackId); + let callbackId = applicationContext.on('environment', envCallback); + console.log('callbackId: ${callbackId}'); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } } } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md index bd56e256603930f874c9ba2c064462c8fad594a8..f25b4fb14d8e4cd253a11ea349ba48f0a3b840e7 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md @@ -46,10 +46,10 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | Name| Value| Description| | -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| +| SCREEN_DENSITY_NOT_SET | 0 | The screen pixel density is not set.| +| SCREEN_DENSITY_SDPI | 120 | The pixel density of the screen is 'sdpi'.| +| SCREEN_DENSITY_MDPI | 160 | The pixel density of the screen is 'mdpi'.| +| SCREEN_DENSITY_LDPI | 240 | The pixel density of the screen is 'ldpi'.| +| SCREEN_DENSITY_XLDPI | 320 | The pixel density of the screen is 'xldpi'.| +| SCREEN_DENSITY_XXLDPI | 480 | The pixel density of the screen is 'xxldpi'.| +| SCREEN_DENSITY_XXXLDPI | 640 | The pixel density of the screen is 'xxxldpi'.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md index 9a869f051a08c4a79c9dac58e8f4dceb9dc4658b..392498e358c592f0d4261994d8ec73138e9b0517 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md @@ -36,10 +36,10 @@ Obtains the ID attached to the end of a given URI. ```ts try { - var id = dataUriUtils.getId("com.example.dataUriUtils/1221") - console.info('get id: ' + id) + let id = dataUriUtils.getId('com.example.dataUriUtils/1221'); + console.info('get id: ${id}'); } catch(err) { - console.error('get id err ,check the uri' + err) + console.error('get id err ,check the uri ${err}'); } ``` @@ -69,15 +69,15 @@ Attaches an ID to the end of a given URI. **Example** ```ts -var id = 1122; +let id = 1122; try { - var uri = dataUriUtils.attachId( - "com.example.dataUriUtils", + let uri = dataUriUtils.attachId( + 'com.example.dataUriUtils', id, - ) - console.info('attachId the uri is: ' + uri) + ); + console.info('attachId the uri is: ${uri}'); } catch (err) { - console.error('get id err ,check the uri' + err) + console.error('get id err ,check the uri ${err}'); } ``` @@ -108,10 +108,10 @@ Deletes the ID from the end of a given URI. ```ts try { - var uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") - console.info('delete id with the uri is: ' + uri) + let uri = dataUriUtils.deleteId('com.example.dataUriUtils/1221'); + console.info('delete id with the uri is: ${uri}'); } catch(err) { - console.error('delete uri err, check the input uri' + err) + console.error('delete uri err, check the input uri ${err}'); } ``` @@ -144,12 +144,12 @@ Updates the ID in a given URI. ```ts try { - var id = 1122; - var uri = dataUriUtils.updateId( - "com.example.dataUriUtils/1221", + let id = 1122; + let uri = dataUriUtils.updateId( + 'com.example.dataUriUtils/1221', id - ) + ); } catch (err) { - console.error('delete uri err, check the input uri' + err) + console.error('delete uri err, check the input uri ${err}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md b/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md new file mode 100644 index 0000000000000000000000000000000000000000..989796d48ee22b34bd28b63b74fe20270d367577 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-dialogRequest.md @@ -0,0 +1,262 @@ +# @ohos.app.ability.dialogRequest (dialogRequest) + +The **dialogRequest** module provides APIs related to modal dialog box processing, including obtaining the request information (used to bind a modal dialog box) and request callback (used to set the request result). +A modal dialog box is a system pop-up box that intercepts events (such as mouse, keyboard, and touchscreen events) triggered for the page displayed under it. The page can be operated only after the modal dialog box is destroyed. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are used in ServiceExtensionAbilities. For a ServiceExtensionAbility that implements modal dialog boxes, you can use the APIs to obtain the request information and request callback and return the request result. + +## Modules to Import + +```js +import dialogRequest from '@ohos.app.ability.dialogRequest'; +``` + +## dialogRequest.getRequestInfo + +getRequestInfo(want: Want): RequestInfo + +Obtains the request information from Want. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | --------------------------- | +| want | [Want](js-apis-application-want.md) | Yes | Want passed in the request for a modal dialog box.| + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| [RequestInfo](#requestinfo) | **RequestInfo** object obtained, which is used to bind a modal dialog box.| + +**Example** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestInfo = dialogRequest.getRequestInfo(want); + } catch(err) { + console.error('getRequestInfo err= ${JSON.stringify(err)}'); + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +## dialogRequest.getRequestCallback + +getRequestCallback(want: Want): RequestCallback + +Obtains the request callback from Want. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | --------------------------- | +| want | [Want](js-apis-application-want.md) | Yes | Want passed in the request for a modal dialog box.| + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| [RequestCallback](#requestcallback) | **RequestCallback** object obtained, which is used to set the return result.| + +**Example** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestCallback = dialogRequest.getRequestCallback(want); + } catch(err) { + console.error('getRequestInfo err= ${JSON.stringify(err)}'); + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +## RequestInfo + +Defines the request information, which is used as an input parameter for binding the modal dialog box. +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + import window from '@ohos.window'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestInfo = dialogRequest.getRequestInfo(want); + window.bindDialogTarget(requestInfo, () => { + console.info('Dialog Window Need Destroy.'); + }, (err) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause: ${JSON.stringify(err)}'); + return; + } + console.info('Succeeded in binding dialog target.'); + }); + } catch(err) { + console.error('getRequestInfo err= ${JSON.stringify(err)}'); + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +## ResultCode + +Enumerates the result codes of the request for the modal dialog box. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name | Value | Description | +| ------------ | ------------------ | ---------------------- | +| RESULT_OK | 0 | The request succeeds. | +| RESULT_CANCEL | 1 | The request fails. | + +## RequestResult +Defines the result of the request for the modal dialog box. Only the result code is included. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| result | [ResultCode](#resultcode) | Yes| Yes| Result code of the request.| + +## RequestCallback + +Provides a callback for setting the modal dialog box request result. + +### RequestCallback.setRequestResult + +setRequestResult(result: RequestResult): void; + +Sets the result of the request for the modal dialog box. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| result | [RequestResult](#requestresult) | Yes| Request result to set.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + import dialogRequest from '@ohos.app.ability.dialogRequest'; + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + try { + var requestCallback = dialogRequest.getRequestCallback(want); + let myResult = { + result : dialogRequest.ResultCode.RESULT_CANCEL, + }; + requestCallback.setRequestResult(myResult); + } catch(err) { + console.error('getRequestInfo err= ${JSON.stringify(err)}'); + } + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md index 0cb95a9abfd6b90f1efacc431070ef6b3397e1e6..a852da75d0192dfcfc7f977dcd0635a08d214389 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -11,7 +11,7 @@ The **EnvironmentCallback** module provides the **onConfigurationUpdated** API f ## Modules to Import ```ts -import EnvironmentCallback from "@ohos.app.ability.EnvironmentCallback"; +import EnvironmentCallback from '@ohos.app.ability.EnvironmentCallback'; ``` @@ -29,33 +29,51 @@ Called when the system environment changes. | -------- | -------- | -------- | -------- | | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| **Configuration** object after the change.| +## EnvironmentCallback.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system memory level changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| + **Example** ```ts -import UIAbility from "@ohos.app.ability.Ability"; +import UIAbility from '@ohos.app.ability.Ability'; -var callbackId; +let callbackId; export default class MyAbility extends UIAbility { onCreate() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate'); globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ - console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + console.log('onConfigurationUpdated config: ${JSON.stringify(config)}'); + } + + onMemoryLevel(level){ + console.log('onMemoryLevel level: ${JSON.stringify(level)}'); } - } + }; // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; // 2. Register a listener for the environment changes through the applicationContext object. callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); - console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + console.log('registerEnvironmentCallback number: ${JSON.stringify(callbackId)}'); } onDestroy() { let applicationContext = globalThis.applicationContext; applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + console.log('unregisterEnvironmentCallback success, err: ${JSON.stringify(error)}'); }); } } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md index e543a93e9ceb5af52f3cdb939a0cfd5d24145968..4c1a2e693f7f08a80541c5bd124a3dd20869adc2 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -8,12 +8,12 @@ The **ErrorManager** module provides APIs for registering and deregistering erro ## Modules to Import ```ts -import errorManager from '@ohos.app.ability.errorManager' +import errorManager from '@ohos.app.ability.errorManager'; ``` ## ErrorManager.on -on(type: "error", observer: ErrorObserver): number; +on(type: 'error', observer: ErrorObserver): number; Registers an error observer. @@ -35,22 +35,22 @@ Registers an error observer. **Example** ```ts -var observer = { +let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) + console.log('onUnhandledException, errorMsg: ', errorMsg); } -} -var observerId = -1; +}; +let observerId = -1; try { - observerId = errorManager.on("error", observer); + observerId = errorManager.on('error', observer); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` ## ErrorManager.off -off(type: "error", observerId: number, callback: AsyncCallback\): void; +off(type: 'error', observerId: number, callback: AsyncCallback\): void; Deregisters an error observer. This API uses an asynchronous callback to return the result. @@ -67,7 +67,7 @@ Deregisters an error observer. This API uses an asynchronous callback to return **Example** ```ts -var observerId = 100; +let observerId = 100; function unregisterErrorObserverCallback(err) { if (err) { @@ -75,15 +75,15 @@ function unregisterErrorObserverCallback(err) { } } try { - errorManager.off("error", observerId, unregisterErrorObserverCallback); + errorManager.off('error', observerId, unregisterErrorObserverCallback); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` ## ErrorManager.off -off(type: "error", observerId: number): Promise\; +off(type: 'error', observerId: number): Promise\; Deregisters an error observer. This API uses a promise to return the result. @@ -105,17 +105,17 @@ Deregisters an error observer. This API uses a promise to return the result. **Example** ```ts -var observerId = 100; +let observerId = 100; try { - errorManager.off("error", observerId) + errorManager.off('error', observerId) .then((data) => { console.log('----------- unregisterErrorObserver success ----------', data); }) .catch((err) => { console.log('----------- unregisterErrorObserver fail ----------', err); - }) + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md index 434fb19383e072a36352012300c2a755769d6c1f..183b3cd82c31d983e8458baee75105ac2025b52e 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -18,7 +18,7 @@ ohos.permission.MANAGE_MISSIONS ## missionManager.on -on(type:"mission", listener: MissionListener): number; +on(type:'mission', listener: MissionListener): number; Registers a listener to observe the mission status. @@ -46,53 +46,53 @@ Registers a listener to observe the mission status. import missionManager from '@ohos.app.ability.missionManager'; import UIAbility from '@ohos.app.ability.UIAbility'; -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; -var listenerId = -1; +let listenerId = -1; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate"); + console.log('[Demo] EntryAbility onCreate'); globalThis.abilityWant = want; globalThis.context = this.context; } onDestroy() { try { - if (listenerId != -1) { - missionManager.off("mission", listenerId).catch(function (err) { + if (listenerId !== -1) { + missionManager.off('mission', listenerId).catch(function (err) { console.log(err); }); } } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } - console.log("[Demo] EntryAbility onDestroy") + console.log('[Demo] EntryAbility onDestroy'); } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] EntryAbility onWindowStageCreate") + console.log('[Demo] EntryAbility onWindowStageCreate'); try { - listenerId = missionManager.on("mission", listener); + listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } - windowStage.loadContent("pages/index", (err, data) => { + windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + console.error('Failed to load the content. Cause: ${JSON.stringify(err)}'); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + console.info('Succeeded in loading the content. Data: ${JSON.stringify(data)}'); }); if (globalThis.flag) { @@ -105,7 +105,7 @@ export default class EntryAbility extends UIAbility { ## missionManager.off -off(type: "mission", listenerId: number, callback: AsyncCallback<void>): void; +off(type: 'mission', listenerId: number, callback: AsyncCallback<void>): void; Deregisters a mission status listener. @@ -128,53 +128,53 @@ Deregisters a mission status listener. import missionManager from '@ohos.app.ability.missionManager'; import UIAbility from '@ohos.app.ability.UIAbility'; -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; -var listenerId = -1; +let listenerId = -1; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate") + console.log('[Demo] EntryAbility onCreate'); globalThis.abilityWant = want; globalThis.context = this.context; } onDestroy() { try { - if (listenerId != -1) { - missionManager.off("mission", listenerId, (err) => { + if (listenerId !== -1) { + missionManager.off('mission', listenerId, (err) => { console.log(err); }); } } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } - console.log("[Demo] EntryAbility onDestroy") + console.log('[Demo] EntryAbility onDestroy'); } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] EntryAbility onWindowStageCreate") + console.log('[Demo] EntryAbility onWindowStageCreate'); try { - listenerId = missionManager.on("mission", listener); + listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } - windowStage.loadContent("pages/index", (err, data) => { + windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + console.error('Failed to load the content. Cause: ${JSON.stringify(err)}'); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + console.info('Succeeded in loading the content. Data: ${JSON.stringify(data)}'); }); if (globalThis.flag) { @@ -187,7 +187,7 @@ export default class EntryAbility extends UIAbility { ## missionManager.off -off(type: "mission", listenerId: number): Promise<void>; +off(type: 'mission', listenerId: number): Promise<void>; Deregisters a mission status listener. This API uses a promise to return the result. @@ -215,53 +215,53 @@ Deregisters a mission status listener. This API uses a promise to return the res import missionManager from '@ohos.app.ability.missionManager'; import UIAbility from '@ohos.app.ability.UIAbility'; -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; -var listenerId = -1; +let listenerId = -1; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate") + console.log('[Demo] EntryAbility onCreate'); globalThis.abilityWant = want; globalThis.context = this.context; } onDestroy() { try { - if (listenerId != -1) { - missionManager.off("mission", listenerId).catch(function (err) { + if (listenerId !== -1) { + missionManager.off('mission', listenerId).catch(function (err) { console.log(err); }); } } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } - console.log("[Demo] EntryAbility onDestroy") + console.log('[Demo] EntryAbility onDestroy'); } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] EntryAbility onWindowStageCreate") + console.log('[Demo] EntryAbility onWindowStageCreate'); try { - listenerId = missionManager.on("mission", listener); + listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } - windowStage.loadContent("pages/index", (err, data) => { + windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + console.error('Failed to load the content. Cause: ${JSON.stringify(err)}'); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + console.info('Succeeded in loading the content. Data: ${JSON.stringify(data)}'); }); if (globalThis.flag) { @@ -299,26 +299,25 @@ Obtains the information about a given mission. This API uses an asynchronous cal let testMissionId = 1; try { - var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); + let allMissions=await missionManager.getMissionInfos('',10).catch(function(err){console.log(err);}); if (allMissions && allMissions.length > 0) { testMissionId = allMissions[0].missionId; } - missionManager.getMissionInfo("", testMissionId, (error, mission) => { + missionManager.getMissionInfo('', testMissionId, (error, mission) => { if (error) { - console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } else { - console.log("mission.missionId = " + mission.missionId); - console.log("mission.runningState = " + mission.runningState); - console.log("mission.lockedState = " + mission.lockedState); - console.log("mission.timestamp = " + mission.timestamp); - console.log("mission.label = " + mission.label); - console.log("mission.iconPath = " + mission.iconPath); + console.log('mission.missionId = ${mission.missionId}'); + console.log('mission.runningState = ${mission.runningState}'); + console.log('mission.lockedState = ${mission.lockedState}'); + console.log('mission.timestamp = ${mission.timestamp}'); + console.log('mission.label = ${mission.label}'); + console.log('mission.iconPath = ${mission.iconPath}'); } }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error.code: ${paramError.code}, error.message: ${paramError.message}'); } ``` @@ -355,13 +354,13 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 1; try { - missionManager.getMissionInfo("", testMissionId).then((data) => { - console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data)); + missionManager.getMissionInfo('', testMissionId).then((data) => { + console.info('getMissionInfo successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('getMissionInfo failed. Cause: ' + error.message); + console.error('getMissionInfo failed. Cause: ${error.message}'); }); } catch (error) { - console.error('getMissionInfo failed. Cause: ' + error.message); + console.error('getMissionInfo failed. Cause: ${error.message}'); } ``` @@ -391,17 +390,16 @@ Obtains information about all missions. This API uses an asynchronous callback t import missionManager from '@ohos.app.ability.missionManager'; try { - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } else { - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); } - }) + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -437,13 +435,13 @@ Obtains information about all missions. This API uses a promise to return the re import missionManager from '@ohos.app.ability.missionManager'; try { - missionManager.getMissionInfos("", 10).then((data) => { - console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data)); + missionManager.getMissionInfos('', 10).then((data) => { + console.info('getMissionInfos successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('getMissionInfos failed. Cause: ' + error.message); + console.error('getMissionInfos failed. Cause: ${error.message}'); }); } catch (error) { - console.error('getMissionInfos failed. Cause: ' + error.message); + console.error('getMissionInfos failed. Cause: ${error.message}'); } ``` @@ -473,15 +471,15 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { - missionManager.getMissionSnapShot("", testMissionId, (err, data) => { + missionManager.getMissionSnapShot('', testMissionId, (err, data) => { if (err) { - console.error('getMissionSnapShot failed:' + err.message); + console.error('getMissionSnapShot failed: ${err.message}'); } else { - console.info('getMissionSnapShot successfully:' + JSON.stringify(data)); + console.info('getMissionSnapShot successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('getMissionSnapShot failed:' + err.message); + console.error('getMissionSnapShot failed: ${err.message}'); } ``` @@ -516,13 +514,13 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { - missionManager.getMissionSnapShot("", testMissionId).then((data) => { - console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + missionManager.getMissionSnapShot('', testMissionId).then((data) => { + console.info('getMissionSnapShot successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('getMissionSnapShot failed. Cause: ' + error.message); + console.error('getMissionSnapShot failed. Cause: ${error.message}'); }); } catch (error) { - console.error('getMissionSnapShot failed. Cause: ' + error.message); + console.error('getMissionSnapShot failed. Cause: ${error.message}'); } ``` @@ -552,15 +550,15 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { - missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => { + missionManager.getLowResolutionMissionSnapShot('', testMissionId, (err, data) => { if (err) { - console.error('getLowResolutionMissionSnapShot failed:' + err.message); + console.error('getLowResolutionMissionSnapShot failed: ${err.message}'); } else { - console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data)); + console.info('getLowResolutionMissionSnapShot successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('getLowResolutionMissionSnapShot failed:' + err.message); + console.error('getLowResolutionMissionSnapShot failed: ${err.message}'); } ``` @@ -596,13 +594,13 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { - missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => { - console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + missionManager.getLowResolutionMissionSnapShot('', testMissionId).then((data) => { + console.info('getLowResolutionMissionSnapShot successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); + console.error('getLowResolutionMissionSnapShot failed. Cause: ${error.message}'); }); } catch (error) { - console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); + console.error('getLowResolutionMissionSnapShot failed. Cause: ${error.message}'); } ``` @@ -635,13 +633,13 @@ let testMissionId = 2; try { missionManager.lockMission(testMissionId, (err, data) => { if (err) { - console.error('lockMission failed:' + err.message); + console.error('lockMission failed: ${err.message}'); } else { - console.info('lockMission successfully:' + JSON.stringify(data)); + console.info('lockMission successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('lockMission failed:' + err.message); + console.error('lockMission failed: ${err.message}'); } ``` @@ -676,12 +674,12 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { missionManager.lockMission(testMissionId).then((data) => { - console.info('lockMission successfully. Data: ' + JSON.stringify(data)); + console.info('lockMission successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('lockMission failed. Cause: ' + error.message); + console.error('lockMission failed. Cause: ${error.message}'); }); } catch (error) { - console.error('lockMission failed. Cause: ' + error.message); + console.error('lockMission failed. Cause: ${error.message}'); } ``` @@ -712,13 +710,13 @@ let testMissionId = 2; try { missionManager.unlockMission(testMissionId, (err, data) => { if (err) { - console.error('unlockMission failed:' + err.message); + console.error('unlockMission failed: ${err.message}'); } else { - console.info('unlockMission successfully:' + JSON.stringify(data)); + console.info('unlockMission successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('unlockMission failed:' + err.message); + console.error('unlockMission failed: ${err.message}'); } ``` @@ -754,12 +752,12 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { missionManager.unlockMission(testMissionId).then((data) => { - console.info('unlockMission successfully. Data: ' + JSON.stringify(data)); + console.info('unlockMission successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('unlockMission failed. Cause: ' + error.message); + console.error('unlockMission failed. Cause: ${error.message}'); }); } catch (error) { - console.error('unlockMission failed. Cause: ' + error.message); + console.error('unlockMission failed. Cause: ${error.message}'); } ``` @@ -791,13 +789,13 @@ let testMissionId = 2; try { missionManager.clearMission(testMissionId, (err, data) => { if (err) { - console.error('clearMission failed:' + err.message); + console.error('clearMission failed: ${err.message}'); } else { - console.info('clearMission successfully:' + JSON.stringify(data)); + console.info('clearMission successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('clearMission failed:' + err.message); + console.error('clearMission failed: ${err.message}'); } ``` @@ -834,12 +832,12 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { missionManager.clearMission(testMissionId).then((data) => { - console.info('clearMission successfully. Data: ' + JSON.stringify(data)); + console.info('clearMission successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('clearMission failed. Cause: ' + error.message); + console.error('clearMission failed. Cause: ${error.message}'); }); } catch (error) { - console.error('clearMission failed. Cause: ' + error.message); + console.error('clearMission failed. Cause: ${error.message}'); } ``` @@ -863,13 +861,13 @@ import missionManager from '@ohos.app.ability.missionManager'; try { missionManager.clearAllMissions(err => { if (err) { - console.error('clearAllMissions failed:' + err.message); + console.error('clearAllMissions failed: ${err.message}'); } else { console.info('clearAllMissions successfully.'); } }); } catch (err) { - console.error('clearAllMissions failed:' + err.message); + console.error('clearAllMissions failed: ${err.message}'); } ``` @@ -900,10 +898,10 @@ try { missionManager.clearAllMissions(bundleName).then(() => { console.info('clearAllMissions successfully.'); }).catch(err => { - console.error('clearAllMissions failed:' + err.message); + console.error('clearAllMissions failed: ${err.message}'); }); } catch (err) { - console.error('clearAllMissions failed:' + err.message); + console.error('clearAllMissions failed: ${err.message}'); } ``` @@ -935,13 +933,13 @@ let testMissionId = 2; try { missionManager.moveMissionToFront(testMissionId, (err, data) => { if (err) { - console.error('moveMissionToFront failed:' + err.message); + console.error('moveMissionToFront failed: ${err.message}'); } else { - console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + console.info('moveMissionToFront successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('moveMissionToFront failed:' + err.message); + console.error('moveMissionToFront failed: ${err.message}'); } ``` @@ -974,13 +972,13 @@ let testMissionId = 2; try { missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => { if (err) { - console.error('moveMissionToFront failed:' + err.message); + console.error('moveMissionToFront failed: ${err.message}'); } else { - console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + console.info('moveMissionToFront successfully: ${JSON.stringify(data)}'); } }); } catch (err) { - console.error('moveMissionToFront failed:' + err.message); + console.error('moveMissionToFront failed: ${err.message}'); } ``` @@ -1017,11 +1015,11 @@ import missionManager from '@ohos.app.ability.missionManager'; let testMissionId = 2; try { missionManager.moveMissionToFront(testMissionId).then((data) => { - console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data)); + console.info('moveMissionToFront successfully. Data: ${JSON.stringify(data)}'); }).catch(error => { - console.error('moveMissionToFront failed. Cause: ' + error.message); + console.error('moveMissionToFront failed. Cause: ${error.message}'); }); } catch (error) { - console.error('moveMissionToFront failed. Cause: ' + error.message); + console.error('moveMissionToFront failed. Cause: ${error.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md index a2090ed00e60cac1b5452bf6357f47cfb3c7be2e..df6469b18033a3405101d904209f1ecef534fd99 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -3,7 +3,7 @@ The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -24,7 +24,7 @@ Defines the quick fix information at the HAP file level. | ----------- | -------------------- | ---- | ------------------------------------------------------------ | | moduleName | string | Yes | Name of the HAP file. | | originHapHash | string | Yes | Hash value of the HAP file. | -| quickFixFilePath | string | Yes | Installation path of the quick fix file. | +| quickFixFilePath | string | Yes | Installation path of the quick fix patch file. | ## ApplicationQuickFixInfo @@ -57,25 +57,29 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +> **NOTE** +> +> The file path passed in the API must be an application sandbox path. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](js-apis-bundle-BundleInstaller.md#obtaining-the-sandbox-path). The path mapped to the device is **/proc/<*applicationProcessId*>/root/*sandboxPath***. **Example** - + ```ts try { - let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf']; quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { if (error) { - console.info( `applyQuickFix failed with error + ${error}`) + console.info( `applyQuickFix failed with error: ${error}`); } else { - console.info( 'applyQuickFix success') + console.info( 'applyQuickFix success'); } - }) + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error.code: ${paramError.code}, error.message: ${paramError.message}'); } ``` @@ -93,28 +97,28 @@ Applies a quick fix patch. This API uses a promise to return the result. **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.| +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise\ | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| **Example** - + ```ts - let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + let hapModuleQuickFixFiles = ['/data/storage/el2/base/entry.hqf']; try { quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { - console.info('applyQuickFix success') + console.info('applyQuickFix success'); }).catch((error) => { - console.info(`applyQuickFix err: + ${error}`) - }) + console.info(`applyQuickFix err: ${error}`); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` @@ -138,20 +142,20 @@ Obtains the quick fix information of the application. This API uses an asynchron | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| **Example** - + ```ts try { - let bundleName = "bundleName" + let bundleName = 'bundleName'; quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { if (error) { - console.info(`getApplicationQuickFixInfo error: + ${error}`) + console.info(`getApplicationQuickFixInfo error: ${error}`); } else { - console.info(`getApplicationQuickFixInfo success: + ${data}`) + console.info(`getApplicationQuickFixInfo success: ${data}`); } - }) + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } + console.log('error: ${paramError.code}, ${paramError.message}'); + } ``` ## quickFixManager.getApplicationQuickFixInfo @@ -174,21 +178,21 @@ Obtains the quick fix information of the application. This API uses a promise to **Return value** - | Type| Description| - | -------- | -------- | - | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| +| Type| Description| +| -------- | -------- | +| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| **Example** - - ```ts + + ```ts try { - let bundleName = "bundleName" + let bundleName = 'bundleName'; quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { - console.info(`getApplicationQuickFixInfo success: + ${data}`) + console.info(`getApplicationQuickFixInfo success: ${data}`); }).catch((error) => { - console.info(`getApplicationQuickFixInfo err: + ${error}`) - }) + console.info(`getApplicationQuickFixInfo err: ${error}`); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 0efdb59d5eaed4c2b70e5ff666b0c9d63b11212f..74686becf7e0f2a20d5a3f8efb07071589296330 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -49,7 +49,7 @@ Called when a ServiceExtensionAbility is created to initialize the service logic ```ts class ServiceExt extends ServiceExtension { onCreate(want) { - console.log('onCreate, want:' + want.abilityName); + console.log('onCreate, want: ${want.abilityName}'); } } ``` @@ -80,7 +80,7 @@ Called when this ServiceExtensionAbility is destroyed to clear resources. onRequest(want: Want, startId: number): void; -Called following **onCreate()** when a ServiceExtensionAbility is started by calling **startAbility()**. The value of **startId** is incremented for each ability that is started. +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **startAbility()** or **startServiceExtensionAbility()**. The value of **startId** is incremented for each ability that is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -98,7 +98,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal ```ts class ServiceExt extends ServiceExtension { onRequest(want, startId) { - console.log('onRequest, want:' + want.abilityName); + console.log('onRequest, want: ${want.abilityName}'); } } ``` @@ -129,7 +129,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal **Example** ```ts - import rpc from '@ohos.rpc' + import rpc from '@ohos.rpc'; class StubTest extends rpc.RemoteObject{ constructor(des) { super(des); @@ -139,8 +139,8 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal } class ServiceExt extends ServiceExtension { onConnect(want) { - console.log('onConnect , want:' + want.abilityName); - return new StubTest("test"); + console.log('onConnect , want: ${want.abilityName}'); + return new StubTest('test'); } } ``` @@ -167,7 +167,7 @@ Called when a client is disconnected from this ServiceExtensionAbility. ```ts class ServiceExt extends ServiceExtension { onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); + console.log('onDisconnect, want: ${want.abilityName}'); } } ``` @@ -193,7 +193,7 @@ Called when a new client attempts to connect to this ServiceExtensionAbility aft ```ts class ServiceExt extends ServiceExtension { onReconnect(want) { - console.log('onReconnect, want:' + want.abilityName); + console.log('onReconnect, want: ${want.abilityName}'); } } ``` @@ -219,7 +219,7 @@ Called when the configuration of this ServiceExtensionAbility is updated. ```ts class ServiceExt extends ServiceExtension { onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + console.log('onConfigurationUpdate, config: ${JSON.stringify(config)}'); } } ``` @@ -245,8 +245,8 @@ Dumps the client information. ```ts class ServiceExt extends ServiceExtension { onDump(params) { - console.log('dump, params:' + JSON.stringify(params)); - return ["params"] + console.log('dump, params: ${JSON.stringify(params)}'); + return ['params']; } } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index 3e95fbf541e7ed79834673c2ca97b1398bc73989..54200ed3e7e27043eb2798522a3fd1c991eca5a3 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -18,7 +18,37 @@ import StartOptions from '@ohos.app.ability.StartOptions'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| +| [windowMode](js-apis-app-ability-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| | displayId | number | No| Display ID. The default value is **0**, indicating the current display.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos('', 10, (error, missions) => { + if (error.code) { + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + return; + } + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; + + let startOptions = { + windowMode : 101, + displayId: 0 + }; + missionManager.moveMissionToFront(id, startOptions).then(() => { + console.log('moveMissionToFront is called '); + }); + }); + } catch (paramError) { + console.log('error: ${paramError.code}, ${paramError.message}'); + } + ``` 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 38d9f5428c37873ae9f786ed0f391142f30a011b..d840fd6854292aa876ecd3777e7cedc96b5e95bb 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 @@ -47,7 +47,7 @@ Called to initialize the service logic when a UIAbility is created. ```ts class MyUIAbility extends UIAbility { onCreate(want, param) { - console.log('onCreate, want:' + want.abilityName); + console.log('onCreate, want: ${want.abilityName}'); } } ``` @@ -202,11 +202,11 @@ Called to save data during the ability migration preparation process. **Example** ```ts - import AbilityConstant from "@ohos.app.ability.AbilityConstant" + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { onContinue(wantParams) { console.log('onContinue'); - wantParams["myData"] = "my1234567"; + wantParams['myData'] = 'my1234567'; return AbilityConstant.OnContinueResult.AGREE; } } @@ -233,8 +233,8 @@ Called when a new Want is passed in and this UIAbility is started again. ```ts class MyUIAbility extends UIAbility { onNewWant(want, launchParams) { - console.log('onNewWant, want:' + want.abilityName); - console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); + console.log('onNewWant, want: ${want.abilityName}'); + console.log('onNewWant, launchParams: ${JSON.stringify(launchParams)}'); } } ``` @@ -258,8 +258,8 @@ Dumps client information. ```ts class MyUIAbility extends UIAbility { onDump(params) { - console.log('dump, params:' + JSON.stringify(params)); - return ["params"] + console.log('dump, params: ${JSON.stringify(params)}'); + return ['params']; } } ``` @@ -289,12 +289,12 @@ Called when the framework automatically saves the UIAbility state in the case of **Example** ```ts -import AbilityConstant from '@ohos.app.ability.AbilityConstant' +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; class MyUIAbility extends UIAbility { onSaveState(reason, wantParam) { console.log('onSaveState'); - wantParam["myData"] = "my1234567"; + wantParam['myData'] = 'my1234567'; return AbilityConstant.OnSaveResult.RECOVERY_AGREE; } } @@ -339,8 +339,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts class MyMessageAble{ // Custom sequenceable data structure. - name:"" - str:"" + name:'' + str:'' num: 1 constructor(name, str) { this.name = name; @@ -349,38 +349,36 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error marshalling(messageParcel) { messageParcel.writeInt(this.num); messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } unmarshalling(messageParcel) { this.num = messageParcel.readInt(); this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); return true; } }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities. - var caller; + let method = 'call_Function'; // Notification message string negotiated by the two abilities. + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' }).then((obj) => { caller = obj; - let msg = new MyMessageAble("msg", "world"); // See the definition of Sequenceable. + let msg = new MyMessageAble('msg', 'world'); // See the definition of Sequenceable. caller.call(method, msg) .then(() => { console.log('Caller call() called'); }) .catch((callErr) => { - console.log('Caller.call catch error, error.code: ' + JSON.stringify(callErr.code) + - ' error.message: ' + JSON.stringify(callErr.message)); + console.log('Caller.call catch error, error.code: ${JSON.stringify(callErr.code)}, error.message: ${JSON.stringify(callErr.message)}'); }); }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); + console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); }); } } @@ -420,8 +418,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts class MyMessageAble{ - name:"" - str:"" + name:'' + str:'' num: 1 constructor(name, str) { this.name = name; @@ -430,40 +428,38 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error marshalling(messageParcel) { messageParcel.writeInt(this.num); messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } unmarshalling(messageParcel) { this.num = messageParcel.readInt(); this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]'); return true; } }; - var method = 'call_Function'; - var caller; + let method = 'call_Function'; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' }).then((obj) => { caller = obj; - let msg = new MyMessageAble(1, "world"); + let msg = new MyMessageAble(1, 'world'); caller.callWithResult(method, msg) .then((data) => { console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); + let retmsg = new MyMessageAble(0, ''); data.readSequenceable(retmsg); }) .catch((callErr) => { - console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) + - ' error.message: ' + JSON.stringify(callErr.message)); + console.log('Caller.callWithResult catch error, error.code: ${JSON.stringify(callErr.code)}, error.message: ${JSON.stringify(callErr.message)}'); }); }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); + console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); }); } } @@ -490,24 +486,22 @@ Releases the caller interface of the target ability. **Example** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' }).then((obj) => { caller = obj; try { caller.release(); } catch (releaseErr) { - console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + - ' error.message: ' + JSON.stringify(releaseErr.message)); + console.log('Caller.release catch error, error.code: ${JSON.stringify(releaseErr.code)}, error.message: ${JSON.stringify(releaseErr.message)}'); } }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); + console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); }); } } @@ -525,31 +519,29 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| **Example** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' }).then((obj) => { caller = obj; try { caller.onRelease((str) => { - console.log(' Caller OnRelease CallBack is called ' + str); + console.log(' Caller OnRelease CallBack is called ${str}'); }); } catch (error) { - console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('Caller.onRelease catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); + console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); }); } } @@ -557,7 +549,7 @@ Registers a callback that is invoked when the stub on the target ability is disc ## Caller.on - on(type: "release", callback: OnReleaseCallback): void; + on(type: 'release', callback: OnReleaseCallback): void; Registers a callback that is invoked when the stub on the target ability is disconnected. @@ -568,7 +560,7 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **release**.| -| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| **Error codes** @@ -581,31 +573,127 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts - var caller; + let caller; export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startUIAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainUIAbility", - deviceId: "" + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' }).then((obj) => { caller = obj; try { - caller.on("release", (str) => { - console.log(' Caller OnRelease CallBack is called ' + str); + caller.on('release', (str) => { + console.log(' Caller OnRelease CallBack is called ${str}'); }); } catch (error) { - console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('Caller.on catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); + console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); }); } } ``` +## Caller.off + +off(type: 'release', callback: OnReleaseCallback): void; + +Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is fixed at **release**.| +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + let caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' + }).then((obj) => { + caller = obj; + try { + let onReleaseCallBack = (str) => { + console.log(' Caller OnRelease CallBack is called ${str}'); + }; + caller.on('release', onReleaseCallBack); + caller.off('release', onReleaseCallBack); + } catch (error) { + console.log('Caller.on or Caller.off catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); + }); + } + } + ``` + +## Caller.off + +off(type: 'release'): void; + +Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is fixed at **release**.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | +For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + let caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: 'com.example.myservice', + abilityName: 'MainUIAbility', + deviceId: '' + }).then((obj) => { + caller = obj; + try { + let onReleaseCallBack = (str) => { + console.log(' Caller OnRelease CallBack is called ${str}'); + }; + caller.on('release', onReleaseCallBack); + caller.off('release'); + } catch (error) { + console.error('Caller.on or Caller.off catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + } + }).catch((err) => { + console.error('Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}'); + }); + } + } + ``` ## Callee @@ -638,8 +726,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts class MyMessageAble{ - name:"" - str:"" + name:'' + str:'' num: 1 constructor(name, str) { this.name = name; @@ -648,22 +736,22 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error marshalling(messageParcel) { messageParcel.writeInt(this.num); messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); return true; } unmarshalling(messageParcel) { this.num = messageParcel.readInt(); this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); return true; } }; - var method = 'call_Function'; + let method = 'call_Function'; function funcCallBack(pdata) { - console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble("test", ""); + console.log('Callee funcCallBack is called ${pdata}'); + let msg = new MyMessageAble('test', ''); pdata.readSequenceable(msg); - return new MyMessageAble("test1", "Callee test"); + return new MyMessageAble('test1', 'Callee test'); } export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { @@ -671,8 +759,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error try { this.callee.on(method, funcCallBack); } catch (error) { - console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('Callee.on catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } } } @@ -704,15 +791,14 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts - var method = 'call_Function'; + let method = 'call_Function'; export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { this.callee.off(method); } catch (error) { - console.log('Callee.off catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('Callee.off catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } } } diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md index c96e29d90f3a10a563df41bc8a545cb42dfdeba4..0411725e055551e68d2902705f3e904592587a1d 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -22,115 +22,133 @@ import Want from '@ohos.app.ability.Want'; | bundleName | string | No | Bundle name of the ability.| | moduleName | string | No| Name of the module to which the ability belongs.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| -| [action](js-apis-app-ability-wantConstant.md#wantconstantaction) | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | -| [entities](js-apis-app-ability-wantConstant.md#wantconstantentity) | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| +| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | +| entities | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| | uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | string | No| MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| type | string | No| MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | | [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| **Example** -- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). +- Basic usage: called in a UIAbility object, as shown in the example below. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). ```ts - let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "FuncAbility", - "moduleName": "entry" // moduleName is optional. - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + let want = { + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.example.myapplication', + 'abilityName': 'FuncAbility', + 'moduleName': 'entry' // moduleName is optional. + }; + + this.context.startAbility(want, (err) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` -- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility): +- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, as shown in the example below. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).) * String ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", - parameters: { - keyForString: "str", - }, - } + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + parameters: { + keyForString: 'str', + }, + }; + + this.context.startAbility(want, (err) => { + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` * Number ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", - parameters: { - keyForInt: 100, - keyForDouble: 99.99, - }, - } + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + parameters: { + keyForInt: 100, + keyForDouble: 99.99, + }, + }; + + this.context.startAbility(want, (err) => { + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` * Boolean ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", - parameters: { - keyForBool: true, - }, - } + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + parameters: { + keyForBool: true, + }, + }; + + this.context.startAbility(want, (err) => { + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` * Object ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", - parameters: { - keyForObject: { - keyForObjectString: "str", - keyForObjectInt: -200, - keyForObjectDouble: 35.5, - keyForObjectBool: false, - }, + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + parameters: { + keyForObject: { + keyForObjectString: 'str', + keyForObjectInt: -200, + keyForObjectDouble: 35.5, + keyForObjectBool: false, }, - } + }, + }; + + this.context.startAbility(want, (err) => { + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` * Array ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "FuncAbility", - parameters: { - keyForArrayString: ["str1", "str2", "str3"], - keyForArrayInt: [100, 200, 300, 400], - keyForArrayDouble: [0.1, 0.2], - keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], - }, - } + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + parameters: { + keyForArrayString: ['str1', 'str2', 'str3'], + keyForArrayInt: [100, 200, 300, 400], + keyForArrayDouble: [0.1, 0.2], + keyForArrayObject: [{ obj1: 'aaa' }, { obj2: 100 }], + }, + }; + + this.context.startAbility(want, (err) => { + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` * File descriptor (FD) ```ts import fileio from '@ohos.fileio'; + let fd; try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); + console.log('openSync fail: ${JSON.stringify(e)}'); } let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "FuncAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} - } + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.example.myapplication', + 'abilityName': 'FuncAbility', + 'moduleName': 'entry', // moduleName is optional. + 'parameters': { + 'keyFd': { 'type': 'FD', 'value': fd } // {'type':'FD', 'value':fd} is a fixed usage, indicating that the data is a file descriptor. + } }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + + this.context.startAbility(want, (err) => { + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); ``` - -- For more details and examples, see [Want](../../application-models/want-overview.md). - - diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md index 43b95743b25c34bdae9457c1e1ed1cf01f8e986e..11ac3b8a692f8e67d33d090b78542b40c155c1eb 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -16,7 +16,7 @@ import WantAgent from '@ohos.app.ability.wantAgent'; getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void -Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. +Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. If the creation fails, a null **WantAgent** object is returned. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -85,20 +85,20 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(err)); + console.error('getWantAgent failed, error: ${JSON.stringify(err)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.error('getWantAgent failed, error: ${JSON.stringify(err)}'); } ``` @@ -108,7 +108,7 @@ try { getWantAgent(info: WantAgentInfo): Promise\ -Obtains a **WantAgent** object. This API uses a promise to return the result. +Obtains a **WantAgent** object. This API uses a promise to return the result. If the creation fails, a null **WantAgent** object is returned. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -180,16 +180,16 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; try { WantAgent.getWantAgent(wantAgentInfo).then((data) => { wantAgent = data; }).catch((err) => { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); }); } catch (err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -268,33 +268,33 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); } // getBundleName callback function getBundleNameCallback(err, data) { if(err) { - console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { - console.info('getBundleName ok!' + JSON.stringify(data)); + console.info('getBundleName ok! ${JSON.stringify(data)}'); } } try { WantAgent.getBundleName(wantAgent, getBundleNameCallback); } catch(err) { - console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -378,29 +378,29 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); } try { WantAgent.getBundleName(wantAgent).then((data)=>{ - console.info('getBundleName ok!' + JSON.stringify(data)); + console.info('getBundleName ok! ${JSON.stringify(data)}'); }).catch((err)=>{ - console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); - }) + console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); + }); } catch(err){ - console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getBundleName failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -480,33 +480,33 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(err)); + console.info('getWantAgent failed ${JSON.stringify(err)}'); } // getUid callback function getUidCallback(err, data) { if(err) { - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { - console.info('getUid ok!' + JSON.stringify(data)); + console.info('getUid ok! ${JSON.stringify(data)}'); } } try { WantAgent.getUid(wantAgent, getUidCallback); } catch(err) { - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -590,29 +590,29 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); } try { WantAgent.getUid(wantAgent).then((data)=>{ - console.info('getUid ok!' + JSON.stringify(data)); + console.info('getUid ok! ${JSON.stringify(data)}'); }).catch((err)=>{ - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); - }) + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); + }); } catch(err){ - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -692,33 +692,33 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); } - // getUid callback + // getWant callback function getWantCallback(err, data) { if(err) { - console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWant failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { - console.info('getWant ok!' + JSON.stringify(data)); + console.info('getWant ok! ${JSON.stringify(data)}'); } } try { - WantAgent.getWant(wantAgent, getBundleNameCallback); + WantAgent.getWant(wantAgent, getWantCallback); } catch(err) { - console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWant failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -804,29 +804,29 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); } try { WantAgent.getUid(wantAgent).then((data)=>{ - console.info('getUid ok!' + JSON.stringify(data)); + console.info('getUid ok! ${JSON.stringify(data)}'); }).catch((err)=>{ - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); - }) + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); + }); } catch(err){ - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -905,33 +905,33 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); } - // getUid callback + // cancel callback function cancelCallback(err, data) { if(err) { - console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { console.info('cancel ok!'); } } try { - WantAgent.cancel(wantAgent, getBundleNameCallback); + WantAgent.cancel(wantAgent, cancelCallback); } catch(err) { - console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1015,29 +1015,29 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); } try { WantAgent.cancel(wantAgent).then((data)=>{ console.info('cancel ok!'); }).catch((err)=>{ - console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); - }) + console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); + }); } catch(err){ - console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('cancel failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1091,8 +1091,8 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error let wantAgent; // triggerInfo let triggerInfo = { - code: 0 // Custom result code. - } + code: 0 // Custom result code. +}; // WantAgentInfo object let wantAgentInfo = { wants: [ @@ -1119,33 +1119,33 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); } - // getUid callback + // trigger callback function triggerCallback(err, data) { if(err) { - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { - console.info('getUid ok!' + JSON.stringify(data)); + console.info('getUid ok! ${JSON.stringify(data)}'); } } try { WantAgent.trigger(wantAgent, triggerInfo, triggerCallback); } catch(err) { - console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getUid failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1164,7 +1164,7 @@ Checks whether two **WantAgent** objects are equal to determine whether the same | Name | Type | Mandatory| Description | | ---------- | ------------------------ | ---- | --------------------------------------- | | agent | WantAgent | Yes | The first **WantAgent** object. | -| otherAgent | WantAgent | Yes | The second **WantAgent** object. | +| otherAgent | WantAgent | Yes | Target **WantAgent** object. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -1226,7 +1226,7 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { @@ -1234,26 +1234,26 @@ function getWantAgentCallback(err, data) { wantAgent1 = data; wantAgent2 = data; } else { - console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); } - // getUid callback + // equal callback function equalCallback(err, data) { if(err) { - console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { - console.info('equal ok!' + JSON.stringify(data)); + console.info('equal ok! ${JSON.stringify(data)}'); } } try { WantAgent.equal(wantAgent1,wantAgent2,equalCallback); } catch(err) { - console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1272,7 +1272,7 @@ Checks whether two **WantAgent** objects are equal to determine whether the same | Name | Type | Mandatory| Description | | ---------- | --------- | ---- | ------------- | | agent | WantAgent | Yes | The first **WantAgent** object.| -| otherAgent | WantAgent | Yes | The second **WantAgent** object.| +| otherAgent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -1339,7 +1339,7 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { @@ -1347,22 +1347,22 @@ function getWantAgentCallback(err, data) { wantAgent1 = data; wantAgent2 = data; } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); } try { WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{ - console.info('equal ok!' + JSON.stringify(data)); + console.info('equal ok! ${JSON.stringify(data)}'); }).catch((err)=>{ - console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); }) } catch(err){ - console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('equal failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1439,33 +1439,33 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed ${JSON.stringify(wantAgent)}'); } - // getUid callback + // getOperationTypeCallback callback function getOperationTypeCallback(err, data) { if(err) { - console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } else { - console.info('getOperationType ok!' + JSON.stringify(data)); + console.info('getOperationType ok! ${JSON.stringify(data)}'); } } try { - WantAgent.getOperationTypeCallback(wantAgent, getBundleNameCallback); + WantAgent.getOperationTypeCallback(wantAgent, getOperationTypeCallback); } catch(err) { - console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getOperationTypeCallback failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1547,29 +1547,29 @@ let wantAgentInfo = { operationType: WantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} +}; // getWantAgent callback function getWantAgentCallback(err, data) { if (err === undefined) { wantAgent = data; } else { - console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + console.info('getWantAgent failed! ${JSON.stringify(wantAgent)}'); } try { WantAgent.getOperationType(wantAgent).then((data)=>{ - console.info('getOperationType ok!' + JSON.stringify(data)); + console.info('getOperationType ok! ${JSON.stringify(data)}'); }).catch((err)=>{ - console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); - }) + console.info('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); + }); } catch(err){ - console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getOperationType failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } } try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + console.info('getWantAgent failed! ${JSON.stringify(err.code)} ${JSON.stringify(err.message)}'); } ``` @@ -1615,5 +1615,5 @@ try { | info | WantAgent | Yes | A triggered **WantAgent** object. | | want | Want | Yes | An existing triggered **want**. | | finalCode | number | Yes | Request code that triggers the **WantAgent** object.| -| finalData | string | No | Final data collected by the common event. | +| finalData | string | Yes | Final data collected by the common event. | | extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md index 4d7a483eab8a55c91d4dbb89287fa611f980ef34..03e519e65568fbbc9de2f33711c01347a12ffb4c 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -8,65 +8,21 @@ The **wantConstant** module provides the actions, entities, and flags used in ** ## Modules to Import -```js +```ts import wantConstant from '@ohos.app.ability.wantConstant'; ``` -## wantConstant.Action +## wantConstant.Params -Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. +Defines **Params** (specifying the action that can be performed) in the Want. -**System capability**: SystemCapability.Ability.AbilityBase - -| Name | Value | Description | -| ------------ | ------------------ | ---------------------- | -| ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | -| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | -| ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | -| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. | -| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | -| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | -| ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | -| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all alarms. | -| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | -| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | -| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | -| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | -| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for opening a contact or picture. | -| ACTION_IMAGE_CAPTURE | ohos.want.action.imageCapture | Action of launching the UI for photographing. | -| ACTION_VIDEO_CAPTURE | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | -| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | -| ACTION_SEND_DATA | ohos.want.action.sendData | Action of launching the UI for sending a single data record. | -| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | Action of launching the UI for sending multiple data records. | -| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | Action of requesting a media scanner to scan a file and add the file to the media library. | -| ACTION_VIEW_DATA | ohos.want.action.viewData | Action of viewing data. | -| ACTION_EDIT_DATA | ohos.want.action.editData | Action of editing data. | -| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | -| INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. | -| ACTION_FILE_SELECT | ohos.action.fileSelect | Action of selecting a file. | -| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. | -| ACTION_APP_ACCOUNT_AUTH | account.appAccount.action.auth | Action of providing the authentication service. | -| ACTION_MARKET_DOWNLOAD | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | -| ACTION_MARKET_CROWDTEST | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_SANDBOX |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_BUNDLE_NAME |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_MODULE_NAME |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_ABILITY_NAME |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications. | -| DLP_PARAMS_INDEX |ohos.dlp.params.index |Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications. | - -## wantConstant.Entity - -Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name | Value | Description | -| ------------ | ------------------ | ---------------------- | -| ENTITY_DEFAULT | entity.system.default | Default entity. The default entity is used if no entity is specified. | -| ENTITY_HOME | entity.system.home | Home screen entity. | -| ENTITY_VOICE | entity.system.voice | Voice interaction entity. | -| ENTITY_BROWSABLE | entity.system.browsable | Browser type entity. | -| ENTITY_VIDEO | entity.system.video | Video type entity. | +| Name | Value | Description | +| ----------------------- | --------------------------- | ------------------------------------------------------------ | +| DLP_PARAMS_SANDBOX | ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications.| +| DLP_PARAMS_BUNDLE_NAME | ohos.dlp.params.bundleName | Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications.| +| DLP_PARAMS_MODULE_NAME | ohos.dlp.params.moduleName | Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications.| +| DLP_PARAMS_ABILITY_NAME | ohos.dlp.params.abilityName | Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications.| +| DLP_PARAMS_INDEX | ohos.dlp.params.index | Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications.| ## wantConstant.Flags diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md index 51637975d72ea807f428f235aec90310f69b197f..fa8e44aa0b0e5a06d88891214baab112d0ce47b6 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -35,7 +35,7 @@ Creates a **FormBindingData** object. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| +| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by **'formImages'**, and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {'formImages': {'key1': fd1, 'key2': fd2}}.| **Return value** @@ -48,14 +48,14 @@ Creates a **FormBindingData** object. **Example** ```ts -import fs from '@ohos.file.fs'; import formBindingData from '@ohos.app.form.formBindingData'; +import fs from '@ohos.file.fs'; try { - let fd = fs.openSync('/path/to/form.png') + let fd = fs.openSync('/path/to/form.png'); let obj = { - "temperature": "21°", - "formImages": { "image": fd } + 'temperature': '21°', + 'formImages': { 'image': fd } }; formBindingData.createFormBindingData(obj); } catch (error) { diff --git a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index ef4e93e215b868013f025722737472735a1016f7..345f889f31e3d31cb834b03e9b5ecbde12aaabfe 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -49,10 +49,10 @@ import formBindingData from '@ohos.app.form.formBindingData'; export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want) { - console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); + console.log('FormExtensionAbility onAddForm, want: ${want.abilityName}'); let dataObj1 = { - temperature: "11c", - "time": "11:00" + temperature: '11c', + 'time': '11:00' }; let obj1 = formBindingData.createFormBindingData(dataObj1); return obj1; @@ -81,7 +81,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onCastToNormalForm(formId) { - console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); + console.log('FormExtensionAbility onCastToNormalForm, formId: ${formId}'); } }; ``` @@ -109,15 +109,15 @@ import formProvider from '@ohos.app.form.formProvider'; export default class MyFormExtensionAbility extends FormExtensionAbility { onUpdateForm(formId) { - console.log('FormExtensionAbility onUpdateForm, formId:' + formId); + console.log('FormExtensionAbility onUpdateForm, formId: ${formId}'); let obj2 = formBindingData.createFormBindingData({ - temperature: "22c", - time: "22:00" + temperature: '22c', + time: '22:00' }); formProvider.updateForm(formId, obj2).then((data) => { - console.log('FormExtensionAbility context updateForm, data:' + data); + console.log('FormExtensionAbility context updateForm, data: ${data}'); }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error); + console.error('Operation updateForm failed. Cause: ${error}'); }); } }; @@ -141,23 +141,23 @@ Called to notify the widget provider of the change of visibility. ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; -import formBindingData from '@ohos.app.form.formBindingData' +import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; export default class MyFormExtensionAbility extends FormExtensionAbility { onChangeFormVisibility(newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); + console.log('FormExtensionAbility onChangeFormVisibility, newStatus: ${newStatus}'); let obj2 = formBindingData.createFormBindingData({ - temperature: "22c", - time: "22:00" + temperature: '22c', + time: '22:00' }); for (let key in newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); + console.log('FormExtensionAbility onChangeFormVisibility, key: ${key}, value= ${newStatus[key]}'); formProvider.updateForm(key, obj2).then((data) => { - console.log('FormExtensionAbility context updateForm, data:' + data); + console.log('FormExtensionAbility context updateForm, data: ${data}'); }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error); + console.error('Operation updateForm failed. Cause: ${error}'); }); } } @@ -186,7 +186,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onFormEvent(formId, message) { - console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + console.log('FormExtensionAbility onFormEvent, formId: ${formId}, message: ${message}'); } }; ``` @@ -212,7 +212,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onRemoveForm(formId) { - console.log('FormExtensionAbility onRemoveForm, formId:' + formId); + console.log('FormExtensionAbility onRemoveForm, formId: ${formId}'); } }; ``` @@ -238,7 +238,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + console.log('onConfigurationUpdate, config: ${JSON.stringify(config)}'); } }; ``` @@ -265,7 +265,7 @@ import formInfo from '@ohos.app.form.formInfo'; export default class MyFormExtensionAbility extends FormExtensionAbility { onAcquireFormState(want) { - console.log('FormExtensionAbility onAcquireFormState, want:' + want); + console.log('FormExtensionAbility onAcquireFormState, want: ${want}'); return formInfo.FormState.UNKNOWN; } }; @@ -300,10 +300,10 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onShareForm(formId) { - console.log('FormExtensionAbility onShareForm, formId:' + formId); + console.log('FormExtensionAbility onShareForm, formId: ${formId}'); let wantParams = { - "temperature": "20", - "time": "2022-8-8 09:59", + 'temperature': '20', + 'time': '2022-8-8 09:59', }; return wantParams; } diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md index e78cf3647a1298ed77b4993d811393ede4e2e5b6..e54e2cc798f8774fcc487d94c2ad9b514c42f897 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -43,7 +43,7 @@ Deletes a widget. After this API is called, the application can no longer use th import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.deleteForm(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -92,7 +92,7 @@ Deletes a widget. After this API is called, the application can no longer use th import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { @@ -133,7 +133,7 @@ Releases a widget. After this API is called, the application can no longer use t import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.releaseForm(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -175,7 +175,7 @@ Releases a widget. After this API is called, the application can no longer use t import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.releaseForm(formId, true, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -222,7 +222,7 @@ Releases a widget. After this API is called, the application can no longer use t import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { @@ -263,7 +263,7 @@ Requests a widget update. This API uses an asynchronous callback to return the r import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.requestForm(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -309,7 +309,7 @@ Requests a widget update. This API uses a promise to return the result. import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { @@ -351,7 +351,7 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.castToNormalForm(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -397,7 +397,7 @@ Converts a temporary widget to a normal one. This API uses a promise to return t import formHost from '@ohos.app.form.formHost'; try { - let formId = "12400633174999288"; + let formId = '12400633174999288'; formHost.castToNormalForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { @@ -438,7 +438,7 @@ Instructs the widget framework to make a widget visible. After this API is calle import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -484,7 +484,7 @@ Instructs the widget framework to make a widget visible. After this API is calle import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { @@ -525,7 +525,7 @@ Instructs the widget framework to make a widget invisible. After this API is cal import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -571,7 +571,7 @@ Instructs the widget framework to make a widget invisible. After this API is cal import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { @@ -612,7 +612,7 @@ Instructs the widget framework to make a widget updatable. After this API is cal import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -658,7 +658,7 @@ Instructs the widget framework to make a widget updatable. After this API is cal import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { @@ -699,7 +699,7 @@ Instructs the widget framework to make a widget not updatable. After this API is import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId, (error) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); @@ -745,7 +745,7 @@ Instructs the widget framework to make a widget not updatable. After this API is import formHost from '@ohos.app.form.formHost'; try { - let formId = ["12400633174999288"]; + let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { @@ -842,7 +842,7 @@ try { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch(error) { @@ -873,7 +873,7 @@ import formHost from '@ohos.app.form.formHost'; try { formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo data: ${JSON.stringify(data)}'); }).catch((error) => { console.log(`error, code: ${error.code}, message: ${error.message}`); }); @@ -912,11 +912,11 @@ Obtains the widget information provided by a given application on the device. Th import formHost from '@ohos.app.form.formHost'; try { - formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { + formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch(error) { @@ -955,11 +955,11 @@ Obtains the widget information provided by a given application on the device. Th import formHost from '@ohos.app.form.formHost'; try { - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { + formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch(error) { @@ -1003,8 +1003,8 @@ Obtains the widget information provided by a given application on the device. Th import formHost from '@ohos.app.form.formHost'; try { - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data) => { + console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); }).catch((error) => { console.log(`error, code: ${error.code}, message: ${error.message}`); }); @@ -1036,12 +1036,12 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to import formHost from '@ohos.app.form.formHost'; try { - let formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds, (error, data) => { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + console.log('formHost deleteInvalidForms, data: ${JSON.stringify(data)}'); } }); } catch(error) { @@ -1077,9 +1077,9 @@ Deletes invalid widgets from the list. This API uses a promise to return the res import formHost from '@ohos.app.form.formHost'; try { - let formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds).then((data) => { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + console.log('formHost deleteInvalidForms, data: ${JSON.stringify(data)}'); }).catch((error) => { console.log(`error, code: ${error.code}, message: ${error.message}`); }); @@ -1118,13 +1118,13 @@ Obtains the widget state. This API uses an asynchronous callback to return the r import formHost from '@ohos.app.form.formHost'; let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; try { @@ -1132,7 +1132,7 @@ try { if (error) { console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + console.log('formHost acquireFormState, data: ${JSON.stringify(data)}'); } }); } catch(error) { @@ -1175,18 +1175,18 @@ Obtains the widget state. This API uses a promise to return the result. import formHost from '@ohos.app.form.formHost'; let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; try { formHost.acquireFormState(want).then((data) => { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + console.log('formHost acquireFormState, data: ${JSON.stringify(data)}'); }).catch((error) => { console.log(`error, code: ${error.code}, message: ${error.message}`); }); @@ -1195,9 +1195,9 @@ try { } ``` -## on("formUninstall") +## on('formUninstall') -on(type: "formUninstall", callback: Callback<string>): void +on(type: 'formUninstall', callback: Callback<string>): void Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. @@ -1207,7 +1207,7 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.| | callback | Callback<string> | Yes| Callback used to return the widget ID.| **Example** @@ -1216,14 +1216,14 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to import formHost from '@ohos.app.form.formHost'; let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); + console.log('formHost on formUninstall, formId: ${formId}'); } -formHost.on("formUninstall", callback); +formHost.on('formUninstall', callback); ``` -## off("formUninstall") +## off('formUninstall') -off(type: "formUninstall", callback?: Callback<string>): void +off(type: 'formUninstall', callback?: Callback<string>): void Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. @@ -1233,8 +1233,8 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on("formUninstall")**.| +| type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on('formUninstall')**.| **Example** @@ -1242,9 +1242,9 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac import formHost from '@ohos.app.form.formHost'; let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); + console.log('formHost on formUninstall, formId: ${formId}'); } -formHost.off("formUninstall", callback); +formHost.off('formUninstall', callback); ``` ## notifyFormsVisible @@ -1277,7 +1277,7 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous ```ts import formHost from '@ohos.app.form.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsVisible(formIds, true, (error) => { if (error) { @@ -1324,7 +1324,7 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret ```ts import formHost from '@ohos.app.form.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); @@ -1366,7 +1366,7 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou ```ts import formHost from '@ohos.app.form.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsEnableUpdate(formIds, true, (error) => { if (error) { @@ -1413,7 +1413,7 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r ```ts import formHost from '@ohos.app.form.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); @@ -1454,8 +1454,8 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca ```ts import formHost from '@ohos.app.form.formHost'; -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +let formId = '12400633174999288'; +let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; try { formHost.shareForm(formId, deviceId, (error) => { if (error) { @@ -1502,8 +1502,8 @@ Shares a specified widget with a remote device. This API uses a promise to retur ```ts import formHost from '@ohos.app.form.formHost'; -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +let formId = '12400633174999288'; +let deviceId = 'EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2'; try { formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); @@ -1545,7 +1545,7 @@ Notifies that the privacy protection status of the specified widgets changes. Th ```ts import formHost from '@ohos.app.form.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsPrivacyProtected(formIds, true, (error) => { if (error) { @@ -1590,7 +1590,7 @@ Notifies that the privacy protection status of the specified widgets changes. Th ```ts import formHost from '@ohos.app.form.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); try { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { console.log('formHost notifyFormsPrivacyProtected success'); diff --git a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md index 84b40a57a56038b89ddf7ee06caef5f492e252f0..09a6ae02c63c18073836925ad9b6399e48fdd67d 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -31,7 +31,6 @@ Describes widget information. | isDefault | boolean | Yes | No | Whether the widget is the default one. | | updateEnabled | boolean | Yes | No | Whether the widget is updatable. | | formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. | -| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | | scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | | formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed. | | updateDuration | number | Yes | No | Update period of the widget.| @@ -93,16 +92,16 @@ Enumerates the widget parameters. | Name | Value | Description | | ----------- | ---- | ------------ | -| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | Widget ID. | -| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | -| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | -| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | -| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | -| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | -| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | -| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. | -| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID. | -| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| +| IDENTITY_KEY | 'ohos.extra.param.key.form_identity' | Widget ID. | +| DIMENSION_KEY | 'ohos.extra.param.key.form_dimension' | Widget dimension. | +| NAME_KEY | 'ohos.extra.param.key.form_name' | Widget name. | +| MODULE_NAME_KEY | 'ohos.extra.param.key.module_name' | Name of the module to which the widget belongs. | +| WIDTH_KEY | 'ohos.extra.param.key.form_width' | Widget width. | +| HEIGHT_KEY | 'ohos.extra.param.key.form_height' | Widget height. | +| TEMPORARY_KEY | 'ohos.extra.param.key.form_temporary' | Temporary widget. | +| ABILITY_NAME_KEY | 'ohos.extra.param.key.ability_name' | Ability name. | +| DEVICE_ID_KEY | 'ohos.extra.param.key.device_id' | Device ID. | +| BUNDLE_NAME_KEY | 'ohos.extra.param.key.bundle_name' | Key that specifies the target bundle name.| ## FormDimension diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md index 8b314c792e584149219e7baf46e05cc9cdb9033f..5815289bcf5258156932e938843bdb3d0ff4c441 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -39,7 +39,7 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback ```ts import formProvider from '@ohos.app.form.formProvider'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error) { @@ -86,7 +86,7 @@ Sets the next refresh time for a widget. This API uses a promise to return the r ```ts import formProvider from '@ohos.app.form.formProvider'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { console.log(`formProvider setFormNextRefreshTime success`); @@ -127,9 +127,9 @@ Updates a widget. This API uses an asynchronous callback to return the result. import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; try { - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); formProvider.updateForm(formId, obj, (error, data) => { if (error) { console.log(`callback error, code: ${error.code}, message: ${error.message})`); @@ -176,8 +176,8 @@ Updates a widget. This API uses a promise to return the result. import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; -let formId = "12400633174999288"; -let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); +let formId = '12400633174999288'; +let obj = formBindingData.createFormBindingData({ temperature: '22c', time: '22:00' }); try { formProvider.updateForm(formId, obj).then(() => { console.log(`formProvider updateForm success`); @@ -221,7 +221,7 @@ try { if (error) { console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch (error) { @@ -258,14 +258,14 @@ import formProvider from '@ohos.app.form.formProvider'; const filter: formInfo.FormInfoFilter = { // get info of forms belong to module entry. - moduleName: "entry" + moduleName: 'entry' }; try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); } }); } catch (error) { @@ -308,11 +308,11 @@ import formProvider from '@ohos.app.form.formProvider'; const filter: formInfo.FormInfoFilter = { // get info of forms belong to module entry. - moduleName: "entry" + moduleName: 'entry' }; try { formProvider.getFormsInfo(filter).then((data) => { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ${JSON.stringify(data)}'); }).catch((error) => { console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); @@ -335,7 +335,7 @@ Requests to publish a widget carrying data to the widget host. This API uses an | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
'ohos.extra.param.key.form_dimension'
'ohos.extra.param.key.form_name'
'ohos.extra.param.key.module_name' | | formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| | callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| @@ -353,20 +353,20 @@ import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; let want = { - abilityName: "FormAbility", + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' } }; try { - let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); + let obj = formBindingData.createFormBindingData({ temperature: '22c', time: '22:00' }); formProvider.requestPublishForm(want, obj, (error, data) => { if (error) { console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); } }); } catch (error) { @@ -388,7 +388,7 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
'ohos.extra.param.key.form_dimension'
'ohos.extra.param.key.form_name'
'ohos.extra.param.key.module_name' | | callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| **Error codes** @@ -404,11 +404,11 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c import formProvider from '@ohos.app.form.formProvider'; let want = { - abilityName: "FormAbility", + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' } }; try { @@ -416,7 +416,7 @@ try { if (error) { console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); } }); } catch (error) { @@ -438,7 +438,7 @@ Requests to publish a widget to the widget host. This API uses a promise to retu | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
'ohos.extra.param.key.form_dimension'
'ohos.extra.param.key.form_name'
'ohos.extra.param.key.module_name' | | formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | **Return value** @@ -460,16 +460,16 @@ Requests to publish a widget to the widget host. This API uses a promise to retu import formProvider from '@ohos.app.form.formProvider'; let want = { - abilityName: "FormAbility", + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' } }; try { formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + console.log('formProvider requestPublishForm success, form ID is : ${JSON.stringify(data)}'); }).catch((error) => { console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); @@ -506,11 +506,11 @@ try { } else { if (isSupported) { var want = { - abilityName: "FormAbility", + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' } }; try { @@ -518,7 +518,7 @@ try { if (error) { console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + console.log('formProvider requestPublishForm, form ID is: ${JSON.stringify(data)}'); } }); } catch (error) { @@ -557,16 +557,16 @@ try { formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { var want = { - abilityName: "FormAbility", + abilityName: 'FormAbility', parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" + 'ohos.extra.param.key.form_dimension': 2, + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.module_name': 'entry' } }; try { formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + console.log('formProvider requestPublishForm success, form ID is : ${JSON.stringify(data)}'); }).catch((error) => { console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index b9ec53b660112df52456caa020b5e9105316bbbd..e48f7440149566926e3700c1885c61596e36eb9e 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -198,18 +198,23 @@ Creates an app account implicitly based on the specified account owner. This API **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { console.log("resultCode: " + code); console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err) => { + let wantInfo = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log("startAbility successfully"); + }).catch((err) => { console.log("startAbility err: " + JSON.stringify(err)); - }); + }) } try { @@ -252,18 +257,23 @@ Creates an app account implicitly based on the specified account owner and optio **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { console.log("resultCode: " + code); console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err) => { + let wantInfo = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log("startAbility successfully"); + }).catch((err) => { console.log("startAbility err: " + JSON.stringify(err)); - }); + }) } let options = { @@ -1346,7 +1356,7 @@ Authenticates an app account. This API uses an asynchronous callback to return t **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; + function onResultCallback(code, authResult) { console.log("resultCode: " + code); @@ -1354,10 +1364,17 @@ Authenticates an app account. This API uses an asynchronous callback to return t } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err) => { - console.log("startAbility err: " + JSON.stringify(err)); - }); + let wantInfo = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log("startAbility successfully"); + }).catch((err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }) } try { @@ -1402,7 +1419,7 @@ Authenticates an app account with customized options. This API uses an asynchron **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; + function onResultCallback(code, authResult) { console.log("resultCode: " + code); @@ -1410,10 +1427,17 @@ Authenticates an app account with customized options. This API uses an asynchron } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err) => { - console.log("startAbility err: " + JSON.stringify(err)); - }); + let wantInfo = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log("startAbility successfully"); + }).catch((err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }) } let options = { @@ -2706,7 +2730,7 @@ Adds an app account. This API uses an asynchronous callback to return the result | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | -------------------- | -| name | string | Yes | Name of the target app account. | +| name | string | Yes | Name of the app account to add. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Example** @@ -2724,6 +2748,7 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>) Adds an app account name and additional information. This API uses an asynchronous callback to return the result. > **NOTE** +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-1). **System capability**: SystemCapability.Account.AppAccount @@ -2750,8 +2775,7 @@ addAccount(name: string, extraInfo?: string): Promise<void> Adds an app account name and additional information. This API uses an asynchronous callback to return the result. This API uses a promise to return the result. -> **NOTE** -> +> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createAccount](#createaccount9-2). **System capability**: SystemCapability.Account.AppAccount @@ -2803,7 +2827,7 @@ Adds an app account implicitly based on the specified owner. This API uses an as **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; + function onResultCallback(code, result) { console.log("resultCode: " + code); @@ -2811,10 +2835,17 @@ Adds an app account implicitly based on the specified owner. This API uses an as } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ + let wantInfo = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log("startAbility successfully"); + }).catch((err) => { console.log("startAbility err: " + JSON.stringify(err)); - }); + }) } appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, { @@ -2839,7 +2870,7 @@ Deletes an app account. This API uses an asynchronous callback to return the res | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------- | -| name | string | Yes | Name of the target app account. | +| name | string | Yes | Name of the app account to delete. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Example** @@ -2866,7 +2897,7 @@ Deletes an app account. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------- | -| name | string | Yes | Name of the target app account.| +| name | string | Yes | Name of the app account to delete.| **Return value** @@ -3751,18 +3782,23 @@ Authenticates an app account with customized options. This API uses an asynchron **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { console.log("resultCode: " + code); console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let wantInfo = { + deviceId: '', + bundleName: 'com.example.accountjsdemo', + action: 'ohos.want.action.viewData', + entities: ['entity.system.default'], + } + this.context.startAbility(wantInfo).then(() => { + console.log("startAbility successfully"); + }).catch((err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }) } appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, { @@ -4521,10 +4557,13 @@ Enumerates the constants. | KEY_REQUIRED_LABELS9+ | "requiredLabels" | Required labels. | | KEY_BOOLEAN_RESULT9+ | "booleanResult" | Return value of the Boolean type. | -## ResultCode8+ +## ResultCode(deprecated) Enumerates the result codes. +> **NOTE** +> This enum is supported since API version 8 and deprecated since API version 9. From API version 9, error codes are used. For details about the error codes, see [App Account Error Codes](../errorcodes/errorcode-app-account.md). + **System capability**: SystemCapability.Account.AppAccount | Name | Value | Description | @@ -4760,7 +4799,7 @@ Creates an app account implicitly based on the specified account owner. This API | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | -| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | +| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating an account. | | callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| ### addAccountImplicitly(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-appControl.md b/en/application-dev/reference/apis/js-apis-appControl.md index 06b334d58cad8e7dd26a45c0344cfa48e1fdf0d6..597b3d8e3b9d15b6d18f4f8e57c0ac71563d3236 100644 --- a/en/application-dev/reference/apis/js-apis-appControl.md +++ b/en/application-dev/reference/apis/js-apis-appControl.md @@ -45,7 +45,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified app ID is not found. | +| 17700005 | The specified app ID is empty string. | **Example** @@ -91,7 +91,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified app ID is not found. | +| 17700005 | The specified app ID is empty string. | **Example** @@ -142,7 +142,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified app ID is not found. | +| 17700005 | The specified app ID is empty string. | **Example** @@ -186,7 +186,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified app ID is not found. | +| 17700005 | The specified app ID is empty string. | **Example** @@ -236,7 +236,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified app ID is not found. | +| 17700005 | The specified app ID is empty string. | **Example** @@ -280,7 +280,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified app ID is not found. | +| 17700005 | The specified app ID is empty string. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md deleted file mode 100644 index 6e96d0194a712340cd63a5510a190ea971d04e01..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ /dev/null @@ -1,756 +0,0 @@ -# @ohos.application.Ability (Ability) - -The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. - -This module provides the following common ability-related functions: - -- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). -- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. - -> **NOTE** -> -> The APIs of this module are deprecated since API version 9. You are advised to use [@ohos.app.ability.UIAbility (UIAbility)](js-apis-app-ability-uiAbility.md) instead. -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import UIAbility from '@ohos.application.Ability'; -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of an ability.| -| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the ability.| -| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.| -| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| - -## Ability.onCreate - -onCreate(want: Want, param: AbilityConstant.LaunchParam): void; - -Called to initialize the service logic when an ability is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, including the ability name and bundle name.| - | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onCreate(want, param) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## Ability.onWindowStageCreate - -onWindowStageCreate(windowStage: window.WindowStage): void - -Called when a **WindowStage** is created for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - } - } - ``` - - -## Ability.onWindowStageDestroy - -onWindowStageDestroy(): void - -Called when the **WindowStage** is destroyed for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onWindowStageDestroy() { - console.log('onWindowStageDestroy'); - } - } - ``` - - -## Ability.onWindowStageRestore - -onWindowStageRestore(windowStage: window.WindowStage): void - -Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onWindowStageRestore(windowStage) { - console.log('onWindowStageRestore'); - } - } - ``` - - -## Ability.onDestroy - -onDestroy(): void; - -Called when this ability is destroyed to clear resources. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## Ability.onForeground - -onForeground(): void; - -Called when this ability is switched from the background to the foreground. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onForeground() { - console.log('onForeground'); - } - } - ``` - - -## Ability.onBackground - -onBackground(): void; - -Called when this ability is switched from the foreground to the background. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onBackground() { - console.log('onBackground'); - } - } - ``` - - -## Ability.onContinue - -onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; - -Called to save data during the ability migration preparation process. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | wantParam | {[key: string]: any} | Yes| **want** parameter.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnContinueResult | Continuation result.| - -**Example** - - ```ts - import AbilityConstant from "@ohos.app.ability.AbilityConstant"; - - export default class EntryAbility extends UIAbility { - onContinue(wantParams) { - console.log('onContinue'); - wantParams["myData"] = "my1234567"; - return AbilityConstant.OnContinueResult.AGREE; - } - } - ``` - - -## Ability.onNewWant - -onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; - -Called when a new Want is passed in and this UIAbility is started again. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information, such as the ability name and bundle name.| -| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onNewWant(want, launchParams) { - console.log('onNewWant, want:' + want.abilityName); - console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); - } - } - ``` - -## Ability.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the global configuration is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, language:' + config.language); - } - } - ``` - -## Ability.dump - -dump(params: Array\): Array\; - -Dumps client information. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - dump(params) { - console.log('dump, params:' + JSON.stringify(params)); - return ["params"] - } - } - ``` - -## Ability.onMemoryLevel - -onMemoryLevel(level: AbilityConstant.MemoryLevel): void; - -Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| - -**Example** - - ```ts - export default class EntryAbility extends UIAbility { - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` - -## Ability.onSaveState - -onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; - -Called when the framework automatically saves the ability state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reason | [AbilityConstant.StateType](js-apis-application-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the ability state.| - | wantParam | {[key: string]: any} | Yes| **want** parameter.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnSaveResult | Whether the ability state is saved.| - -**Example** - - ```ts -import AbilityConstant from '@ohos.app.ability.AbilityConstant'; - -export default class EntryAbility extends UIAbility { - onSaveState(reason, wantParam) { - console.log('onSaveState'); - wantParam["myData"] = "my1234567"; - return AbilityConstant.OnSaveResult.RECOVERY_AGREE; - } -} - ``` - -## Caller - -Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). - -## Caller.call - -call(method: string, data: rpc.Sequenceable): Promise<void>; - -Sends sequenceable data to the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return a response.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16200001 | Caller released. The caller has been released. | -| 16200002 | Callee invalid. The callee does not exist. | -| 16000050 | Internal Error. | - -**Example** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - class MyMessageAble{ // Custom sequenceable data structure. - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities - var caller; - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "EntryAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble("msg", "world"); // See the definition of Sequenceable. - caller.call(method, msg) - .then(() => { - console.log('Caller call() called'); - }) - .catch((callErr) => { - console.log('Caller.call catch error, error.code: ' + JSON.stringify(callErr.code) + - ' error.message: ' + JSON.stringify(callErr.message)); - }); - }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); - }); - } - } - ``` - - -## Caller.callWithResult - -callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; - -Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| - | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16200001 | Caller released. The caller has been released. | -| 16200002 | Callee invalid. The callee does not exist. | -| 16000050 | Internal Error. | - -**Example** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - class MyMessageAble{ - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; - var caller; - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "EntryAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); - caller.callWithResult(method, msg) - .then((data) => { - console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); - data.readSequenceable(retmsg); - }) - .catch((callErr) => { - console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) + - ' error.message: ' + JSON.stringify(callErr.message)); - }); - }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); - }); - } - } - ``` - - -## Caller.release - -release(): void; - -Releases the caller interface of the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| 16200001 | Caller released. The caller has been released. | -| 16200002 | Callee invalid. The callee does not exist. | -| 16000050 | Internal Error. | - -**Example** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - var caller; - - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "EntryAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.release(); - } catch (releaseErr) { - console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + - ' error.message: ' + JSON.stringify(releaseErr.message)); - } - }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); - }); - } - } - ``` - -## Caller.onRelease - - onRelease(callback: OnReleaseCallBack): void; - -Registers a callback that is invoked when the stub on the target ability is disconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| - -**Example** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - var caller; - - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "EntryAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.onRelease((str) => { - console.log(' Caller OnRelease CallBack is called ' + str); - }); - } catch (error) { - console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - } - }).catch((err) => { - console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + - ' error.message: ' + JSON.stringify(err.message)); - }); - } - } - ``` - - -## Callee - -Implements callbacks for caller notification registration and deregistration. - -## Callee.on - -on(method: string, callback: CalleeCallBack): void; - -Registers a caller notification callback, which is invoked when the target ability registers a function. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities.| - | callback | CalleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| 16200004 | Method registered. The method has registered. | -| 16000050 | Internal Error. | - -**Example** - - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - class MyMessageAble{ - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; - function funcCallBack(pdata) { - console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble("test", ""); - pdata.readSequenceable(msg); - return new MyMessageAble("test1", "Callee test"); - } - export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - try { - this.callee.on(method, funcCallBack); - } catch (error) { - console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - } - } - } - ``` - -## Callee.off - -off(method: string): void; - -Deregisters a caller notification callback, which is invoked when the target ability registers a function. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Registered notification message string.| - -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| 16200005 | Method not registered. The method has not registered. | -| 16000050 | Internal Error. | - - -**Example** - ```ts - import UIAbility from '@ohos.app.ability.UIAbility'; - - var method = 'call_Function'; - - export default class EntryAbility extends UIAbility { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - try { - this.callee.off(method); - } catch (error) { - console.log('Callee.off catch error, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - } - } - } - ``` - -## OnReleaseCallBack - -(msg: string): void; - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.| - -## CalleeCallBack - -(indata: rpc.MessageParcel): rpc.Sequenceable; - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md deleted file mode 100644 index 70d679e5f44e1089e91ff7377b687ded761e29e6..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ /dev/null @@ -1,115 +0,0 @@ -# @ohos.application.AbilityConstant (AbilityConstant) - -The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. - -> **NOTE** -> -> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import AbilityConstant from '@ohos.application.AbilityConstant'; -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason.| -| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit.| - -## AbilityConstant.LaunchReason - -Enumerates the initial ability launch reasons. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | Unknown reason.| -| START_ABILITY | 1 | Ability startup.| -| CALL | 2 | Call.| -| CONTINUATION | 3 | Ability continuation.| -| APP_RECOVERY | 4 | Application recovery.| - - -## AbilityConstant.LastExitReason - -Enumerates the reasons for the last exit. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | Unknown reason.| -| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| -| NORMAL | 2 | Normal status.| - - -## AbilityConstant.OnContinueResult - -Enumerates the ability continuation results. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| AGREE | 0 | Continuation agreed.| -| REJECT | 1 | Continuation denied.| -| MISMATCH | 2 | Mismatch.| - -## AbilityConstant.WindowMode - -Enumerates the window modes in which an ability can be displayed at startup. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value| Description | -| --- | --- | --- | -| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. | -| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. | -| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. | -| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | -| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| - -## AbilityConstant.MemoryLevel - -Enumerates the memory levels. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value| Description | -| --- | --- | --- | -| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. | -| MEMORY_LEVEL_LOW | 1 | Low memory usage. | -| MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | - -## AbilityConstant.OnSaveResult - -Enumerates the result types for the operation of saving application data. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| ALL_AGREE | 0 | Agreed to save the status.| -| CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| -| CONTINUATION_MISMATCH | 2 | Continuation mismatch.| -| RECOVERY_AGREE | 3 | Agreed to restore the saved status.| -| RECOVERY_REJECT | 4 | Rejected to restore the saved state.| -| ALL_REJECT | 5 | Rejected to save the status.| - -## AbilityConstant.StateType - -Enumerates the scenarios for saving application data. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| CONTINUATION | 0 | Saving the status in continuation.| -| APP_RECOVERY | 1 | Saving the status in application recovery.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index 4dd701b54e2924b5ec1b928e4c0f5ad8a8d3f05f..28948de20eabb33cca06ee75b728a75bd639208b 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,6 +1,6 @@ # @ohos.application.abilityDelegatorRegistry (AbilityDelegatorRegistry) -The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. +The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. The APIs can be used only in the test framework. > **NOTE** > @@ -43,7 +43,7 @@ Obtains the **AbilityDelegator** object of the application. **Example** ```ts -var abilityDelegator; +let abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` @@ -65,8 +65,8 @@ Obtains the **AbilityDelegatorArgs** object of the application. **Example** ```ts -var args = AbilityDelegatorRegistry.getArguments(); -console.info("getArguments bundleName:" + args.bundleName); -console.info("getArguments testCaseNames:" + args.testCaseNames); -console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +let args = AbilityDelegatorRegistry.getArguments(); +console.info('getArguments bundleName: ${args.bundleName}'); +console.info('getArguments testCaseNames: ${args.testCaseNames}'); +console.info('getArguments testRunnerClassName: ${args.testRunnerClassName}'); ``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md deleted file mode 100644 index 5e29491014719ab9e5cf09dd976ed71f2b449c6e..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ /dev/null @@ -1,213 +0,0 @@ -# @ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback) - -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. These callbacks can be used as an input parameter of [registerAbilityLifecycleCallback](js-apis-inner-application-applicationContext.md#applicationcontextregisterabilitylifecyclecallback). - -> **NOTE** -> -> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - - -## Modules to Import - -```ts -import AbilityLifecycleCallback from "@ohos.application.AbilityLifecycleCallback"; -``` - - -## AbilityLifecycleCallback.onAbilityCreate - -onAbilityCreate(ability: Ability): void; - -Called when an ability is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - - -## AbilityLifecycleCallback.onWindowStageCreate - -onWindowStageCreate(ability: Ability, windowStage: window.WindowStage): void; - -Called when the window stage of an ability is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| - - -## AbilityLifecycleCallback.onWindowStageActive - -onWindowStageActive(ability: Ability, windowStage: window.WindowStage): void; - -Called when the window stage of an ability gains focus. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| - - -## AbilityLifecycleCallback.onWindowStageInactive - -onWindowStageInactive(ability: Ability, windowStage: window.WindowStage): void; - -Called when the window stage of an ability loses focus. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| - - -## AbilityLifecycleCallback.onWindowStageDestroy - -onWindowStageDestroy(ability: Ability, windowStage: window.WindowStage): void; - -Called when the window stage of an ability is destroyed. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| -| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| - - -## AbilityLifecycleCallback.onAbilityDestroy - -onAbilityDestroy(ability: Ability): void; - -Called when an ability is destroyed. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - - -## AbilityLifecycleCallback.onAbilityForeground - -onAbilityForeground(ability: Ability): void; - -Called when an ability is switched from the background to the foreground. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - - -## AbilityLifecycleCallback.onAbilityBackground - -onAbilityBackground(ability: Ability): void; - -Called when an ability is switched from the foreground to the background. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - - -## AbilityLifecycleCallback.onAbilityContinue - -onAbilityContinue(ability: Ability): void; - -Called when an ability is continued on another device. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - -**Example** - -```ts -import AbilityStage from "@ohos.app.ability.AbilityStage"; - -var lifecycleId; - -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability) { - console.log("onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onWindowStageCreate(ability, windowStage) { - console.log("onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageActive(ability, windowStage) { - console.log("onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("onWindowStageActive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageInactive(ability, windowStage) { - console.log("onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageDestroy(ability, windowStage) { - console.log("onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); - }, - onAbilityDestroy(ability) { - console.log("onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability) { - console.log("onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability) { - console.log("onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability) { - console.log("onAbilityContinue ability:" + JSON.stringify(ability)); - } - } - // 1. Obtain applicationContext through the context attribute. - let applicationContext = this.context.getApplicationContext(); - // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); - } - - onDestroy() { - let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - } -} -``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index b734efe10a8dcd445e7a51db1509a0c1d4bedc5f..5edd8883d8f9d294f6f1408821efa95289108123 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -49,13 +49,13 @@ Updates the configuration. This API uses an asynchronous callback to return the **Example** ```ts -var config = { +let config = { language: 'chinese' -} +}; abilityManager.updateConfiguration(config, () => { console.log('------------ updateConfiguration -----------'); -}) +}); ``` ## updateConfiguration @@ -83,15 +83,15 @@ Updates the configuration. This API uses a promise to return the result. **Example** ```ts -var config = { +let config = { language: 'chinese' -} +}; abilityManager.updateConfiguration(config).then(() => { console.log('updateConfiguration success'); }).catch((err) => { console.log('updateConfiguration fail'); -}) +}); ``` ## getAbilityRunningInfos @@ -114,7 +114,7 @@ Obtains the ability running information. This API uses an asynchronous callback ```ts abilityManager.getAbilityRunningInfos((err,data) => { - console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); + console.log('getAbilityRunningInfos err: ${err}, data: ${JSON.stringify(data)}'); }); ``` @@ -138,115 +138,8 @@ Obtains the ability running information. This API uses a promise to return the r ```ts abilityManager.getAbilityRunningInfos().then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) + console.log('getAbilityRunningInfos data: ${JSON.stringify(data)}'); }).catch((err) => { - console.log("getAbilityRunningInfos err: " + err) + console.log('getAbilityRunningInfos err: ${JSON.stringify(err)}'); }); ``` - -## getExtensionRunningInfos9+ - -getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void - -Obtains the extension running information. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | Yes| Maximum number of messages that can be obtained.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | - -**Example** - -```ts -var upperLimit = 0; - -abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); -}); -``` - -## getExtensionRunningInfos9+ - -getExtensionRunningInfos(upperLimit: number): Promise\> - -Obtains the extension running information. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | Yes| Maximum number of messages that can be obtained.| - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| - -**Example** - -```ts -var upperLimit = 0; - -abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); -}).catch((err) => { - console.log("getAbilityRunningInfos err: " + err); -}) -``` - -## getTopAbility9+ - -getTopAbility(callback: AsyncCallback\): void; - -Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the result. | - -**Example** - -```ts -abilityManager.getTopAbility((err,data) => { - console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); -}); -``` - -## getTopAbility9+ - -getTopAbility(): Promise\; - -Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------- | -| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the result.| - -**Example** - -```ts -abilityManager.getTopAbility().then((data) => { - console.log("getTopAbility data: " + JSON.stringify(data)); -}).catch((err) => { - console.log("getTopAbility err: " + err); -}) -``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityStage.md b/en/application-dev/reference/apis/js-apis-application-abilityStage.md deleted file mode 100644 index 1421dcd723028b9a7f052e76e2534f1ea7c4017a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilityStage.md +++ /dev/null @@ -1,127 +0,0 @@ -# @ohos.application.AbilityStage (AbilityStage) - -**AbilityStage** is a runtime class for HAP files. - -The **AbilityStage** module notifies you of when you can perform HAP initialization such as resource pre-loading and thread creation during the HAP loading. - -> **NOTE** -> -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import AbilityStage from '@ohos.application.AbilityStage'; -``` - -## AbilityStage.onCreate - -onCreate(): void - -Called when the application is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Example** - - ```ts - class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage.onCreate is called") - } - } - ``` - - -## AbilityStage.onAcceptWant - -onAcceptWant(want: Want): string; - -Called when a UIAbility is started. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target UIAbility, such as the ability name and bundle name.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Returns a UIAbility ID. If this UIAbility has been started, no new instance is created and the UIAbility is placed at the top of the stack. Otherwise, a new instance is created and started.| - -**Example** - - ```ts - class MyAbilityStage extends AbilityStage { - onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; - } - } - ``` - - -## AbilityStage.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the global configuration is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| - -**Example** - - ```ts - class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, language:' + config.language); - } - } - ``` - -## AbilityStage.onMemoryLevel - -onMemoryLevel(level: AbilityConstant.MemoryLevel): void; - -Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| - -**Example** - - ```ts - class MyAbilityStage extends AbilityStage { - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` - -## AbilityStage.context - -context: AbilityStageContext; - -Defines the **Context** object of **AbilityStage**. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Description | -| ------- | ------------------------------------------------------------ | -------------------------- | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | **Context** object of AbilityStage.| diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md index a31f9c88969155dc1f0fc7717fd2aa6267ac3180..da884686b0782d74836421a915521c8882639d74 100644 --- a/en/application-dev/reference/apis/js-apis-application-appManager.md +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -30,9 +30,9 @@ Checks whether this application is undergoing a stability test. This API uses an ```ts appManager.isRunningInStabilityTest((err, flag) => { - console.log('error:' + JSON.stringfy(err)); - console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); - }) + console.log('error: ${JSON.stringify(err)}'); + console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); + }); ``` @@ -54,9 +54,9 @@ Checks whether this application is undergoing a stability test. This API uses a ```ts appManager.isRunningInStabilityTest().then((flag) => { - console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); + console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); }).catch((error) => { - console.log('error:' + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -79,9 +79,9 @@ Checks whether this application is running on a RAM constrained device. This API ```ts appManager.isRamConstrainedDevice().then((data) => { - console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); + console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log('error:' + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -103,9 +103,9 @@ Checks whether this application is running on a RAM constrained device. This API ```ts appManager.isRamConstrainedDevice((err, data) => { - console.log('error:' + JSON.stringify(err)); - console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); - }) + console.log('error: ${JSON.stringify(err)}'); + console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); + }); ``` ## appManager.getAppMemorySize @@ -120,15 +120,15 @@ Obtains the memory size of this application. This API uses a promise to return t | Type| Description| | -------- | -------- | - | Promise<number> | Size of the application memory.| + | Promise<number> | Promise used to return the memory size, in MB.| **Example** ```ts appManager.getAppMemorySize().then((data) => { - console.log('The size of app memory is:' + JSON.stringify(data)); + console.log('The size of app memory is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log('error:' + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -144,15 +144,15 @@ Obtains the memory size of this application. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | Yes| Size of the application memory.| + | callback | AsyncCallback<number> | Yes| Callback used to return the memory size, in MB.| **Example** ```ts appManager.getAppMemorySize((err, data) => { - console.log('error:' + JSON.stringify(err)); - console.log('The size of app memory is:' + JSON.stringify(data)); - }) + console.log('error: ${JSON.stringify(err)}'); + console.log('The size of app memory is: ${JSON.stringify(data)}'); + }); ``` ## appManager.getProcessRunningInfos(deprecated) @@ -160,7 +160,7 @@ getProcessRunningInfos(): Promise\>; Obtains information about the running processes. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. +> This API is deprecated since API version 9. You are advised to use [appManager.getRunningProcessInformation9+](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation) instead. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -176,9 +176,9 @@ Obtains information about the running processes. This API uses a promise to retu ```ts appManager.getProcessRunningInfos().then((data) => { - console.log('The process running infos is:' + JSON.stringify(data)); + console.log('The process running infos is: ${JSON.stringify(data)}'); }).catch((error) => { - console.log('error:' + JSON.stringify(error)); + console.log('error: ${JSON.stringify(error)}'); }); ``` @@ -188,7 +188,7 @@ getProcessRunningInfos(callback: AsyncCallback\>): vo Obtains information about the running processes. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. +> This API is deprecated since API version 9. You are advised to use [appManager.getRunningProcessInformation9+](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9) instead. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -204,62 +204,11 @@ Obtains information about the running processes. This API uses an asynchronous c ```ts appManager.getProcessRunningInfos((err, data) => { - console.log('error:' + JSON.stringify(err)); - console.log('The process running infos is:' + JSON.stringify(data)); - }) - ``` - -## appManager.getProcessRunningInformation9+ - -getProcessRunningInformation(): Promise\>; - -Obtains information about the running processes. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Obtains information about the running processes. This API uses a promise to return the result.| - -**Example** - - ```ts - appManager.getProcessRunningInformation().then((data) => { - console.log('The process running info is:' + JSON.stringify(data)); - }).catch((error) => { - console.log('error:' + JSON.stringify(error)); + console.log('error: ${JSON.stringify(err)}'); + console.log('The process running infos is: ${JSON.stringify(data)}'); }); ``` -## appManager.getProcessRunningInformation9+ - -getProcessRunningInformation(callback: AsyncCallback\>): void; - -Obtains information about the running processes. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| - -**Example** - - ```ts - appManager.getProcessRunningInformation((err, data) => { - console.log('error:' + JSON.stringify(err)); - console.log('The process running info is:' + JSON.stringify(data)); - }) - ``` - ## appManager.registerApplicationStateObserver8+ registerApplicationStateObserver(observer: ApplicationStateObserver): number; @@ -281,7 +230,7 @@ Registers an observer to listen for the state changes of all applications. **Example** ```ts - var applicationStateObserver = { + let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { console.log('------------ onForegroundApplicationChanged -----------', appStateData); }, @@ -297,7 +246,7 @@ Registers an observer to listen for the state changes of all applications. onProcessStateChanged(processData) { console.log('------------ onProcessStateChanged -----------', processData); } - } + }; const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); console.log('-------- observerCode: ---------', observerCode); ``` @@ -324,7 +273,7 @@ Registers an observer to listen for the state changes of a specified application **Example** ```ts - var applicationStateObserver = { + let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { console.log('------------ onForegroundApplicationChanged -----------', appStateData); }, @@ -340,8 +289,8 @@ Registers an observer to listen for the state changes of a specified application onProcessStateChanged(processData) { console.log('------------ onProcessStateChanged -----------', processData); } - } - var bundleNameList = ['bundleName1', 'bundleName2']; + }; + let bundleNameList = ['bundleName1', 'bundleName2']; const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList); console.log('-------- observerCode: ---------', observerCode); ``` @@ -367,7 +316,7 @@ Deregisters the application state observer. This API uses an asynchronous callba **Example** ```ts - var observerId = 100; + let observerId = 100; function unregisterApplicationStateObserverCallback(err) { if (err) { @@ -404,7 +353,7 @@ Deregisters the application state observer. This API uses a promise to return th **Example** ```ts - var observerId = 100; + let observerId = 100; appManager.unregisterApplicationStateObserver(observerId) .then((data) => { @@ -412,7 +361,7 @@ Deregisters the application state observer. This API uses a promise to return th }) .catch((err) => { console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) + }); ``` ## appManager.getForegroundApplications8+ @@ -440,7 +389,7 @@ Obtains information about the applications that are running in the foreground. T if (err) { console.log('--------- getForegroundApplicationsCallback fail ---------', err); } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) + console.log('--------- getForegroundApplicationsCallback success ---------', data); } } appManager.getForegroundApplications(getForegroundApplicationsCallback); @@ -473,7 +422,7 @@ Obtains information about the applications that are running in the foreground. T }) .catch((err) => { console.log('--------- getForegroundApplications fail -------', err); - }) + }); ``` ## appManager.killProcessWithAccount8+ @@ -498,15 +447,15 @@ Kills a process by bundle name and account ID. This API uses a promise to return **Example** ```ts -var bundleName = 'bundleName'; -var accountId = 0; +let bundleName = 'bundleName'; +let accountId = 0; appManager.killProcessWithAccount(bundleName, accountId) .then((data) => { console.log('------------ killProcessWithAccount success ------------', data); }) .catch((err) => { console.log('------------ killProcessWithAccount fail ------------', err); - }) + }); ``` @@ -533,8 +482,8 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **Example** ```ts -var bundleName = 'bundleName'; -var accountId = 0; +let bundleName = 'bundleName'; +let accountId = 0; function killProcessWithAccountCallback(err, data) { if (err) { console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); @@ -567,7 +516,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return **Example** ```ts - var bundleName = 'bundleName'; + let bundleName = 'bundleName'; function killProcessesByBundleNameCallback(err, data) { if (err) { console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); @@ -605,14 +554,14 @@ Kills a process by bundle name. This API uses a promise to return the result. **Example** ```ts - var bundleName = 'com.example.myapplication'; + let bundleName = 'com.example.myapplication'; appManager.killProcessesByBundleName(bundleName) .then((data) => { console.log('------------ killProcessesByBundleName success ------------', data); }) .catch((err) => { console.log('------------ killProcessesByBundleName fail ------------', err); - }) + }); ``` ## appManager.clearUpApplicationData8+ @@ -637,7 +586,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t **Example** ```ts - var bundleName = 'bundleName'; + let bundleName = 'bundleName'; function clearUpApplicationDataCallback(err, data) { if (err) { console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); @@ -675,40 +624,12 @@ Clears application data by bundle name. This API uses a promise to return the re **Example** ```ts - var bundleName = 'bundleName'; + let bundleName = 'bundleName'; appManager.clearUpApplicationData(bundleName) .then((data) => { console.log('------------ clearUpApplicationData success ------------', data); }) .catch((err) => { console.log('------------ clearUpApplicationData fail ------------', err); - }) + }); ``` - -## ApplicationState9+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | State indicating that the application is being created. | -| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | -| STATE_ACTIVE | 3 | State indicating that the application is active. | -| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | -| STATE_DESTROY | 5 | State indicating that the application is destroyed. | - -## ProcessState9+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | State indicating that the process is being created. | -| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | -| STATE_ACTIVE | 3 | State indicating that the process is active. | -| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | -| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md index 82d964e100a1bda94ad0f6f470ae29895d2acde5..ea31ed6a6b019ef446e94c9ee07407ff1f9d3ae1 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -1,33 +1,22 @@ # @ohos.application.Configuration (Configuration) -The **Configuration** module defines environment change information. +The **Configuration** module defines environment change information. **Configuration** is an interface definition and is used only for field declaration. > **NOTE** > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead. -## Modules to Import - -```ts -import Configuration from '@ohos.application.Configuration' -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | language8+ | string | Yes| Yes| Language of the application, for example, **zh**.| | colorMode8+ | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction9+ | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity9+ | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| -| displayId9+ | number | Yes| No| ID of the display where the application is located.| -| hasPointerDevice9+ | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| For details about the fields, see the **ohos.application.Configuration.d.ts** file. **Example** ```ts -import hilog from '@ohos.hilog'; import UIAbility from '@ohos.app.ability.UIAbility'; import Window from '@ohos.window'; @@ -41,13 +30,9 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: Window.WindowStage) { let envCallback = { onConfigurationUpdated(config) { - console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`); let language = config.language; let colorMode = config.colorMode; - let direction = config.direction; - let screenDensity = config.screenDensity; - let displayId = config.displayId; - let hasPointerDevice = config.hasPointerDevice; } }; @@ -56,12 +41,10 @@ export default class EntryAbility extends UIAbility { windowStage.loadContent('pages/index', (err, data) => { if (err.code) { - hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR); - hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + console.error('failed to load the content, error: + ${JSON.stringify(err)}'); return; } - hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); - hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); + console.info('Succeeded in loading the content, data: + ${JSON.stringify(data)}'); }); } } diff --git a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md index dabe32b2f9d166dbce68b94c204b82f78b0090de..b1017a036bdb9f02a656c1890310cd3e029337f5 100644 --- a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -23,33 +23,3 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| | COLOR_MODE_DARK | 0 | Dark mode.| | COLOR_MODE_LIGHT | 1 | Light mode.| - - -## ConfigurationConstant.Direction9+ - -You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Value| Description| -| -------- | -------- | -------- | -| DIRECTION_NOT_SET | -1 | Unspecified direction.| -| DIRECTION_VERTICAL | 0 | Vertical direction.| -| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| - - -## ConfigurationConstant.ScreenDensity9+ - -You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Value| Description| -| -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md deleted file mode 100644 index d42e522c14266de6ca53fff7370c68de14c34d36..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ /dev/null @@ -1,41 +0,0 @@ -# @ohos.application.context (Context) - -The **Context** module provides all level-2 module APIs for developers to export. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import context from '@ohos.application.context' -``` - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| AbilityContext | Read Only | [AbilityContext](js-apis-ability-context.md) | No | Level-2 module **AbilityContext**. | -| AbilityStageContext | Read Only | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.| -| ApplicationContext | Read Only | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.| -| BaseContext | Read Only | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.| -| Context | Read Only | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.| -| ExtensionContext | Read Only | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.| -| FormExtensionContext | Read Only | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.| -| EventHub | Read Only | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.| -| PermissionRequestResult | Read Only | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.| - -**Example** -```ts -let abilityContext: context.AbilityContext; -let abilityStageContext: context.AbilityStageContext; -let applicationContext: context.ApplicationContext; -let baseContext: context.BaseContext; -let context: context.Context; -let extensionContext: context.ExtensionContext; -let formExtensionContext: context.FormExtensionContext; -let eventHub: context.EventHub; -let permissionRequestResult: context.PermissionRequestResult; -``` 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 a98dc0e7c402469de49f9b1f4397fc4eecad000d..ee7ba37cdd08795b0ea33e09dc687b7ccd4712bc 100644 --- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -14,7 +14,7 @@ The **DataShareExtensionAbility** module provides data share services based on t ## Modules to Import ```ts -import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility' +import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility'; ``` ## URI Naming Rule @@ -65,11 +65,11 @@ Called by the server to initialize service logic when the DataShare client conne ```ts import rdb from '@ohos.data.relationalStore'; -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " +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)"; + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -78,10 +78,10 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 }, function (err, data) { - console.log('getRdbStore done, data : ' + data); + console.log('getRdbStore done, data : ${data}'); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { - console.log('executeSql done, error message : ' + err); + console.log('executeSql done, error message : ${err}'); }); if (callback) { callback(); @@ -112,22 +112,22 @@ Inserts data into the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " +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)"; + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { insert(uri, valueBucket, callback) { - if (valueBucket == null) { + if (valueBucket === null) { console.info('invalid valueBuckets'); return; } rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) { - console.info('callback ret:' + ret); - if (callback != undefined) { + console.info('callback ret: ${ret}'); + if (callback !== undefined) { callback(err, ret); } }); @@ -157,20 +157,20 @@ Updates data in the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " +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)"; + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { update(uri, predicates, valueBucket, callback) { - if (predicates == null || predicates == undefined) { + if (predicates === null || predicates === undefined) { return; } rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) { - if (callback != undefined) { + if (callback !== undefined) { callback(err, ret); } }); @@ -199,20 +199,20 @@ Deletes data from the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " +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)"; + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { delete(uri, predicates, callback) { - if (predicates == null || predicates == undefined) { + if (predicates === null || predicates === undefined) { return; } rdbStore.delete(TBL_NAME, predicates, function (err, ret) { - if (callback != undefined) { + if (callback !== undefined) { callback(err, ret); } }); @@ -242,23 +242,23 @@ Queries data from the database. This API can be overridden as required. ```ts import rdb from '@ohos.data.relationalStore'; -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " +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)"; + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { query(uri, predicates, columns, callback) { - if (predicates == null || predicates == undefined) { + if (predicates === null || predicates === undefined) { return; } rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { - if (resultSet != undefined) { - console.info('resultSet.rowCount: ' + resultSet.rowCount); + if (resultSet !== undefined) { + console.info('resultSet.rowCount: ${resultSet.rowCount}'); } - if (callback != undefined) { + if (callback !== undefined) { callback(err, resultSet); } }); @@ -287,23 +287,23 @@ Batch inserts data into the database. This API is called by the server and can b ```ts import rdb from '@ohos.data.relationalStore'; -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " +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)"; + + ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)'; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { batchInsert(uri, valueBuckets, callback) { - if (valueBuckets == null || valueBuckets.length == undefined) { + if (valueBuckets === null || valueBuckets.length === undefined) { console.info('invalid valueBuckets'); return; } - let resultNum = valueBuckets.length + let resultNum = valueBuckets.length; valueBuckets.forEach(vb => { rdbStore.insert(TBL_NAME, vb, function (err, ret) { - if (callback != undefined) { + if (callback !== undefined) { callback(err, resultNum); } }); @@ -332,8 +332,8 @@ 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; + let err = {'code':0}; + let ret = 'normalize+${uri}'; callback(err, ret); } }; @@ -359,8 +359,8 @@ 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; + let err = {'code':0}; + let ret = 'denormalize+${uri}'; callback(err, ret); } }; diff --git a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md index d4c25269235da3b95e4f230c084d92c1df047269..257c83a9f99821e77191a69f89ef9a25e457b982 100644 --- a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md @@ -11,7 +11,7 @@ The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdat ## Modules to Import ```ts -import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; +import EnvironmentCallback from '@ohos.application.EnvironmentCallback'; ``` @@ -41,37 +41,37 @@ Called when the system memory level changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| + | level | [MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| **Example** ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate'); globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ - console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + console.log('onConfigurationUpdated config: ${JSON.stringify(config)}'); }, onMemoryLevel(level){ - console.log("onMemoryLevel level:" + level); + console.log('onMemoryLevel level: ${level}'); } - } + }; // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; // 2. Register a listener for the environment changes through the applicationContext object. callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); - console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + console.log('registerEnvironmentCallback number: ${JSON.stringify(callbackId)}'); } onDestroy() { let applicationContext = globalThis.applicationContext; applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + console.log('unregisterEnvironmentCallback success, err: ${JSON.stringify(error)}'); }); } } diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md deleted file mode 100644 index 2fbd840782cefe200f53d6df090bff9220b52c49..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-errorManager.md +++ /dev/null @@ -1,100 +0,0 @@ -# @ohos.application.errorManager (ErrorManager) - -The **ErrorManager** module provides APIs for registering and deregistering error observers. - -> **NOTE** -> -> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import -```ts -import errorManager from '@ohos.application.errorManager'; -``` - -## ErrorManager.registerErrorObserver - -registerErrorObserver(observer: ErrorObserver): number; - -Registers an error observer. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| - -**Example** - -```ts -var observer = { - onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) - } -} -errorManager.registerErrorObserver(observer) -``` - -## ErrorManager.unregisterErrorObserver - -unregisterErrorObserver(observerId: number, callback: AsyncCallback\): void; - -Deregisters an error observer. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observerId | number | Yes| Numeric code of the observer.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Example** - -```ts -var observerId = 100; - -function unregisterErrorObserverCallback(err) { - if (err) { - console.log('------------ unregisterErrorObserverCallback ------------', err); - } -} -errorManager.unregisterErrorObserver(observerId, unregisterErrorObserverCallback); - -``` - -## ErrorManager.unregisterErrorObserver - -unregisterErrorObserver(observerId: number): Promise\; - -Deregisters an error observer. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observerId | number | Yes| Numeric code of the observer.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```ts -var observerId = 100; -errorManager.unregisterErrorObserver(observerId) -.then((data) => { - console.log('----------- unregisterErrorObserver success ----------', data); -}) -.catch((err) => { - console.log('----------- unregisterErrorObserver fail ----------', err); -}) - -``` diff --git a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md deleted file mode 100644 index f18b293edd8d7a4f65684bc38df4fe48498fa11b..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md +++ /dev/null @@ -1,62 +0,0 @@ -# @ohos.application.ExtensionAbility (ExtensionAbility) - -The **ExtensionAbility** module manages the ExtensionAbility lifecycle and context, such as creating and destroying an ExtensionAbility, and dumping client information. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import ExtensionAbility from '@ohos.application.ExtensionAbility'; -``` - -## ExtensionAbility.onConfigurationUpdated - -onConfigurationUpdated(newConfig: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| - -**Example** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -## ExtensionAbility.onMemoryLevel - -onMemoryLevel(level: AbilityConstant.MemoryLevel): void; - -Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| - -**Example** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md index e82f3f2f199c103a6b2ee6d1f15c54144ece2036..c7c5e55ff067afe25c43e57b0ce2491090324101 100644 --- a/en/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -35,7 +35,7 @@ Creates a **FormBindingData** object. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| +| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by **'formImages'**, and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {'formImages': {'key1': fd1, 'key2': fd2}}.| **Return value** @@ -52,13 +52,13 @@ import formBindingData from '@ohos.application.formBindingData'; import fs from '@ohos.file.fs'; try { - let fd = fs.openSync('/path/to/form.png') + let fd = fs.openSync('/path/to/form.png'); let obj = { - "temperature": "21°", - "formImages": { "image": fd } + 'temperature': '21°', + 'formImages': { 'image': fd } }; formBindingData.createFormBindingData(obj); -} catch (error.code) { - console.log('catch error, error:' + JSON.stringify(error)); +} catch (error) { + console.log('catch error, error: ${JSON.stringify(error)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formExtension.md b/en/application-dev/reference/apis/js-apis-application-formExtension.md deleted file mode 100644 index fcde831bc20ca03c224b977271f40b69f1ad0569..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-formExtension.md +++ /dev/null @@ -1,284 +0,0 @@ -# @ohos.application.FormExtension (FormExtension) - -The **FormExtension** module provides APIs related to Form Extension abilities. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> This module is deprecated since API version 9. You are advised to use [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) instead. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import FormExtension from '@ohos.application.FormExtension'; -``` - -## Attributes - -**System capability**: SystemCapability.Ability.Form - -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| - -## onCreate - -onCreate(want: Want): formBindingData.FormBindingData - -Called to notify the widget provider that a **Form** instance (widget) has been created. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | ----------------------------------------------------------- | -| [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| - -**Example** - -```ts -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onCreate(want) { - console.log('FormExtension onCreate, want:' + want.abilityName); - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -} -``` - -## FormExtension.onCastToNormal - -onCastToNormal(formId: string): void - -Called to notify the widget provider that a temporary widget has been converted to a normal one. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------ | -| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| - -**Example** - -```ts -export default class MyFormExtension extends FormExtension { - onCastToNormal(formId) { - console.log('FormExtension onCastToNormal, formId:' + formId); - } -} -``` - -## FormExtension.onUpdate - -onUpdate(formId: string): void - -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| formId | string | Yes | ID of the widget that requests to be updated.| - -**Example** - -```ts -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2).then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } -} -``` - -## FormExtension.onVisibilityChange - -onVisibilityChange(newStatus: { [key: string]: number }): void - -Called to notify the widget provider of the change of visibility. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ---------------------------- | -| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| - -**Example** - -```ts -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onVisibilityChange(newStatus) { - console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2).then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } -} -``` - -## FormExtension.onEvent - -onEvent(formId: string, message: string): void - -Called to instruct the widget provider to receive and process the widget event. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ---------------------- | -| formId | string | Yes | ID of the widget that requests the event.| -| message | string | Yes | Event message. | - -**Example** - -```ts -export default class MyFormExtension extends FormExtension { - onEvent(formId, message) { - console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); - } -} -``` - -## FormExtension.onDestroy - -onDestroy(formId: string): void - -Called to notify the widget provider that a **Form** instance (widget) has been destroyed. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| formId | string | Yes | ID of the widget to be destroyed.| - -**Example** - -```ts -export default class MyFormExtension extends FormExtension { - onDestroy(formId) { - console.log('FormExtension onDestroy, formId:' + formId); - } -} -``` - -## FormExtension.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| - -**Example** - -```ts -class MyFormExtension extends FormExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } -} -``` - -## FormExtension.onAcquireFormState - -onAcquireFormState?(want: Want): formInfo.FormState; - -Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| - -**Example** - -```ts -import formInfo from '@ohos.application.formInfo' -class MyFormExtension extends FormExtension { - onAcquireFormState(want) { - console.log('FormExtension onAcquireFormState, want:' + want); - return formInfo.FormState.UNKNOWN; - } -} -``` - -## FormExtension.onShare - -onShare?(formId: string): {[key: string]: any}; - -Called by the widget provider to receive shared widget data. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| formId | string | Yes | Widget ID.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | ----------------------------------------------------------- | -| {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| - -**Example** - -```ts -class MyFormExtension extends FormExtension { - onShare(formId) { - console.log('FormExtension onShare, formId:' + formId); - let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", - }; - return wantParams; - } -} -``` diff --git a/en/application-dev/reference/apis/js-apis-application-formHost.md b/en/application-dev/reference/apis/js-apis-application-formHost.md index 11da810effa714b8aaf37e35d3c0566556281ebf..30de68453080be4b6dc12f3693545d95787308d9 100644 --- a/en/application-dev/reference/apis/js-apis-application-formHost.md +++ b/en/application-dev/reference/apis/js-apis-application-formHost.md @@ -36,10 +36,10 @@ Deletes a widget. After this API is called, the application can no longer use th ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.deleteForm(formId, (error, data) => { if (error.code) { - console.error('formHost deleteForm, error:' + JSON.stringify(error)); + console.error('formHost deleteForm, error: ${JSON.stringify(error)}'); } }); ``` @@ -66,16 +66,16 @@ Deletes a widget. After this API is called, the application can no longer use th | -------- | -------- | | Promise<void> | Promise that returns no value.| -**Parameters** +**Example** ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.error('formHost deleteForm, error:' + JSON.stringify(error)); + console.error('formHost deleteForm, error: ${JSON.stringify(error)}'); }); ``` @@ -101,10 +101,10 @@ Releases a widget. After this API is called, the application can no longer use t ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.releaseForm(formId, (error, data) => { if (error.code) { - console.error('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error: ${JSON.stringify(error)}'); } else { console.log('formHost releaseForm success'); } @@ -134,10 +134,10 @@ Releases a widget. After this API is called, the application can no longer use t ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.releaseForm(formId, true, (error, data) => { if (error.code) { - console.error('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error: ${JSON.stringify(error)}'); } else { console.log('formHost releaseForm success'); } @@ -172,11 +172,11 @@ Releases a widget. After this API is called, the application can no longer use t ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.error('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error: ${JSON.stringify(error)}'); }); ``` @@ -202,10 +202,10 @@ Requests a widget update. This API uses an asynchronous callback to return the r ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.requestForm(formId, (error, data) => { if (error.code) { - console.error('formHost requestForm, error:' + JSON.stringify(error)); + console.error('formHost requestForm, error: ${JSON.stringify(error)}'); } }); ``` @@ -237,11 +237,11 @@ Requests a widget update. This API uses a promise to return the result. ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.error('formHost requestForm, error:' + JSON.stringify(error)); + console.error('formHost requestForm, error: ${JSON.stringify(error)}'); }); ``` @@ -267,10 +267,10 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.castTempForm(formId, (error, data) => { if (error.code) { - console.error('formHost castTempForm, error:' + JSON.stringify(error)); + console.error('formHost castTempForm, error: ${JSON.stringify(error)}'); } }); ``` @@ -302,11 +302,11 @@ Converts a temporary widget to a normal one. This API uses a promise to return t ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.castTempForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.error('formHost castTempForm, error:' + JSON.stringify(error)); + console.error('formHost castTempForm, error: ${JSON.stringify(error)}'); }); ``` @@ -332,10 +332,10 @@ Instructs the widget framework to make a widget visible. After this API is calle ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId, (error, data) => { if (error.code) { - console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyVisibleForms, error: ${JSON.stringify(error)}'); } }); ``` @@ -367,11 +367,11 @@ Instructs the widget framework to make a widget visible. After this API is calle ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyVisibleForms, error: ${JSON.stringify(error)}'); }); ``` @@ -397,10 +397,10 @@ Instructs the widget framework to make a widget invisible. After this API is cal ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId, (error, data) => { if (error.code) { - console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyInvisibleForms, error: ${JSON.stringify(error)}'); } }); ``` @@ -432,11 +432,11 @@ Instructs the widget framework to make a widget invisible. After this API is cal ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyInvisibleForms, error: ${JSON.stringify(error)}'); }); ``` @@ -462,10 +462,10 @@ Instructs the widget framework to make a widget updatable. After this API is cal ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId, (error, data) => { if (error.code) { - console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost enableFormsUpdate, error: ${JSON.stringify(error)}'); } }); ``` @@ -497,11 +497,11 @@ Instructs the widget framework to make a widget updatable. After this API is cal ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost enableFormsUpdate, error: ${JSON.stringify(error)}'); }); ``` @@ -527,10 +527,10 @@ Instructs the widget framework to make a widget not updatable. After this API is ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId, (error, data) => { if (error.code) { - console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost disableFormsUpdate, error: ${JSON.stringify(error)}'); } }); ``` @@ -562,11 +562,11 @@ Instructs the widget framework to make a widget not updatable. After this API is ```ts import formHost from '@ohos.application.formHost'; -let formId = ["12400633174999288"]; +let formId = ['12400633174999288']; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost disableFormsUpdate, error: ${JSON.stringify(error)}'); }); ``` @@ -589,10 +589,10 @@ Checks whether the system is ready. This API uses an asynchronous callback to re ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.isSystemReady((error, data) => { if (error.code) { - console.error('formHost isSystemReady, error:' + JSON.stringify(error)); + console.error('formHost isSystemReady, error: ${JSON.stringify(error)}'); } }); ``` @@ -616,11 +616,11 @@ Checks whether the system is ready. This API uses a promise to return the result ```ts import formHost from '@ohos.application.formHost'; -let formId = "12400633174999288"; +let formId = '12400633174999288'; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.error('formHost isSystemReady, error:' + JSON.stringify(error)); + console.error('formHost isSystemReady, error: ${JSON.stringify(error)}'); }); ``` @@ -647,9 +647,9 @@ import formHost from '@ohos.application.formHost'; formHost.getAllFormsInfo((error, data) => { if (error.code) { - console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getAllFormsInfo, error: ${JSON.stringify(error)}'); } else { - console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo, data: ${JSON.stringify(data)}'); } }); ``` @@ -676,9 +676,9 @@ Obtains the widget information provided by all applications on the device. This import formHost from '@ohos.application.formHost'; formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + console.log('formHost getAllFormsInfo data: ${JSON.stringify(data)}'); }).catch((error) => { - console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getAllFormsInfo, error: ${JSON.stringify(error)}'); }); ``` @@ -704,11 +704,11 @@ Obtains the widget information provided by a given application on the device. Th ```ts import formHost from '@ohos.application.formHost'; -formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { +formHost.getFormsInfo('com.example.ohos.formjsdemo', (error, data) => { if (error.code) { - console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error: ${JSON.stringify(error)}'); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); } }); ``` @@ -736,11 +736,11 @@ Obtains the widget information provided by a given application on the device. Th ```ts import formHost from '@ohos.application.formHost'; -formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { +formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry', (error, data) => { if (error.code) { - console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error: ${JSON.stringify(error)}'); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); } }); ``` @@ -773,10 +773,10 @@ Obtains the widget information provided by a given application on the device. Th ```ts import formHost from '@ohos.application.formHost'; - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + formHost.getFormsInfo('com.example.ohos.formjsdemo', 'entry').then((data) => { + console.log('formHost getFormsInfo, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error: ${JSON.stringify(error)}'); }); ``` @@ -802,12 +802,12 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to ```ts import formHost from '@ohos.application.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds, (error, data) => { if (error.code) { - console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.error('formHost deleteInvalidForms, error: ${JSON.stringify(error)}'); } else { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + console.log('formHost deleteInvalidForms, data: ${JSON.stringify(data)}'); } }); ``` @@ -839,11 +839,11 @@ Deletes invalid widgets from the list. This API uses a promise to return the res ```ts import formHost from '@ohos.application.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.deleteInvalidForms(formIds).then((data) => { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + console.log('formHost deleteInvalidForms, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.error('formHost deleteInvalidForms, error: ${JSON.stringify(error)}'); }); ``` @@ -870,20 +870,20 @@ Obtains the widget state. This API uses an asynchronous callback to return the r import formHost from '@ohos.application.formHost'; let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; formHost.acquireFormState(want, (error, data) => { if (error.code) { - console.error('formHost acquireFormState, error:' + JSON.stringify(error)); + console.error('formHost acquireFormState, error: ${JSON.stringify(error)}'); } else { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + console.log('formHost acquireFormState, data: ${JSON.stringify(data)}'); } }); ``` @@ -916,25 +916,25 @@ Obtains the widget state. This API uses a promise to return the result. import formHost from '@ohos.application.formHost'; let want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 + 'deviceId': '', + 'bundleName': 'ohos.samples.FormApplication', + 'abilityName': 'FormAbility', + 'parameters': { + 'ohos.extra.param.key.module_name': 'entry', + 'ohos.extra.param.key.form_name': 'widget', + 'ohos.extra.param.key.form_dimension': 2 } }; formHost.acquireFormState(want).then((data) => { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + console.log('formHost acquireFormState, data: ${JSON.stringify(data)}'); }).catch((error) => { - console.error('formHost acquireFormState, error:' + JSON.stringify(error)); + console.error('formHost acquireFormState, error: ${JSON.stringify(error)}'); }); ``` -## on("formUninstall") +## on('formUninstall') -on(type: "formUninstall", callback: Callback<string>): void +on(type: 'formUninstall', callback: Callback<string>): void Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. @@ -944,7 +944,7 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.| | callback | Callback<string> | Yes| Callback used to return the widget ID.| **Example** @@ -953,14 +953,14 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to import formHost from '@ohos.application.formHost'; let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); -} -formHost.on("formUninstall", callback); + console.log('formHost on formUninstall, formId: ${formId}'); +}; +formHost.on('formUninstall', callback); ``` -## off("formUninstall") +## off('formUninstall') -off(type: "formUninstall", callback?: Callback<string>): void +off(type: 'formUninstall', callback?: Callback<string>): void Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. @@ -970,8 +970,8 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on("formUninstall")**.| +| type | string | Yes | Event type. The value **'formUninstall'** indicates a widget uninstallation event.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on('formUninstall')**.| **Example** @@ -979,9 +979,9 @@ Unsubscribes from widget uninstall events. This API uses an asynchronous callbac import formHost from '@ohos.application.formHost'; let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); -} -formHost.off("formUninstall", callback); + console.log('formHost on formUninstall, formId: ${formId}'); +}; +formHost.off('formUninstall', callback); ``` ## notifyFormsVisible @@ -1007,10 +1007,10 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous ```ts import formHost from '@ohos.application.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsVisible(formIds, true, (error, data) => { if (error.code) { - console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsVisible, error: ${JSON.stringify(error)}'); } }); ``` @@ -1043,11 +1043,11 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret ```ts import formHost from '@ohos.application.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsVisible, error: ${JSON.stringify(error)}'); }); ``` @@ -1074,10 +1074,10 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou ```ts import formHost from '@ohos.application.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { if (error.code) { - console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsEnableUpdate, error: ${JSON.stringify(error)}'); } }); ``` @@ -1110,145 +1110,10 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r ```ts import formHost from '@ohos.application.formHost'; -let formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array('12400633174999288', '12400633174999289'); formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); -}); -``` -## shareForm9+ - -shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void - -Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.| - -**Example** - -```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; -formHost.shareForm(formId, deviceId, (error, data) => { - if (error.code) { - console.error('formHost shareForm, error:' + JSON.stringify(error)); - } + console.error('formHost notifyFormsEnableUpdate, error: ${JSON.stringify(error)}'); }); ``` - -## shareForm9+ - -shareForm(formId: string, deviceId: string): Promise<void> - -Shares a specified widget with a remote device. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise that returns no value.| - -**Parameters** - -```ts -import formHost from '@ohos.application.formHost'; - -let formId = "12400633174999288"; -let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; -formHost.shareForm(formId, deviceId).then(() => { - console.log('formHost shareForm success'); -}).catch((error) => { - console.error('formHost shareForm, error:' + JSON.stringify(error)); -}); -``` - -## notifyFormsPrivacyProtected9+ - -notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean, callback: AsyncCallback<void>): void - -Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| - -```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); -formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost shareForm success'); -}).catch((error) => { - console.error('formHost shareForm, error:' + JSON.stringify(error)); -}); -``` - -## notifyFormsPrivacyProtected - -function notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean): Promise<void>; - -Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | --------------- | ---- | -------------------------------- | -| formIds | Array<string> | Yes | ID of the widgets.| -| isProtected | boolean | Yes | Whether privacy protection is enabled. | - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| - - -```ts -import formHost from '@ohos.application.formHost'; - -let formIds = new Array("12400633174999288", "12400633174999289"); -try { - formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost notifyFormsPrivacyProtected success'); - }).catch((error) => { - console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); - }); -} catch(error) { - console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); -} -``` diff --git a/en/application-dev/reference/apis/js-apis-application-formInfo.md b/en/application-dev/reference/apis/js-apis-application-formInfo.md index df591cea222b9bdbc98c4d108a4151a8aa1c69cb..96cb62a8eb83ab71ed3fad0ed7ea45651dcdf9ef 100644 --- a/en/application-dev/reference/apis/js-apis-application-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-application-formInfo.md @@ -49,7 +49,6 @@ Enumerates the widget types. | Name | Value | Description | | ----------- | ---- | ------------ | | JS | 1 | JS widget. | -| eTS9+ | 2 | eTS widget.| ## ColorMode @@ -94,48 +93,10 @@ Enumerates the widget parameters. | Name | Value | Description | | ----------- | ---- | ------------ | -| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | Widget ID.
**System API**: This is a system API. | -| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | -| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | -| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | -| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | -| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | -| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | -| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | -| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID. | -| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| - -## FormDimension9+ - -Enumerates the widget dimensions. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| Dimension_1_2 9+ | 1 | 1 x 2. | -| Dimension_2_2 9+ | 2 | 2 x 2. | -| Dimension_2_4 9+ | 3 | 2 x 4. | -| Dimension_4_4 9+ | 4 | 4 x 4. | -| Dimension_2_1 9+ | 5 | 2 x 1. | - -## FormInfoFilter9+ - -Defines the widget information filter. Only the widget information that meets the filter is returned. - -**System capability**: SystemCapability.Ability.Form - -| Name | Description | -| ----------- | ------------ | -| moduleName9+ | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering.| - -## VisibilityType9+ - -Enumerates the visibility types of the widget. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| FORM_VISIBLE9+ | 1 | The widget is visible.| -| FORM_INVISIBLE9+ | 2 | The widget is invisible.| +| IDENTITY_KEY | 'ohos.extra.param.key.form_identity' | Widget ID.
**System API**: This is a system API. | +| DIMENSION_KEY | 'ohos.extra.param.key.form_dimension' | Widget dimension. | +| NAME_KEY | 'ohos.extra.param.key.form_name' | Widget name. | +| MODULE_NAME_KEY | 'ohos.extra.param.key.module_name' | Name of the module to which the widget belongs. | +| WIDTH_KEY | 'ohos.extra.param.key.form_width' | Widget width. | +| HEIGHT_KEY | 'ohos.extra.param.key.form_height' | Widget height. | +| TEMPORARY_KEY | 'ohos.extra.param.key.form_temporary' | Temporary widget. | diff --git a/en/application-dev/reference/apis/js-apis-application-formProvider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md index 15428096d42ef9321249dc924e3569bbe4c4809a..81b1711b18d198350e0ee6f759a7587b805cc66c 100644 --- a/en/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -33,10 +33,10 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback ```ts import formProvider from '@ohos.app.form.formProvider'; - let formId = "12400633174999288"; + let formId = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error.code) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log('formProvider setFormNextRefreshTime, error: ${JSON.stringify(error)}'); } }); ``` @@ -67,11 +67,11 @@ Sets the next refresh time for a widget. This API uses a promise to return the r ```ts import formProvider from '@ohos.app.form.formProvider'; - let formId = "12400633174999288"; + let formId = '12400633174999288'; formProvider.setFormNextRefreshTime(formId, 5).then(() => { console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log('formProvider setFormNextRefreshTime, error: ${JSON.stringify(error)}'); }); ``` @@ -97,11 +97,11 @@ Updates a widget. This API uses an asynchronous callback to return the result. import formBindingData from '@ohos.app.form.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; - let formId = "12400633174999288"; - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + let formId = '12400633174999288'; + let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); formProvider.updateForm(formId, obj, (error, data) => { if (error.code) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log('formProvider updateForm, error: ${JSON.stringify(error)}'); } }); ``` @@ -133,316 +133,11 @@ Updates a widget. This API uses a promise to return the result. import formBindingData from '@ohos.application.formBindingData'; import formProvider from '@ohos.app.form.formProvider'; - let formId = "12400633174999288"; - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + let formId = '12400633174999288'; + let obj = formBindingData.createFormBindingData({temperature:'22c', time:'22:00'}); formProvider.updateForm(formId, obj).then(() => { console.log('formProvider updateForm success'); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log('formProvider updateForm, error: ${JSON.stringify(error)}'); }); ``` - -## getFormsInfo9+ - -getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void - -Obtains the application's widget information on the device. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| - -**Example** - -```ts -import formProvider from '@ohos.app.form.formProvider'; - -formProvider.getFormsInfo((error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } -}); -``` -## getFormsInfo9+ - -getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void - -Obtains the application's widget information that meets a filter criterion on the device. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| - -**Example** - -```ts -import formInfo from '@ohos.application.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" -}; -formProvider.getFormsInfo(filter, (error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } -}); -``` - -## getFormsInfo9+ - -getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>> - -Obtains the application's widget information on the device. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md) | No| Filter criterion.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| - -**Example** - -```ts -import formInfo from '@ohos.application.formInfo'; -import formProvider from '@ohos.app.form.formProvider'; - -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" -}; -formProvider.getFormsInfo(filter).then((data) => { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); -}).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); -}); -``` - -## requestPublishForm9+ - -requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void - -Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. - -**System capability**: SystemCapability.Ability.Form - -**System API**: This is a system API. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| -| callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| - -**Example** - - ```ts - import formBindingData from '@ohos.application.formBindingData'; - import formProvider from '@ohos.app.form.formProvider'; - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - formProvider.requestPublishForm(want, obj, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } - }); - ``` - -## requestPublishForm9+ - -requestPublishForm(want: Want, callback: AsyncCallback<string>): void - -Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. - -**System capability**: SystemCapability.Ability.Form - -**System API**: This is a system API. - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| - -**Example** - - ```ts - import formProvider from '@ohos.app.form.formProvider'; - - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } - }); - ``` - -## requestPublishForm9+ - -requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string> - -Requests to publish a widget to the widget host. This API uses a promise to return the result. This API is usually called by the home screen. - -**System capability**: SystemCapability.Ability.Form - -**System API**: This is a system API. - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<string> | Promise used to return the widget ID.| - -**Example** - - ```ts - import formProvider from '@ohos.app.form.formProvider'; - - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); - }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - }); - ``` - -## isRequestPublishFormSupported9+ - -isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void - -Checks whether a widget can be published to the widget host. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the widget can be published to the widget host.| - -**Example** - -```ts -formProvider.isRequestPublishFormSupported((error, isSupported) => { - if (error.code) { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); - } else { - if (isSupported) { - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } - }); - } - } -}); -``` - -## isRequestPublishFormSupported9+ - -isRequestPublishFormSupported(): Promise<boolean> - -Checks whether a widget can be published to the widget host. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Ability.Form - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<boolean> | Promise used to return whether the widget can be published to the widget host.| - -**Example** - -```ts -formProvider.isRequestPublishFormSupported().then((isSupported) => { - if (isSupported) { - let want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); - }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - }); - } -}).catch((error) => { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); -}); -``` diff --git a/en/application-dev/reference/apis/js-apis-application-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md index 17de66e19334dce9663017c3df9c18b575e14bd7..8e180f9286a98e8c04ef41505c2e3439f866d01e 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -9,7 +9,7 @@ The **missionManager** module provides APIs to lock, unlock, and clear missions, ## Modules to Import ```ts -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.application.missionManager'; ``` ## Required Permissions @@ -43,17 +43,17 @@ Registers a listener to observe the mission status. **Example** ```ts -var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; -console.log("registerMissionListener") -var listenerid = missionManager.registerMissionListener(listener); +console.log('registerMissionListener'); +let listenerid = missionManager.registerMissionListener(listener); ``` @@ -79,21 +79,21 @@ Deregisters a mission status listener. This API uses an asynchronous callback to **Example** ```ts - var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); + console.log('registerMissionListener'); + let listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid, (error) => { - console.log("unregisterMissionListener"); - }) + console.log('unregisterMissionListener'); + }); ``` @@ -124,17 +124,17 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** ```ts - var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, - onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} + let listener = { + onMissionCreated: function (mission) {console.log('--------onMissionCreated-------');}, + onMissionDestroyed: function (mission) {console.log('--------onMissionDestroyed-------');}, + onMissionSnapshotChanged: function (mission) {console.log('--------onMissionSnapshotChanged-------');}, + onMissionMovedToFront: function (mission) {console.log('--------onMissionMovedToFront-------');}, + onMissionIconUpdated: function (mission, icon) {console.log('--------onMissionIconUpdated-------');}, + onMissionClosed: function (mission) {console.log('--------onMissionClosed-------');}, + onMissionLabelUpdated: function (mission) {console.log('--------onMissionLabelUpdated-------');} }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); + console.log('registerMissionListener'); + let listenerid = missionManager.registerMissionListener(listener); missionManager.unregisterMissionListener(listenerid).catch(function (err) { console.log(err); @@ -165,22 +165,21 @@ Obtains the information about a given mission. This API uses an asynchronous cal **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); - missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { + let allMissions=missionManager.getMissionInfos('',10).catch(function(err){console.log(err);}); + missionManager.getMissionInfo('', allMissions[0].missionId, (error, mission) => { if (error.code) { - console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("mission.missionId = " + mission.missionId); - console.log("mission.runningState = " + mission.runningState); - console.log("mission.lockedState = " + mission.lockedState); - console.log("mission.timestamp = " + mission.timestamp); - console.log("mission.label = " + mission.label); - console.log("mission.iconPath = " + mission.iconPath); + console.log('mission.missionId = ${mission.missionId}'); + console.log('mission.runningState = ${mission.runningState}'); + console.log('mission.lockedState = ${mission.lockedState}'); + console.log('mission.timestamp = ${mission.timestamp}'); + console.log('mission.label = ${mission.label}'); + console.log('mission.iconPath = ${mission.iconPath}'); }); ``` @@ -213,9 +212,9 @@ Obtains the information about a given mission. This API uses a promise to return **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var mission = missionManager.getMissionInfo("", 10).catch(function (err){ + let mission = missionManager.getMissionInfo('', 10).catch(function (err){ console.log(err); }); ``` @@ -244,17 +243,16 @@ Obtains information about all missions. This API uses an asynchronous callback t **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - }) + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + }); ``` @@ -286,9 +284,9 @@ Obtains information about all missions. This API uses a promise to return the re **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ + let allMissions = missionManager.getMissionInfos('', 10).catch(function (err){ console.log(err); }); ``` @@ -317,27 +315,25 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; - missionManager.getMissionSnapShot("", id, (error, snapshot) => { + missionManager.getMissionSnapShot('', id, (error, snapshot) => { if (error.code) { - console.log("getMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionSnapShot failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) + console.log('bundleName = ${snapshot.ability.bundleName}'); + }); + }); ``` @@ -369,17 +365,17 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ${allMissions.length}'); + console.log('missions = ${JSON.stringify(allMissions)}'); + let id = allMissions[0].missionId; - var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ + let snapshot = missionManager.getMissionSnapShot('', id).catch(function (err){ console.log(err); }); ``` @@ -407,27 +403,26 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; - missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { + missionManager.getLowResolutionMissionSnapShot('', id, (error, snapshot) => { if (error.code) { - console.log("getLowResolutionMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getLowResolutionMissionSnapShot failed, error.code: ${JSON.stringify(error.code)} + 'error.message: ${JSON.stringify(error.message)}'); return; } - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) + console.log('bundleName = ${snapshot.ability.bundleName}'); + }); + }); ``` @@ -459,17 +454,17 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ${allMissions.length}'); + console.log('missions = ${JSON.stringify(allMissions)}'); + let id = allMissions[0].missionId; - var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ + let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (err){ console.log(err); }); ``` @@ -497,21 +492,21 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)} + 'error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; missionManager.lockMission(id).then(() => { - console.log("lockMission is called "); - }); + console.log('lockMission is called '); + }); }); ``` @@ -543,14 +538,14 @@ Locks a given mission. This API uses a promise to return the result. **Example** ```ts - import missionManager from '@ohos.application.missionManager' - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + import missionManager from '@ohos.application.missionManager'; + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ${allMissions.length}'); + console.log('missions = ${JSON.stringify(allMissions)}'); + let id = allMissions[0].missionId; missionManager.lockMission(id).catch(function (err){ console.log(err); @@ -580,21 +575,20 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; missionManager.unlockMission(id).then(() => { - console.log("unlockMission is called "); - }); + console.log('unlockMission is called '); + }); }); ``` @@ -626,15 +620,15 @@ Unlocks a given mission. This API uses a promise to return the result. **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ${allMissions.length}'); + console.log('missions = ${JSON.stringify(allMissions)}'); + let id = allMissions[0].missionId; missionManager.lockMission(id).catch(function (err){ console.log(err); @@ -667,21 +661,20 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; missionManager.clearMission(id).then(() => { - console.log("clearMission is called "); - }); + console.log('clearMission is called '); + }); }); ``` @@ -713,15 +706,15 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ${allMissions.length}'); + console.log('missions = ${JSON.stringify(allMissions)}'); + let id = allMissions[0].missionId; missionManager.clearMission(id).catch(function (err){ console.log(err); @@ -747,7 +740,7 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t import missionManager from '@ohos.application.missionManager' missionManager.clearAllMissions().then(() => { - console.log("clearAllMissions is called "); + console.log('clearAllMissions is called '); }); ``` @@ -773,7 +766,7 @@ Clears all unlocked missions. This API uses a promise to return the result. **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; missionManager.clearAllMissions().catch(function (err){ console.log(err); }); @@ -802,21 +795,20 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; missionManager.moveMissionToFront(id).then(() => { - console.log("moveMissionToFront is called "); - }); + console.log('moveMissionToFront is called '); + }); }); ``` @@ -838,26 +830,25 @@ Switches a given mission to the foreground, with the startup parameters for the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| - | options | [StartOptions](js-apis-application-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => { - console.log("moveMissionToFront is called "); + console.log('moveMissionToFront is called '); }); }); ``` @@ -880,7 +871,7 @@ Switches a given mission to the foreground, with the startup parameters for the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| - | options | [StartOptions](js-apis-application-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| **Return value** @@ -891,15 +882,15 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** ```ts - import missionManager from '@ohos.application.missionManager' + import missionManager from '@ohos.application.missionManager'; - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ + let allMissions; + missionManager.getMissionInfos('',10).then(function(res){ allMissions=res; }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; + console.log('size = ${allMissions.length}'); + console.log('missions = ${JSON.stringify(allMissions)}'); + let id = allMissions[0].missionId; missionManager.moveMissionToFront(id).catch(function (err){ console.log(err); diff --git a/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md deleted file mode 100644 index beb8c007b0fa58bdae058ac554c96425bdf93bd5..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md +++ /dev/null @@ -1,255 +0,0 @@ -# @ohos.application.ServiceExtensionAbility (ServiceExtensionAbility) - -The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. - -> **NOTE** -> -> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. -> -> Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; -``` - -## Required Permissions - -None. - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| - - -## ServiceExtensionAbility.onCreate - -onCreate(want: Want): void; - -Called when a Service Extension ability is created to initialize the service logic. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - onCreate(want) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onDestroy - -onDestroy(): void; - -Called when this Service Extension ability is destroyed to clear resources. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## ServiceExtensionAbility.onRequest - -onRequest(want: Want, startId: number): void; - -Called after **onCreate** is invoked when a Service Extension ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| -| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - onRequest(want, startId) { - console.log('onRequest, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onConnect - -onConnect(want: Want): rpc.RemoteObject; - -Called after **onCreate** is invoked when a Service Extension ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| - -**Example** - - ```ts - import rpc from '@ohos.rpc' - class StubTest extends rpc.RemoteObject{ - constructor(des) { - super(des); - } - onConnect(code, data, reply, option) { - } - } - class ServiceExt extends ServiceExtension { - onConnect(want) { - console.log('onConnect , want:' + want.abilityName); - return new StubTest("test"); - } - } - ``` - - -## ServiceExtensionAbility.onDisconnect - -onDisconnect(want: Want): void; - -Called when this Service Extension ability is disconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); - } - } - ``` - -## ServiceExtensionAbility.onReconnect - -onReconnect(want: Want): void; - -Called when this Service Extension ability is reconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - onReconnect(want) { - console.log('onReconnect, want:' + want.abilityName); - } - } - ``` - -## ServiceExtensionAbility.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of this Service Extension ability is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -## ServiceExtensionAbility.dump - -dump(params: Array\): Array\; - -Dumps the client information. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| params | Array\ | Yes| Parameters in the form of a command.| - -**Example** - - ```ts - class ServiceExt extends ServiceExtension { - dump(params) { - console.log('dump, params:' + JSON.stringify(params)); - return ["params"] - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-application-startOptions.md b/en/application-dev/reference/apis/js-apis-application-startOptions.md deleted file mode 100644 index 7634b276495d98e18bc7ec966f3483e526dd3ba3..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-startOptions.md +++ /dev/null @@ -1,23 +0,0 @@ -# @ohos.application.StartOptions (StartOptions) - -The **StartOptions** module implements ability startup options. - -> **NOTE** -> -> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Modules to Import - -```ts -import StartOptions from '@ohos.application.StartOptions'; -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| -| displayId | number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index 5fc9b0999940310b10bf7b4e7227d5651153eb50..096433a60c44904bbe9b2f25d09e9384e192c7fb 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -10,7 +10,7 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for ## Modules to Import ```ts -import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' +import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'; ``` ## StaticSubscriberExtensionAbility.onReceiveEvent @@ -32,12 +32,9 @@ Callback of the common event of a static subscriber. **Example** ```ts - var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") - { - onReceiveEvent(event){ - console.log('onReceiveEvent,event:' + event.code); - } - } - export default MyStaticSubscriberExtensionAbility - + class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility { + onReceiveEvent(event) { + console.log('onReceiveEvent, event: ${JSON.stringify(event)}'); + } + } ``` diff --git a/en/application-dev/reference/apis/js-apis-application-testRunner.md b/en/application-dev/reference/apis/js-apis-application-testRunner.md index d2146524c0c5249374e21c95762438d35dc48c35..34d272091725be3a4086b6df466f02f4aff38e7c 100644 --- a/en/application-dev/reference/apis/js-apis-application-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-application-testRunner.md @@ -11,7 +11,7 @@ To implement your own unit test framework, extend this class and override its AP ## Modules to Import ```ts -import TestRunner from '@ohos.application.testRunner' +import TestRunner from '@ohos.application.testRunner'; ``` ## TestRunner.onPrepare @@ -27,7 +27,7 @@ Prepares the unit test environment to run test cases. ```ts export default class UserTestRunner implements TestRunner { onPrepare() { - console.log("Trigger onPrepare") + console.log('Trigger onPrepare'); } onRun() {} }; @@ -49,7 +49,7 @@ Runs test cases. export default class UserTestRunner implements TestRunner { onPrepare() {} onRun() { - console.log("Trigger onRun") + console.log('Trigger onRun'); } }; ``` diff --git a/en/application-dev/reference/apis/js-apis-application-want.md b/en/application-dev/reference/apis/js-apis-application-want.md index 44cc01a00c5057488b45a5a6a38cc02adbf1cbc2..d5fd64638541acdb567b3d2a04d4bf5933c822f1 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -4,7 +4,7 @@ Want is a carrier for information transfer between objects (application componen > **NOTE** > -> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -22,10 +22,10 @@ import Want from '@ohos.application.Want'; | bundleName | string | No | Bundle name.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | +| type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| | action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | | entities | Array\ | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). | | moduleName9+ | string | No | Module to which the ability belongs.| @@ -35,15 +35,15 @@ import Want from '@ohos.application.Want'; ```ts let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry" // moduleName is optional. + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.example.myapplication', + 'abilityName': 'EntryAbility', + 'moduleName': 'entry' // moduleName is optional. }; this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + console.log('error.code = ${error.code}'); + }); ``` - Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility): @@ -51,84 +51,84 @@ import Want from '@ohos.application.Want'; * String ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', parameters: { - keyForString: "str", + keyForString: 'str', }, - } + }; ``` * Number ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', parameters: { keyForInt: 100, keyForDouble: 99.99, }, - } + }; ``` * Boolean ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', parameters: { keyForBool: true, }, - } + }; ``` * Object ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', parameters: { keyForObject: { - keyForObjectString: "str", + keyForObjectString: 'str', keyForObjectInt: -200, keyForObjectDouble: 35.5, keyForObjectBool: false, }, }, - } + }; ``` * Array ```ts let want = { - bundleName: "com.example.myapplication", - abilityName: "EntryAbility", + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', parameters: { - keyForArrayString: ["str1", "str2", "str3"], + keyForArrayString: ['str1', 'str2', 'str3'], keyForArrayInt: [100, 200, 300, 400], keyForArrayDouble: [0.1, 0.2], - keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], + keyForArrayObject: [{obj1: 'aaa'}, {obj2: 100}], }, - } + }; ``` * File descriptor (FD) ```ts import fileio from '@ohos.fileio'; let fd; try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); + console.log('openSync fail: ${JSON.stringify(e)}'); } let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.example.myapplication', + 'abilityName': 'EntryAbility', + 'moduleName': 'entry', // moduleName is optional. + 'parameters': { + 'keyFd':{'type':'FD', 'value':fd} } }; this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + console.log('error.code = ${error.code}'); + }); ``` - For more details and examples, see [Want](../../application-models/want-overview.md). diff --git a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md index bd6d74bbcbbdb4b0d29ccad209b012a11f44c9af..80528c23b2edad90880162fb3055b7b51dc719d9 100644 --- a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md @@ -5,7 +5,7 @@ > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> > The APIs provided by this module are system APIs. > > The APIs of this module can be used only in the stage model. @@ -22,7 +22,7 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------------------- | -| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes | No | Context of an Extension ability. | +| context | [WindowExtensionContext](js-apis-inner-application-windowExtensionContext.md) | Yes | No | Context of an Extension ability. | ## WindowExtensionAbility.onConnect @@ -44,7 +44,7 @@ Called when this Window Extension ability is connected to an ability for the fir export default class MyWindowExtensionAbility extends WindowExtensionAbility { onConnect(want) { - console.info('WindowExtAbility onConnect ' + want.abilityName); + console.info('WindowExtAbility onConnect, abilityName: ${want.abilityName}'); } } @@ -71,7 +71,7 @@ Called when this Window Extension ability is disconnected from all connected abi export default class MyWindowExtensionAbility extends WindowExtensionAbility { onDisconnect(want) { - console.info('WindowExtAbility onDisconnect ' + want.abilityName); + console.info('WindowExtAbility onDisconnect, abilityName: ${want.abilityName}'); } } @@ -100,10 +100,10 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { onWindowReady(window) { window.loadContent('WindowExtAbility/pages/index1').then(() => { window.getProperties().then((pro) => { - console.log('WindowExtension ' + JSON.stringify(pro)); - }) + console.log('WindowExtension pro: ${JSON.stringify(pro)}'); + }); window.show(); - }) + }); } } diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md index 8e6821b79eb36a6bd93dd9aed2b9016a3029dad2..5ac1f36f06bc8cab683227b26bcacab465323408 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md @@ -6,8 +6,6 @@ The **BundleInfo** module defines the bundle information. A system application c > > 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. - - ## BundleInfo **System capability**: SystemCapability.BundleManager.BundleFramework.Core diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md index 016b7af13fded843c7c85f05834669aa5e45c2bd..7ed2eac254782a4616a51cf0dfdfc02a46ac70f3 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md @@ -1,6 +1,6 @@ # ExtensionAbilityInfo -The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A system application can obtain its own or others' ExtensionAbility information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own ExtensionAbility information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY** must be passed in to the input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) to obtain the information. +The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A system application can obtain its own or others' ExtensionAbility information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own ExtensionAbility information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). The input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) must be set to **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY**. > **NOTE** > @@ -18,7 +18,7 @@ The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A | labelId | number | Yes | No | ID of the ExtensionAbility label. | | descriptionId | number | Yes | No | ID of the ExtensionAbility description. | | iconId | number | Yes | No | ID of the ExtensionAbility icon. | -| isVisible | boolean | Yes | No | Whether the ExtensionAbility can be called by other bundles. | +| exported | boolean | Yes | No | Whether the ExtensionAbility can be called by other bundles. | | extensionAbilityType | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | Type of the ExtensionAbility. | | permissions | Array\ | Yes | No | Permissions required for other bundles to call the ExtensionAbility.| | applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md index 8fe0cc4768b4b0ac352fcd98d9cefad9cc2c1553..146e3da56069f96ce10e20a62b9d2474bc51508a 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md @@ -1,6 +1,6 @@ # HapModuleInfo -The **HapModuleInfo** module defines the HAP module information. A system application can obtain its own or others' HAP module information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own HAP module information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **GET_BUNDLE_INFO_WITH_HAP_MODULE** must be passed in to the input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) to obtain the information. +The **HapModuleInfo** module defines the HAP module information. A system application can obtain its own or others' HAP module information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own HAP module information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). The input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) must be set to **GET_BUNDLE_INFO_WITH_HAP_MODULE**. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index 38e42db4dc336dece5467e60c3a390d579fcac98..a346a61081df95cc18e35898c07674db7bd3f318 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -147,7 +147,7 @@ Enumerates the launch types of the ability. | Name| Value| Description| |:----------------:|:---:|:---:| | SINGLETON | 0 | The ability can have only one instance.| -| STANDARD | 1 | The ability can have multiple instances.| +| MULTITON | 1 | The ability can have multiple instances.| | SPECIFIED | 2 | The ability can have one or multiple instances, depending on the internal service of the ability.| ### AbilityType @@ -2236,8 +2236,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName does not exist. | -| 17700003 | The specified abilityName does not exist. | +| 17700002 | The specified moduleName is not existed. | +| 17700003 | The specified abilityName is not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2292,8 +2292,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName does not exist. | -| 17700003 | The specified abilityName does not exist. | +| 17700002 | The specified moduleName is not existed. | +| 17700003 | The specified abilityName is not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2357,7 +2357,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName does not exist. | +| 17700002 | The specified moduleName is not existed. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | @@ -2412,7 +2412,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName does not exist. | +| 17700002 | The specified moduleName is not existed. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | @@ -2655,122 +2655,11 @@ try { } ``` -### bundleManager.getAbilityIcon - -getAbilityIcon(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)>): void; - -Obtains the ability icon based on the given bundle name, module name, and ability name. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO - -**System capability**: SystemCapability.BundleManager.BundleFramework.Resource - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| moduleName | string | Yes | Module name. | -| abilityName | string | Yes | Ability name. | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **PixelMap** object of the icon. Otherwise, **err** is an error object.| - -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - -| ID| Error Message | -| -------- | -------------------------------------- | -| 17700001 | The specified bundleName is not found. | -| 17700002 | The specified moduleName is not found. | -| 17700003 | The specified abilityName is not found. | -| 17700026 | The specified bundle is disabled. | -| 17700029 | The specified ability is disabled. | - -**Example** - -```ts -import bundleManager from '@ohos.bundle.bundleManager'; -import hilog from '@ohos.hilog'; -let bundleName = 'com.example.myapplication'; -let moduleName = 'entry'; -let abilityName = 'EntryAbility'; - -try { - bundleManager.getAbilityIcon(bundleName, moduleName, abilityName, (err, data) => { - if (err) { - hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); - } else { - hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully: %{public}s', JSON.stringify(data)); - } - }); -} catch (err) { - hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); -} -``` - -### bundleManager.getAbilityIcon - -getAbilityIcon(bundleName: string, moduleName: string, abilityName: string): Promise<[image.PixelMap](js-apis-image.md#pixelmap7)>; - -Obtains the ability icon based on the given bundle name, module name, and ability name. This API uses a promise to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO - -**System capability**: SystemCapability.BundleManager.BundleFramework.Resource - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------- | -| bundleName | string | Yes | Bundle name. | -| moduleName | string | Yes | Module name. | -| abilityName | string | Yes | Ability name.| - -**Return value** - -| Type | Description | -| ----------------------------------------------------- | ------------------------------------------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the **PixelMap** object of the icon.| - -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - -| ID| Error Message | -| -------- | -------------------------------------- | -| 17700001 | The specified bundleName is not found. | -| 17700002 | The specified moduleName is not found. | -| 17700003 | The specified abilityName is not found. | -| 17700026 | The specified bundle is disabled. | -| 17700029 | The specified ability is disabled. | - -**Example** - -```ts -import bundleManager from '@ohos.bundle.bundleManager'; -import hilog from '@ohos.hilog'; -let bundleName = 'com.example.myapplication'; -let moduleName = 'entry'; -let abilityName = 'EntryAbility'; - -try { - bundleManager.getAbilityIcon(bundleName, moduleName, abilityName).then((data) => { - hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully. Data: %{public}s', JSON.stringify(data)); - }).catch(err => { - hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); - }); -} catch (err) { - hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); -} -``` ### bundleManager.getApplicationInfoSync getApplicationInfoSync(bundleName: string, applicationFlags: number, userId: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); +getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); Synchronously obtains the application information based on the given bundle name, application flags, and user ID. @@ -2786,7 +2675,7 @@ Synchronously obtains the application information based on the given bundle name | ----------- | ------ | ---- | ----------------------------------------------------------| | bundleName | string | Yes | Bundle name. | | applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. | -| userId | number | No | User ID. | +| userId | number | Yes | User ID. | **Return value** @@ -2838,6 +2727,7 @@ try { ### bundleManager.getBundleInfoSync getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag), userId: number): [BundleInfo](js-apis-bundleManager-bundleInfo.md); +getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); Synchronously obtains the bundle information based on the given bundle name, bundle flags, and user ID. diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 35a696a15b0569a7370fd8ec7938e92e2d13fe0d..613913c3635b0f4d4c235e02428faf9a18b9f4b0 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -3,7 +3,6 @@ The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. > **NOTE** -> > - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.commonEventManager](js-apis-commonEventManager.md). > > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -43,7 +42,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r // Callback for common event publication function publishCB(err) { if (err.code) { - console.error("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}`); } else { console.info("publish"); } @@ -85,7 +84,7 @@ let options = { // Callback for common event publication function publishCB(err) { if (err.code) { - console.error("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}`); } else { console.info("publish"); } @@ -121,7 +120,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb // Callback for common event publication function publishCB(err) { if (err.code) { - console.error("publishAsUser failed " + JSON.stringify(err)); + console.error(`publishAsUser failed, code is ${err.code}`); } else { console.info("publishAsUser"); } @@ -161,14 +160,14 @@ Publishes a common event with given attributes to a specific user. This API uses ```ts // Attributes of a common event. let options = { - code: 0, // Initial code of the common event. - data: "initial data";// Initial data of the common event. + code: 0, // Result code of the common event. + data: "initial data",// Result data of the common event. } // Callback for common event publication function publishCB(err) { if (err.code) { - console.error("publishAsUser failed " + JSON.stringify(err)); + console.error(`publishAsUser failed, code is ${err.code}`); } else { console.info("publishAsUser"); } @@ -212,7 +211,7 @@ let subscribeInfo = { // Callback for subscriber creation. function createCB(err, commonEventSubscriber) { if (err.code) { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}`); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -259,7 +258,7 @@ CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; }).catch((err) => { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}`); }); ``` @@ -293,7 +292,7 @@ let subscribeInfo = { // Callback for common event subscription. function subscribeCB(err, data) { if (err.code) { - console.error("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}`); } else { console.info("subscribe " + JSON.stringify(data)); } @@ -302,7 +301,7 @@ function subscribeCB(err, data) { // Callback for subscriber creation. function createCB(err, subscriber) { if (err.code) { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}`); } else { console.info("createSubscriber"); // Subscribe to a common event. @@ -344,7 +343,7 @@ let subscribeInfo = { // Callback for common event subscription. function subscribeCB(err, data) { if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}`); } else { console.info("subscribe " + JSON.stringify(data)); } @@ -353,7 +352,7 @@ function subscribeCB(err, data) { // Callback for subscriber creation. function createCB(err, commonEventSubscriber) { if (err.code) { - console.info("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}`); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -365,7 +364,7 @@ function createCB(err, commonEventSubscriber) { // Callback for common event unsubscription. function unsubscribeCB(err) { if (err.code) { - console.info("unsubscribe failed " + JSON.stringify(err)); + console.error(`unsubscribe failed, code is ${err.code}`); } else { console.info("unsubscribe"); } @@ -404,7 +403,7 @@ let subscriber; // Subscriber object successfully created. // Callback for result code obtaining of an ordered common event. function getCodeCB(err, Code) { if (err.code) { - console.error("getCode failed " + JSON.stringify(err)); + console.error(`getCode failed, code is ${err.code}`); } else { console.info("getCode " + JSON.stringify(Code)); } @@ -436,7 +435,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getCode().then((code) => { console.info("getCode " + JSON.stringify(code)); }).catch((err) => { - console.error("getCode failed " + JSON.stringify(err)); + console.error(`getCode failed, code is ${err.code}`); }); ``` @@ -465,7 +464,7 @@ let subscriber; // Subscriber object successfully created. // Callback for result code setting of an ordered common event. function setCodeCB(err) { if (err.code) { - console.error("setCode failed " + JSON.stringify(err)); + console.error(`setCode failed, code is ${err.code}`); } else { console.info("setCode"); } @@ -503,7 +502,7 @@ let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { console.info("setCode"); }).catch((err) => { - console.error("setCode failed " + JSON.stringify(err)); + console.error(`setCode failed, code is ${err.code}`); }); ``` @@ -531,7 +530,7 @@ let subscriber; // Subscriber object successfully created. // Callback for result data obtaining of an ordered common event. function getDataCB(err, data) { if (err.code) { - console.error("getData failed " + JSON.stringify(err)); + console.error(`getData failed, code is ${err.code}`); } else { console.info("getData " + JSON.stringify(data)); } @@ -564,7 +563,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getData().then((data) => { console.info("getData " + JSON.stringify(data)); }).catch((err) => { - console.error("getData failed " + JSON.stringify(err)); + console.error(`getData failed, code is ${err.code}`); }); ``` @@ -593,7 +592,7 @@ let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event function setDataCB(err) { if (err.code) { - console.error("setData failed " + JSON.stringify(err)); + console.error(`sendData failed, code is ${err.code}`); } else { console.info("setData"); } @@ -631,7 +630,7 @@ let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { console.info("setData"); }).catch((err) => { - console.error("setData failed " + JSON.stringify(err)); + console.error(`setData failed, code is ${err.code}`); }); ``` @@ -661,7 +660,7 @@ let subscriber; // Subscriber object successfully created. // Callback for result code and result data setting of an ordered common event. function setCodeDataCB(err) { if (err.code) { - console.error("setCodeAndData failed " + JSON.stringify(err)); + console.error(`setCodeAndData failed, code is ${err.code}`); } else { console.info("setCodeDataCallback"); } @@ -701,7 +700,7 @@ let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); }).catch((err) => { - console.info("setCodeAndData failed " + JSON.stringify(err)); + console.error(`setCodeAndData failed, code is ${err.code}`); }); ``` @@ -729,7 +728,7 @@ let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. function isOrderedCB(err, isOrdered) { if (err.code) { - console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + console.error(`isOrderedCommonEvent failed, code is ${err.code}`); } else { console.info("isOrdered " + JSON.stringify(isOrdered)); } @@ -761,7 +760,7 @@ let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); }).catch((err) => { - console.error("isOrdered failed " + JSON.stringify(err)); + console.error(`isOrderedCommonEvent failed, code is ${err.code}`); }); ``` @@ -789,7 +788,7 @@ let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. function isStickyCB(err, isSticky) { if (err.code) { - console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + console.error(`isStickyCommonEvent failed, code is ${err.code}`); } else { console.info("isSticky " + JSON.stringify(isSticky)); } @@ -821,7 +820,7 @@ let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); }).catch((err) => { - console.error("isSticky failed " + JSON.stringify(err)); + console.error(`isSticky failed, code is ${err.code}`); }); ``` @@ -849,7 +848,7 @@ let subscriber; // Subscriber object successfully created. // Callback for common event aborting. function abortCB(err) { if (err.code) { - console.error("abortCommonEvent failed " + JSON.stringify(err)); + console.error(`abortCommonEvent failed, code is ${err.code}`); } else { console.info("abortCommonEvent"); } @@ -882,7 +881,7 @@ let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); }).catch((err) => { - console.error("abortCommonEvent failed " + JSON.stringify(err)); + console.error(`abortCommonEvent failed, code is ${err.code}`); }); ``` @@ -910,7 +909,7 @@ let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. function clearAbortCB(err) { if (err.code) { - console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`clearAbortCommonEvent failed, code is ${err.code}`); } else { console.info("clearAbortCommonEvent"); } @@ -943,7 +942,7 @@ let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); }).catch((err) => { - console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`clearAbortCommonEvent failed, code is ${err.code}`); }); ``` @@ -971,7 +970,7 @@ let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. function getAbortCB(err, abortEvent) { if (err.code) { - console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`getAbortCommonEvent failed, code is ${err.code}`); } else { console.info("abortEvent " + abortEvent) } @@ -1004,7 +1003,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getAbortCommonEvent().then((abortCommonEvent) => { console.info("abortCommonEvent " + JSON.stringify(abortCommonEvent)); }).catch((err) => { - console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`getAbortCommonEvent failed, code is ${err.code}`); }); ``` @@ -1032,7 +1031,7 @@ let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. function getCB(err, subscribeInfo) { if (err.code) { - console.error("getSubscribeInfo failed " + JSON.stringify(err)); + console.error(`getSubscribeInfo failed, code is ${err.code}`); } else { console.info("SubscribeInfo " + JSON.stringify(subscribeInfo)); } @@ -1065,7 +1064,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getSubscribeInfo().then((subscribeInfo) => { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); }).catch((err) => { - console.error("getSubscribeInfo failed " + JSON.stringify(err)); + console.error(`getSubscribeInfo failed, code is ${err.code}`); }); ``` @@ -1088,12 +1087,12 @@ Finishes this common event. This API takes effect only for ordered common events **Example** ```ts -let subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. function finishCB(err) { if (err.code) { - console.error("finishCommonEvent failed " + JSON.stringify(err)); + console.error(`finishCommonEvent failed, code is ${err.code}`); } else { console.info("FinishCommonEvent"); } @@ -1126,7 +1125,7 @@ let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); }).catch((err) => { - console.error("finishCommonEvent failed " + JSON.stringify(err)); + console.error(`finishCommonEvent failed, code is ${err.code}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index 982f0d103e100d14712db5b16e0ae98552869e6e..bdcc1af2a479d300303a8d9f851f07c81c3e7d5a 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -45,7 +45,7 @@ For details about the error codes, see [Event Error Codes](../errorcodes/errorco // Callback for common event publication function publishCB(err) { if (err) { - console.error("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publish"); } @@ -55,7 +55,7 @@ function publishCB(err) { try { CommonEventManager.publish("event", publishCB); } catch(err) { - console.error('publish failed, catch error' + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -94,7 +94,7 @@ let options = { // Callback for common event publication function publishCB(err) { if (err) { - console.error("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publish"); } @@ -104,7 +104,7 @@ function publishCB(err) { try { CommonEventManager.publish("event", options, publishCB); } catch (err) { - console.error('publish failed, catch error' + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -138,7 +138,7 @@ For details about the error codes, see [Event Error Codes](../errorcodes/errorco // Callback for common event publication function publishCB(err) { if (err) { - console.error("publishAsUser failed " + JSON.stringify(err)); + console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publishAsUser"); } @@ -151,7 +151,7 @@ let userId = 100; try { CommonEventManager.publishAsUser("event", userId, publishCB); } catch (err) { - console.error('publishAsUser failed, catch error' + JSON.stringify(err)); + console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -193,7 +193,7 @@ let options = { // Callback for common event publication. function publishCB(err) { if (err) { - console.error("publishAsUser failed " + JSON.stringify(err)); + console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publishAsUser"); } @@ -206,7 +206,7 @@ let userId = 100; try { CommonEventManager.publishAsUser("event", userId, options, publishCB); } catch (err) { - console.error('publishAsUser failed, catch error' + JSON.stringify(err)); + console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -244,7 +244,7 @@ function createCB(err, commonEventSubscriber) { console.info("createSubscriber"); subscriber = commonEventSubscriber; } else { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } } @@ -252,7 +252,7 @@ function createCB(err, commonEventSubscriber) { try { CommonEventManager.createSubscriber(subscribeInfo, createCB); } catch (err) { - console.error('createSubscriber failed, catch error' + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -292,7 +292,7 @@ CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) console.info("createSubscriber"); subscriber = commonEventSubscriber; }).catch((err) => { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -328,7 +328,7 @@ let subscribeInfo = { // Callback for common event subscription. function SubscribeCB(err, data) { if (err.code) { - console.error("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribe "); } @@ -342,10 +342,10 @@ function createCB(err, subscriber) { try { CommonEventManager.subscribe(subscriber, SubscribeCB); } catch (err) { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } } else { - console.error("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } } @@ -353,7 +353,7 @@ function createCB(err, subscriber) { try { CommonEventManager.createSubscriber(subscribeInfo, createCB); } catch (err) { - console.error('createSubscriber failed, catch error' + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -385,7 +385,7 @@ let subscribeInfo = { // Callback for common event subscription. function subscribeCB(err, data) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribe"); } @@ -393,21 +393,21 @@ function subscribeCB(err, data) { // Callback for subscriber creation. function createCB(err, subscriber) { if (err) { - console.info("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } else { console.info("createSubscriber"); // Subscribe to a common event. try { CommonEventManager.subscribe(subscriber, subscribeCB); } catch(err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } } } // Callback for common event unsubscription. function unsubscribeCB(err) { if (err) { - console.info("unsubscribe failed " + JSON.stringify(err)); + console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("unsubscribe"); } @@ -416,14 +416,14 @@ function unsubscribeCB(err) { try { CommonEventManager.createSubscriber(subscribeInfo, createCB); } catch (err) { - console.info("createSubscriber failed " + JSON.stringify(err)); + console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); } // Unsubscribe from the common event. try { CommonEventManager.unsubscribe(subscriber, unsubscribeCB); } catch (err) { - console.info("unsubscribe failed " + JSON.stringify(err)); + console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -453,7 +453,7 @@ let subscriber; // Subscriber object successfully created. // Callback for code obtaining of an ordered common event. function getCodeCB(err, code) { if (err.code) { - console.error("getCode failed " + JSON.stringify(err)); + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getCode " + JSON.stringify(code)); } @@ -485,7 +485,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getCode().then((code) => { console.info("getCode " + JSON.stringify(code)); }).catch((err) => { - console.error("getCode failed " + JSON.stringify(err)); + console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -514,7 +514,7 @@ let subscriber; // Subscriber object successfully created. // Callback for code setting of an ordered common event. function setCodeCB(err) { if (err.code) { - console.error("setCode failed " + JSON.stringify(err)); + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setCode"); } @@ -552,7 +552,7 @@ let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { console.info("setCode"); }).catch((err) => { - console.error("setCode failed " + JSON.stringify(err)); + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -580,7 +580,7 @@ let subscriber; // Subscriber object successfully created. // Callback for data obtaining of an ordered common event. function getDataCB(err, data) { if (err.code) { - console.error("getData failed " + JSON.stringify(err)); + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getData " + JSON.stringify(data)); } @@ -612,7 +612,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getData().then((data) => { console.info("getData " + JSON.stringify(data)); }).catch((err) => { - console.error("getData failed " + JSON.stringify(err)); + console.error(`getData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -639,7 +639,7 @@ let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event function setDataCB(err) { if (err.code) { - console.error("setData failed " + JSON.stringify(err)); + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setData"); } @@ -677,7 +677,7 @@ let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { console.info("setData"); }).catch((err) => { - console.error("setData failed " + JSON.stringify(err)); + console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -707,7 +707,7 @@ let subscriber; // Subscriber object successfully created. // Callback for code and data setting of an ordered common event. function setCodeDataCB(err) { if (err.code) { - console.error("setCodeAndData failed " + JSON.stringify(err)); + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setCodeDataCallback"); } @@ -746,7 +746,7 @@ let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); }).catch((err) => { - console.info("setCodeAndData failed " + JSON.stringify(err)); + console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -774,7 +774,7 @@ let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. function isOrderedCB(err, isOrdered) { if (err.code) { - console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isOrdered " + JSON.stringify(isOrdered)); } @@ -790,7 +790,7 @@ isOrderedCommonEvent(): Promise Checks whether this common event is an ordered one. This API uses a promise to return the result. - **System capability**: SystemCapability.Notification.CommonEvent +**System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -806,7 +806,7 @@ let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); }).catch((err) => { - console.error("isOrdered failed " + JSON.stringify(err)); + console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -816,7 +816,7 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { isStickyCommonEvent(callback: AsyncCallback): void ``` -Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -834,7 +834,7 @@ let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. function isStickyCB(err, isSticky) { if (err.code) { - console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isSticky " + JSON.stringify(isSticky)); } @@ -866,7 +866,7 @@ let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); }).catch((err) => { - console.error("isSticky failed " + JSON.stringify(err)); + console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -894,7 +894,7 @@ let subscriber; // Subscriber object successfully created. // Callback for common event aborting. function abortCB(err) { if (err.code) { - console.error("abortCommonEvent failed " + JSON.stringify(err)); + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { console.info("abortCommonEvent"); } @@ -926,7 +926,7 @@ let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); }).catch((err) => { - console.error("abortCommonEvent failed " + JSON.stringify(err)); + console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -954,7 +954,7 @@ let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. function clearAbortCB(err) { if (err.code) { - console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { console.info("clearAbortCommonEvent"); } @@ -986,7 +986,7 @@ let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); }).catch((err) => { - console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -1014,7 +1014,7 @@ let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. function getAbortCB(err, abortEvent) { if (err.code) { - console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { console.info("abortCommonEvent " + abortEvent) } @@ -1046,7 +1046,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getAbortCommonEvent().then((abortEvent) => { console.info("abortCommonEvent " + JSON.stringify(abortEvent)); }).catch((err) => { - console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -1074,7 +1074,7 @@ let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. function getCB(err, subscribeInfo) { if (err.code) { - console.error("getSubscribeInfo failed " + JSON.stringify(err)); + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); } @@ -1106,7 +1106,7 @@ let subscriber; // Subscriber object successfully created. subscriber.getSubscribeInfo().then((subscribeInfo) => { console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); }).catch((err) => { - console.error("getSubscribeInfo failed " + JSON.stringify(err)); + console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -1134,11 +1134,11 @@ let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. function finishCB(err) { if (err.code) { - console.error("finishCommonEvent failed " + JSON.stringify(err)); + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); } else { console.info("FinishCommonEvent"); } -} + subscriber.finishCommonEvent(finishCB); ``` @@ -1166,7 +1166,7 @@ let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); }).catch((err) => { - console.error("finishCommonEvent failed " + JSON.stringify(err)); + console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); }); ``` 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 579dd277e83b8d7a20f55dc21542099e690ec470..1b9948db2d3decf6b7d21d17cb74b53450ae3865 100644 --- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -15,10 +15,10 @@ The **relationalStore** module provides the following functions: ## Modules to Import ```js -import data_rdb from '@ohos.data.relationalStore'; +import relationalStore from '@ohos.data.relationalStore' ``` -## data_rdb.getRdbStore +## relationalStore.getRdbStore getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void @@ -51,20 +51,23 @@ FA model: import featureAbility from '@ohos.ability.featureAbility' +var store; + // Obtain the context. -let context = featureAbility.getContext() +let context = featureAbility.getContext(); const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} - -data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { - if (err) { - console.info("Failed to get RdbStore, err: " + err) - return - } - console.log("Got RdbStore successfully.") + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; + +relationalStore.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + if (err) { + console.error(`Get RdbStore failed, err: ${err}`); + return; + } + console.info(`Get RdbStore successfully.`); }) ``` @@ -74,24 +77,26 @@ Stage model: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + onWindowStageCreate(windowStage) { + var store; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 + }; - data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { - if (err) { - console.info("Failed to get RdbStore, err: " + err) - return - } - console.log("Got RdbStore successfully.") - }) - } + relationalStore.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) { + store = rdbStore; + if (err) { + console.error(`Get RdbStore failed, err: ${err}`); + return; + } + console.info(`Get RdbStore successfully.`); + }) + } } ``` -## data_rdb.getRdbStore +## relationalStore.getRdbStore getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> @@ -128,19 +133,22 @@ FA model: ```js import featureAbility from '@ohos.ability.featureAbility' +var store; + // Obtain the context. -let context = featureAbility.getContext() +let context = featureAbility.getContext(); const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 -} + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; -let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +let promise = relationalStore.getRdbStore(context, STORE_CONFIG); promise.then(async (rdbStore) => { - console.log("Got RdbStore successfully.") + store = rdbStore; + console.info(`Get RdbStore successfully.`); }).catch((err) => { - console.log("Failed to get RdbStore, err: " + err) + console.error(`Get RdbStore failed, err: ${err}`); }) ``` @@ -150,23 +158,25 @@ Stage model: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - const STORE_CONFIG = { - name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1 - } + onWindowStageCreate(windowStage) { + var store; + const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 + }; - let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG); - promise.then(async (rdbStore) => { - console.log("Got RdbStore successfully.") - }).catch((err) => { - console.log("Failed to get RdbStore, err: " + err) - }) - } + let promise = relationalStore.getRdbStore(this.context, STORE_CONFIG); + promise.then(async (rdbStore) => { + store = rdbStore; + console.info(`Get RdbStore successfully.`) + }).catch((err) => { + console.error(`Get RdbStore failed, err: ${err}`); + }) + } } ``` -## data_rdb.deleteRdbStore +## relationalStore.deleteRdbStore deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void @@ -200,12 +210,12 @@ import featureAbility from '@ohos.ability.featureAbility' // Obtain the context. let context = featureAbility.getContext() -data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { - if (err) { - console.info("Failed to delete RdbStore, err: " + err) - return - } - console.log("Deleted RdbStore successfully.") +relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.error(`Delete RdbStore failed, err: ${err}`); + return; + } + console.info(`Delete RdbStore successfully.`); }) ``` @@ -215,19 +225,19 @@ Stage model: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) { - if (err) { - console.info("Failed to delete RdbStore, err: " + err) - return - } - console.log("Deleted RdbStore successfully.") - }) - } + onWindowStageCreate(windowStage){ + relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) { + if (err) { + console.error(`Delete RdbStore failed, err: ${err}`); + return; + } + console.info(`Delete RdbStore successfully.`); + }) + } } ``` -## data_rdb.deleteRdbStore +## relationalStore.deleteRdbStore deleteRdbStore(context: Context, name: string): Promise<void> @@ -264,13 +274,13 @@ FA model: import featureAbility from '@ohos.ability.featureAbility' // Obtain the context. -let context = featureAbility.getContext() +let context = featureAbility.getContext(); -let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +let promise = relationalStore.deleteRdbStore(context, "RdbTest.db"); promise.then(()=>{ - console.log("Deleted RdbStore successfully.") + console.info(`Delete RdbStore successfully.`); }).catch((err) => { - console.info("Failed to delete RdbStore, err: " + err) + console.error(`Delete RdbStore failed, err: ${err}`); }) ``` @@ -280,14 +290,14 @@ Stage model: import UIAbility from '@ohos.app.ability.UIAbility' class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage){ - let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") - promise.then(()=>{ - console.log("Deleted RdbStore successfully.") - }).catch((err) => { - console.info("Failed to delete RdbStore, err: " + err) - }) - } + onWindowStageCreate(windowStage){ + let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); + promise.then(()=>{ + console.info(`Delete RdbStore successfully.`); + }).catch((err) => { + console.error(`Delete RdbStore failed, err: ${err}`); + }) + } } ``` @@ -397,7 +407,7 @@ A constructor used to create an **RdbPredicates** object. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); ``` ### inDevices @@ -424,8 +434,8 @@ Sets an **RdbPredicates** to specify the remote devices to connect on the networ **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inDevices(['12345678abcde']) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.inDevices(['12345678abcde']); ``` ### inAllDevices @@ -446,8 +456,8 @@ Sets an **RdbPredicates** to specify all remote devices on the network to connec **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inAllDevices() +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.inAllDevices(); ``` ### equalTo @@ -475,8 +485,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "lisi"); ``` @@ -505,8 +515,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notEqualTo("NAME", "lisi") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notEqualTo("NAME", "lisi"); ``` @@ -528,7 +538,7 @@ Adds a left parenthesis to the **RdbPredicates**. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) @@ -554,7 +564,7 @@ Adds a right parenthesis to the **RdbPredicates**. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) @@ -580,7 +590,7 @@ Adds the OR condition to the **RdbPredicates**. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") @@ -603,7 +613,7 @@ Adds the AND condition to the **RdbPredicates**. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) @@ -633,8 +643,8 @@ Sets an **RdbPredicates** to match a string containing the specified value. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.contains("NAME", "os") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.contains("NAME", "os"); ``` ### beginsWith @@ -661,8 +671,8 @@ Sets an **RdbPredicates** to match a string that starts with the specified value **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.beginsWith("NAME", "os") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.beginsWith("NAME", "os"); ``` ### endsWith @@ -689,8 +699,8 @@ Sets an **RdbPredicates** to match a string that ends with the specified value. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.endsWith("NAME", "se") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.endsWith("NAME", "se"); ``` ### isNull @@ -716,8 +726,8 @@ Sets an **RdbPredicates** to match the field whose value is null. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNull("NAME") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNull("NAME"); ``` ### isNotNull @@ -743,8 +753,8 @@ Sets an **RdbPredicates** to match the field whose value is not null. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNotNull("NAME") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNotNull("NAME"); ``` ### like @@ -771,8 +781,8 @@ Sets an **RdbPredicates** to match a string that is similar to the specified val **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.like("NAME", "%os%") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.like("NAME", "%os%"); ``` ### glob @@ -799,8 +809,8 @@ Sets an **RdbPredicates** to match the specified string. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.glob("NAME", "?h*g") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.glob("NAME", "?h*g"); ``` ### between @@ -828,8 +838,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.between("AGE", 10, 50) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.between("AGE", 10, 50); ``` ### notBetween @@ -857,8 +867,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notBetween("AGE", 10, 50) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notBetween("AGE", 10, 50); ``` ### greaterThan @@ -885,8 +895,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThan("AGE", 18) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.greaterThan("AGE", 18); ``` ### lessThan @@ -913,8 +923,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThan("AGE", 20) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThan("AGE", 20); ``` ### greaterThanOrEqualTo @@ -941,8 +951,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThanOrEqualTo("AGE", 18) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.greaterThanOrEqualTo("AGE", 18); ``` ### lessThanOrEqualTo @@ -969,8 +979,8 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThanOrEqualTo("AGE", 20) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThanOrEqualTo("AGE", 20); ``` ### orderByAsc @@ -996,8 +1006,8 @@ Sets an **RdbPredicates** to match the column with values sorted in ascending or **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByAsc("NAME") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByAsc("NAME"); ``` ### orderByDesc @@ -1023,8 +1033,8 @@ Sets an **RdbPredicates** to match the column with values sorted in descending o **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByDesc("AGE") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByDesc("AGE"); ``` ### distinct @@ -1044,8 +1054,8 @@ Sets an **RdbPredicates** to filter out duplicate records. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").distinct() +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").distinct(); ``` ### limitAs @@ -1071,8 +1081,8 @@ Sets an **RdbPredicates** to specify the maximum number of records. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").limitAs(3) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").limitAs(3); ``` ### offsetAs @@ -1098,8 +1108,8 @@ Sets an **RdbPredicates** to specify the start position of the returned result. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").offsetAs(3) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").offsetAs(3); ``` ### groupBy @@ -1125,8 +1135,8 @@ Sets an **RdbPredicates** to group rows that have the same value into summary ro **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.groupBy(["AGE", "NAME"]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.groupBy(["AGE", "NAME"]); ``` ### indexedBy @@ -1153,8 +1163,8 @@ Sets an **RdbPredicates** object to specify the index column. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.indexedBy("SALARY_INDEX") +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.indexedBy("SALARY_INDEX"); ``` ### in @@ -1181,8 +1191,8 @@ Sets an **RdbPredicates** to match the field with data type **Array<ValueTyp **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.in("AGE", [18, 20]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.in("AGE", [18, 20]); ``` ### notIn @@ -1209,8 +1219,8 @@ Sets an **RdbPredicates** to match the field with data type **Array<ValueTyp **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notIn("NAME", ["Lisa", "Rose"]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notIn("NAME", ["Lisa", "Rose"]); ``` ## RdbStore @@ -1231,9 +1241,9 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the ```js // Set the RDB store version. -rdbStore.version = 3 +store.version = 3; // Obtain the RDB store version. -console.info("Get RdbStore version is " + rdbStore.version) +console.info(`RdbStore version is ${store.version}`); ``` ### insert @@ -1256,17 +1266,17 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { - if (status) { - console.log("Failed to insert data"); - return; - } - console.log("Inserted data successfully, rowId = " + rowId); + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +store.insert("EMPLOYEE", valueBucket, function (err, rowId) { + if (err) { + console.error(`Insert is failed, err: ${err}`); + return; + } + console.info(`Insert is successful, rowId = ${rowId}`); }) ``` @@ -1291,17 +1301,17 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (status, rowId) { - if (status) { - console.log("Failed to insert data"); - return; - } - console.log("Inserted data successfully, rowId = " + rowId); + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rowId) { + if (err) { + console.error(`Insert is failed, err: ${err}`); + return; + } + console.info(`Insert is successful, rowId = ${rowId}`); }) ``` @@ -1330,16 +1340,16 @@ Inserts a row of data into a table. This API uses a promise to return the result ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let promise = rdbStore.insert("EMPLOYEE", valueBucket) + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let promise = store.insert("EMPLOYEE", valueBucket); promise.then((rowId) => { - console.log("Inserted data successfully, rowId = " + rowId); -}).catch((status) => { - console.log("Failed to insert data"); + console.info(`Insert is successful, rowId = ${rowId}`); +}).catch((err) => { + console.error(`Insert is failed, err: ${err}`); }) ``` @@ -1369,16 +1379,16 @@ Inserts a row of data into a table. This API uses a promise to return the result ```js const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let promise = rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let promise = store.insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); promise.then((rowId) => { - console.log("Inserted data successfully, rowId = " + rowId); -}).catch((status) => { - console.log("Failed to insert data"); + console.info(`Insert is successful, rowId = ${rowId}`); +}).catch((err) => { + console.error(`Insert is failed, err: ${err}`); }) ``` @@ -1402,31 +1412,31 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur ```js const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) -} + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +}; const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) -} + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +}; const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) -} + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +}; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { - if (status) { - console.log("batchInsert is failed, status = " + status); - return; - } - console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +store.batchInsert("EMPLOYEE", valueBuckets, function(err, insertNum) { + if (err) { + console.error(`batchInsert is failed, err: ${err}`); + return; + } + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); }) ``` @@ -1455,30 +1465,30 @@ Batch inserts data into a table. This API uses a promise to return the result. ```js const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) -} + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +}; const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) -} + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +}; const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) -} + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +}; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +let promise = store.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { - console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); -}).catch((status) => { - console.log("batchInsert is failed, status = " + status); + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); +}).catch((err) => { + console.error(`batchInsert is failed, err: ${err}`); }) ``` @@ -1502,19 +1512,19 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, rows) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + rows) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +store.update(valueBucket, predicates, function (err, rows) { + if (err) { + console.error(`Updated failed, err: ${err}`); + return; + } + console.info(`Updated row count: ${rows}`); }) ``` @@ -1539,19 +1549,19 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + rows) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +store.update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { + if (err) { + console.error(`Updated failed, err: ${err}`); + return; + } + console.info(`Updated row count: ${rows}`); }) ``` @@ -1580,18 +1590,18 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update(valueBucket, predicates) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +let promise = store.update(valueBucket, predicates); promise.then(async (rows) => { - console.log("Updated row count: " + rows) + console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.info("Failed to update data, err: " + err) + console.error(`Updated failed, err: ${err}`); }) ``` @@ -1621,18 +1631,18 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr ```js const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +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) => { - console.log("Updated row count: " + rows) + console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.info("Failed to update data, err: " + err) + console.error(`Updated failed, err: ${err}`); }) ``` @@ -1664,15 +1674,15 @@ const valueBucket = { "AGE": 22, "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + rows) +}; +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +store.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { + if (err) { + console.error(`Updated failed, err: ${err}`); + return; + } + console.info(`Updated row count: ${rows}`); }) ``` @@ -1705,18 +1715,18 @@ Updates data based on the specified **DataSharePredicates** object. This API use ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +}; +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +let promise = store.update("EMPLOYEE", valueBucket, predicates); promise.then(async (rows) => { - console.log("Updated row count: " + rows) + console.info(`Updated row count: ${rows}`); }).catch((err) => { - console.info("Failed to update data, err: " + err) + console.error(`Updated failed, err: ${err}`); }) ``` @@ -1738,14 +1748,14 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.delete(predicates, function (err, rows) { - if (err) { - console.info("Failed to delete data, err: " + err) - return - } - console.log("Deleted rows: " + rows) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +store.delete(predicates, function (err, rows) { + if (err) { + console.error(`Delete failed, err: ${err}`); + return; + } + console.info(`Delete rows: ${rows}`); }) ``` @@ -1772,13 +1782,13 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete(predicates) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa"); +let promise = store.delete(predicates); promise.then((rows) => { - console.log("Deleted rows: " + rows) + console.info(`Delete rows: ${rows}`); }).catch((err) => { - console.info("Failed to delete data, err: " + err) + console.error(`Delete failed, err: ${err}`); }) ``` @@ -1804,14 +1814,14 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { - if (err) { - console.info("Failed to delete data, err: " + err) - return - } - console.log("Deleted rows: " + rows) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +store.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.error(`Delete failed, err: ${err}`); + return; + } + console.info(`Delete rows: ${rows}`); }) ``` @@ -1842,13 +1852,13 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Lisa"); +let promise = store.delete("EMPLOYEE", predicates); promise.then((rows) => { - console.log("Deleted rows: " + rows) + console.info(`Delete rows: ${rows}`); }).catch((err) => { - console.info("Failed to delete data, err: " + err) + console.error(`Delete failed, err: ${err}`); }) ``` @@ -1871,15 +1881,15 @@ Queries data from the RDB store based on specified conditions. This API uses an **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose") -rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Failed to query data, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose"); +store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.error(`Query failed, err: ${err}`); + return; + } + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }) ``` @@ -1907,14 +1917,14 @@ Queries data from the RDB store based on specified conditions. This API uses a p **Example** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Failed to query data, err: " + err) + console.error(`Query failed, err: ${err}`); }) ``` @@ -1941,15 +1951,15 @@ Queries data from the RDB store based on specified conditions. This API uses an ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Failed to query data, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Rose"); +store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.error(`Query failed, err: ${err}`); + return; + } + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }) ``` @@ -1981,14 +1991,14 @@ Queries data from the RDB store based on specified conditions. This API uses a p ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +let predicates = new dataSharePredicates.DataSharePredicates(); +predicates.equalTo("NAME", "Rose"); +let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Failed to query data, err: " + err) + console.error(`Query failed, err: ${err}`); }) ``` @@ -2013,17 +2023,18 @@ Queries data from the RDB store of a remote device based on specified conditions **Example** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ +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.info("Failed to remoteQuery, err: " + err) - return + console.error(`Failed to remoteQuery, err: ${err}`); + return; } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); + } +) ``` ### remoteQuery @@ -2052,14 +2063,14 @@ Queries data from the RDB store of a remote device based on specified conditions **Example** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +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) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) + console.error(`Failed to remoteQuery, err: ${err}`); }) ``` @@ -2082,13 +2093,13 @@ Queries data using the specified SQL statement. This API uses an asynchronous ca **Example** ```js -rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { - if (err) { - console.info("Failed to query data, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { + if (err) { + console.error(`Query failed, err: ${err}`); + return; + } + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }) ``` @@ -2116,12 +2127,12 @@ Queries data using the specified SQL statement. This API uses a promise to retur **Example** ```js -let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']); promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.info(`ResultSet column names: ${resultSet.columnNames}`); + console.info(`ResultSet column count: ${resultSet.columnCount}`); }).catch((err) => { - console.info("Failed to query data, err: " + err) + console.error(`Query failed, err: ${err}`); }) ``` @@ -2145,12 +2156,12 @@ Executes an SQL statement that contains specified arguments but returns no value ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" -rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { - if (err) { - console.info("Failed to execute SQL, err: " + err) - return - } - console.info('Create table done.') +store.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.error(`ExecuteSql failed, err: ${err}`); + return; + } + console.info(`Create table done.`); }) ``` @@ -2179,11 +2190,11 @@ Executes an SQL statement that contains specified arguments but returns no value ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" -let promise = rdbStore.executeSql(SQL_CREATE_TABLE) +let promise = store.executeSql(SQL_CREATE_TABLE); promise.then(() => { - console.info('Create table done.') + console.info(`Create table done.`); }).catch((err) => { - console.info("Failed to execute SQL, err: " + err) + console.error(`ExecuteSql failed, err: ${err}`); }) ``` @@ -2199,19 +2210,25 @@ Starts the transaction before executing an SQL statement. ```js import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { - rdbStore.beginTransaction() - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() +let context = featureAbility.getContext(); +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; +relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { + if (err) { + console.error(`GetRdbStore failed, err: ${err}`); + return; + } + store.beginTransaction(); + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + }; + await store.insert("test", valueBucket); + store.commit(); }) ``` @@ -2227,19 +2244,25 @@ Commits the executed SQL statements. ```js import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { - rdbStore.beginTransaction() - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() +let context = featureAbility.getContext(); +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; +relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { + if (err) { + console.error(`GetRdbStore failed, err: ${err}`); + return; + } + store.beginTransaction(); + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + }; + await store.insert("test", valueBucket); + store.commit(); }) ``` @@ -2255,24 +2278,31 @@ Rolls back the SQL statements that have been executed. ```js import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { - try { - rdbStore.beginTransaction() - const valueBucket = { - "id": 1, - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() - } catch (e) { - rdbStore.rollBack() - } +let context = featureAbility.getContext(); +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S1 +}; +relationalStore.getRdbStore(context, STORE_CONFIG, async function (err, store) { + if (err) { + console.error(`GetRdbStore failed, err: ${err}`); + return; + } + try { + store.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + }; + await store.insert("test", valueBucket); + store.commit(); + } catch (err) { + console.error(`Transaction failed, err: ${err}`); + store.rollBack(); + } }) ``` @@ -2294,12 +2324,12 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu **Example** ```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Backup failed, err: ' + err) - return - } - console.info('Backup success.') +store.backup("dbBackup.db", function(err) { + if (err) { + console.error(`Backup failed, err: ${err}`); + return; + } + console.info(`Backup success.`); }) ``` @@ -2326,11 +2356,11 @@ Backs up an RDB store. This API uses a promise to return the result. **Example** ```js -let promiseBackup = rdbStore.backup("dbBackup.db") +let promiseBackup = store.backup("dbBackup.db"); promiseBackup.then(()=>{ - console.info('Backup success.') + console.info(`Backup success.`); }).catch((err)=>{ - console.info('Backup failed, err: ' + err) + console.error(`Backup failed, err: ${err}`); }) ``` @@ -2352,12 +2382,12 @@ Restores an RDB store from a backup file. This API uses an asynchronous callback **Example** ```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Restore failed, err: ' + err) - return - } - console.info('Restore success.') +store.restore("dbBackup.db", function(err) { + if (err) { + console.error(`Restore failed, err: ${err}`); + return; + } + console.info(`Restore success.`); }) ``` @@ -2384,11 +2414,11 @@ Restores an RDB store from a backup file. This API uses a promise to return the **Example** ```js -let promiseRestore = rdbStore.restore("dbBackup.db") +let promiseRestore = store.restore("dbBackup.db"); promiseRestore.then(()=>{ - console.info('Restore success.') + console.info(`Restore success.`); }).catch((err)=>{ - console.info('Restore failed, err: ' + err) + console.error(`Restore failed, err: ${err}`); }) ``` @@ -2412,12 +2442,12 @@ Sets distributed tables. This API uses an asynchronous callback to return the re **Example** ```js -rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { - if (err) { - console.info('Failed to set distributed tables, err: ' + err) - return - } - console.info('Set distributed tables successfully.') +store.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.error(`SetDistributedTables failed, err: ${err}`); + return; + } + console.info(`SetDistributedTables successfully.`); }) ``` @@ -2446,11 +2476,11 @@ Sets distributed tables. This API uses a promise to return the result. **Example** ```js -let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) +let promise = store.setDistributedTables(["EMPLOYEE"]); promise.then(() => { - console.info("Set distributed tables successfully.") + console.info(`SetDistributedTables successfully.`); }).catch((err) => { - console.info("Failed to set distributed tables, err: " + err) + console.error(`SetDistributedTables failed, err: ${err}`); }) ``` @@ -2475,12 +2505,12 @@ Obtains the distributed table name for a remote device based on the local table **Example** ```js -rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { +store.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { if (err) { - console.info('Failed to obtain DistributedTableName, err: ' + err) - return + console.error(`ObtainDistributedTableName failed, err: ${err}`); + return; } - console.info('Obtained distributed table name successfully, tableName=.' + tableName) + console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }) ``` @@ -2510,11 +2540,11 @@ Obtains the distributed table name for a remote device based on the local table **Example** ```js -let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +let promise = store.obtainDistributedTableName("12345678abcde", "EMPLOYEE"); promise.then((tableName) => { - console.info('Obtained distributed table name successfully, tableName= ' + tableName) + console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }).catch((err) => { - console.info('Failed to obtain DistributedTableName, err: ' + err) + console.error(`ObtainDistributedTableName failed, err: ${err}`); }) ``` @@ -2539,17 +2569,17 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret **Example** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.inDevices(['12345678abcde']) -rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { - if (err) { - console.log('Sync failed, err: ' + err) - return - } - console.log('Sync done.') - for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + ' status=' + result[i][1]) - } +let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); +predicates.inDevices(['12345678abcde']); +store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { + if (err) { + console.error(`Sync failed, err: ${err}`); + return; + } + console.info(`Sync done.`); + for (let i = 0; i < result.length; i++) { + console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); + } }) ``` @@ -2579,16 +2609,16 @@ Synchronizes data between devices. This API uses a promise to return the result. **Example** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.inDevices(['12345678abcde']) -let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) +let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); +predicates.inDevices(['12345678abcde']); +let promise = store.sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates); promise.then((resultSet) =>{ - console.log('Sync done.') - for (let i = 0; i < resultSet.length; i++) { - console.log('device=' + resultSet[i][0] + ' status=' + resultSet[i][1]) - } + console.info(`Sync done.`); + for (let i = 0; i < resultSet.length; i++) { + console.info(`device= ${result[i][0]}, status= ${result[i][1]}`); + } }).catch((err) => { - console.log('Sync failed') + console.error(`Sync failed, err: ${err}`); }) ``` @@ -2604,22 +2634,22 @@ Registers an observer for this RDB store. When the data in the RDB store changes | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------- | -| event | string | Yes | The value is'dataChange', which indicates a data change event. | +| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. | | type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.| -| observer | Callback<Array<string>> | Yes | Observer that listens for the data changes in the RDB store. | +| observer | Callback<Array<string>> | Yes | Callback invoked to return the data change event. | **Example** ```js function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + devices[i] + ' data changed') - } + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } } try { - rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + store.on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.log('Failed to register observer') + console.error(`Register observer failed, err: ${err}`); } ``` @@ -2635,22 +2665,22 @@ Unregisters the observer of the specified type from the RDB store. This API uses | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------------------ | -| event | string | Yes | The value is'dataChange', which indicates a data change event. | -| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register. | -| observer | Callback<Array<string>> | Yes | Data change observer registered. | +| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. | +| type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. | +| observer | Callback<Array<string>> | Yes | Callback for the data change event. | **Example** ```js function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + devices[i] + ' data changed') - } + for (let i = 0; i < devices.length; i++) { + console.info(`device= ${devices[i]} data changed`); + } } try { - rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + store.off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } catch (err) { - console.log('Failed to unregister observer') + console.error(`Unregister observer failed, err: ${err}`); } ``` @@ -2660,16 +2690,15 @@ Provides APIs to access the result set obtained by querying the RDB store. A res ### Usage -Obtain the **resultSet** object by [RdbStore.query()](#query). +Obtain the **resultSet** object first. ```js -import dataRdb from '@ohos.data.rdb'; -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("AGE", 18); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); + console.info(`resultSet columnNames: ${resultSet.columnNames}`); + console.info(`resultSet columnCount: ${resultSet.columnCount}`); }); ``` @@ -2794,13 +2823,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise= rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise= store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goTo(1); - resultSet.close(); + resultSet.goTo(1); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2835,13 +2864,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.(5); - resultSet.close(); + resultSet.(5); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2871,13 +2900,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToFirstRow(); - resultSet.close(); + resultSet.goToFirstRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2906,13 +2935,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToLastRow(); - resultSet.close(); + resultSet.goToLastRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2941,13 +2970,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToNextRow(); - resultSet.close(); + resultSet.goToNextRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -2976,13 +3005,13 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode **Example** ```js -let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { - resultSet.goToPreviousRow(); - resultSet.close(); + resultSet.goToPreviousRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed'); + console.error(`query failed, err: ${err}`); }); ``` @@ -3054,9 +3083,9 @@ Obtains the value of the Long type based on the specified column and the current **Return value** -| Type | Description | -| ------ | -------------------------- | -| number | Value obtained.| +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Value obtained.
The value range supported by this API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).| **Example** @@ -3135,12 +3164,12 @@ Closes this result set. **Example** ```js -let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); -let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +let predicatesClose = new relationalStore.RdbPredicates("EMPLOYEE"); +let promiseClose = store.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promiseClose.then((resultSet) => { - resultSet.close(); + resultSet.close(); }).catch((err) => { - console.log('resultset close failed'); + console.error(`resultset close failed, err: ${err}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 8cdecd1134a270075b3d4dd86a7e4e7a07fc7390..634dd98afad96df6eb8e02549b03c1c2920307cf 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -331,7 +331,7 @@ Obtains the value in the specified column in the current row as a string. getLong(columnIndex: number): number -Obtains the value in the specified column in the current row as a Long. +Obtains the value in the specified column in the current row as a Long integer. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -343,9 +343,9 @@ Obtains the value in the specified column in the current row as a Long. **Return value** - | Type| Description| - | -------- | -------- | - | number | Value in the specified column as a Long.| +| Type| Description| +| -------- | -------- | +| number | Value in the specified column as a Long integer.
The value range supported by this API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).| **Example** diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index e8363f6203436eec807f436ca3c63c00cfc3bc74..60e97b69134e1b1b962fc1f5e67e790a00daea4a 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -78,6 +78,7 @@ Defines device information. | deviceType | [DeviceType](#devicetype) | Yes | Device type. | | networkId8+ | string | Yes | Network ID of the device. | | range9+ | number | Yes | Distance between the device (discovered device) and the device that initiates device discovery. | +| authForm10+ | [AuthForm](#authform) | Yes | Authentication type of the device. | ## DeviceType @@ -95,6 +96,18 @@ Enumerates the device types. | CAR | 0x83 | Car. | | UNKNOWN_TYPE | 0 | Unknown device type.| +## AuthForm + +Enumerates the device authentication types. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Value | Description | +| ------------------- | ---- | --------------- | +| INVALID_TYPE | -1 | No authentication.| +| PEER_TO_PEER | 0 | Point-to-point authentication for devices without accounts. | +| IDENTICAL_ACCOUNT | 1 | Authentication for devices using the same account. | +| ACROSS_ACCOUNT | 2 | Authentication for devices using different accounts.| ## DeviceStateChangeAction @@ -588,8 +601,9 @@ For details about the error codes, see [Device Management Error Codes](../errorc **Example** ```js - // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. try { + // stopDeviceDiscovery and startDeviceDiscovery must be used in pairs, and the input parameter **subscribeId** passed in them must be the same. + var subscribeId = 12345; dmInstance.stopDeviceDiscovery(subscribeId); } catch (err) { console.error("stopDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); @@ -630,7 +644,7 @@ For details about the error codes, see [Device Management Error Codes](../errorc "publishId": publishId, "mode": 0xAA, // Active discovery "freq": 2, // High frequency - "ranging": 1 // The device supports reporting the distance to the discovery initiator. + "ranging": true // The device supports reporting the distance to the discovery initiator. }; try { dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published. @@ -666,8 +680,9 @@ For details about the error codes, see [Device Management Error Codes](../errorc **Example** ```js - // The publishId input must be the same as that automatically generated in publishDeviceDiscovery. try { + // unPublishDeviceDiscovery and publishDeviceDiscovery must be used in pairs, and the input parameter **publishId** passed in them must be the same. + var publishId = 12345; dmInstance.unPublishDeviceDiscovery(publishId); } catch (err) { console.error("unPublishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); @@ -708,11 +723,19 @@ For details about the error codes, see [Device Management Error Codes](../errorc var deviceInfo ={ "deviceId": "XXXXXXXX", "deviceName": "", - deviceType: 0x0E + "deviceType": 0x0E, + "networkId" : "xxxxxxx", + "range" : 0 }; + let extraInfo = { + 'targetPkgName': 'ohos.samples.xxx', + 'appName': 'xxx', + 'appDescription': 'xxx', + 'business': '0' + } let authParam = { - "authType": 1, // Authentication type. The value 1 means no account PIN authentication. - "extraInfo": {} + 'authType': 1, // Authentication type. The value 1 means no account PIN authentication. + 'extraInfo': extraInfo } try { dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { @@ -756,6 +779,13 @@ For details about the error codes, see [Device Management Error Codes](../errorc ```js try { + var deviceInfo ={ + "deviceId": "XXXXXXXX", + "deviceName": "", + "deviceType": 0x0E, + "networkId" : "xxxxxxx", + "range" : 0 + }; dmInstance.unAuthenticateDevice(deviceInfo); } catch (err) { console.error("unAuthenticateDevice errCode:" + err.code + ",errMessage:" + err.message); @@ -792,7 +822,7 @@ For details about the error codes, see [Device Management Error Codes](../errorc ```js let authInfo = { "authType": 1, - "token": xxxxxx, + "token": 123456, "extraInfo": {} } try { @@ -838,7 +868,7 @@ Sets a user operation. operateAction = 5 - Confirm the input in the PIN input box. */ let operation = 0; - this.dmInstance.setUserOperation(operation, "extra") + dmInstance.setUserOperation(operation, "extra") } catch (err) { console.error("setUserOperation errCode:" + err.code + ",errMessage:" + err.message); } @@ -868,11 +898,8 @@ Subscribes to UI status changes. dmInstance.on('uiStateChange', (data) => { console.log("uiStateChange executed, dialog closed" + JSON.stringify(data)) var tmpStr = JSON.parse(data.param) - this.isShow = tmpStr.verifyFailed - console.log("uiStateChange executed, dialog closed" + this.isShow) - if (!this.isShow) { - this.destruction() - } + var isShow = tmpStr.verifyFailed + console.log("uiStateChange executed, dialog closed" + isShow) }); } catch (err) { console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 15f5d8bdbc7796954b7c7129f3ab43321bba5555..634231b14e689d9a2dbdb5e8cc74b3f0117889b8 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -28,6 +28,19 @@ Enumerates the display states. | STATE_VR | 5 | The display is in VR mode.| | STATE_ON_SUSPEND | 6 | The display is powered on, and the CPU is suspended.| +## Orientation10+ + +Enumerates the orientations of the display. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| PORTRAIT | 0 | The display is in portrait mode.| +| LANDSCAPE | 1 | The display is in landscape mode.| +| PORTRAIT_INVERTED | 2 | The display is in reverse portrait mode.| +| LANDSCAPE_INVERTED | 3 | The display is in reverse landscape mode.| + ## Rect9+ Describes a rectangle on the display. @@ -420,6 +433,7 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg | width | number | Yes| No| Width of the display, in pixels.| | height | number | Yes| No| Height of the display, in pixels.| | densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. Generally, the value is **160** or **480**.| +| orientation10+ | [Orientation](#orientation10) | Yes| No| Orientation of the display.| | densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. Generally, the value is **1** or **3**.| | scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. Generally, the value is the same as that of **densityPixels**.| | xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| diff --git a/en/application-dev/reference/apis/js-apis-file-fs.md b/en/application-dev/reference/apis/js-apis-file-fs.md index f82393a4691289ac4729b07334fa54c3b66067e2..19ab5a4812762f0c812a843ad0db452801497dbe 100644 --- a/en/application-dev/reference/apis/js-apis-file-fs.md +++ b/en/application-dev/reference/apis/js-apis-file-fs.md @@ -5,6 +5,7 @@ The **fs** module provides APIs for file operations, including basic file manage > **NOTE** > > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import @@ -15,7 +16,7 @@ import fs from '@ohos.file.fs'; ## Guidelines -Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: +Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the file or directory in the application sandbox as follows: **Stage Model** @@ -147,7 +148,7 @@ Checks whether a file exists. This API uses a promise to return the result. | Type | Description | | ------------------- | ---------------------------- | -| Promise<boolean> | Promise used to return a Boolean value. | +| Promise<boolean> | Promise used to return a Boolean value.| **Example** @@ -554,7 +555,7 @@ Synchronously opens a file. File URIs are supported. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the file in the application sandbox or URI of the file. | -| mode | number | No | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| +| mode | number | No | [Mode](#openmode) for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **OpenMode.READ_ONLY(0o0)**: Open the file in read-only mode.
- **OpenMode.WRITE_ONLY(0o1)**: Open the file in write-only mode.
- **OpenMode.READ_WRITE(0o2)**: Open the file in read/write mode.
You can also specify the following options, separated by a bitwise OR operator (|). By default, no additional options are given.
- **OpenMode.CREATE(0o100)**: If the file does not exist, create it.
- **OpenMode.TRUNC(0o1000)**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **OpenMode.APPEND(0o2000)**: Open the file in append mode. New data will be added to the end of the file.
- **OpenMode.NONBLOCK(0o4000)**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **OpenMode.DIR(0o200000)**: If **path** does not point to a directory, throw an exception.
- **OpenMode.NOFOLLOW(0o400000)**: If **path** points to a symbolic link, throw an exception.
- **OpenMode.SYNC(0o4010000)**: Open the file in synchronous I/O mode.| **Return value** @@ -1079,7 +1080,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Path of the file in the application sandbox. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to read in the file. This parameter is optional. By default, data is read from the current position.
- **length** (number): length of the data to read. This parameter is optional. The default value is the file length.
- **encoding** (string): format of the string to be encoded. The default value is **'utf-8'**, which is the only value supported.| -| callback | AsyncCallback<string> | Yes | Callback used to return the content read. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the content read. | **Example** @@ -1169,7 +1170,7 @@ Obtains information about a symbolic link. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | -------------------------------------- | | path | string | Yes | Path of the symbolic link in the application sandbox.| -| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the symbolic link information obtained. | +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the symbolic link information obtained. | **Example** @@ -1215,7 +1216,7 @@ Obtains information about a symbolic link synchronously. rename(oldPath: string, newPath: string): Promise<void> -Renames a file. This API uses a promise to return the result. +Renames a file or directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1248,7 +1249,7 @@ Renames a file. This API uses a promise to return the result. rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void -Renames a file. This API uses an asynchronous callback to return the result. +Renames a file or directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1278,7 +1279,7 @@ Renames a file. This API uses an asynchronous callback to return the result. renameSync(oldPath: string, newPath: string): void -Synchronously renames a file. +Renames a file or directory synchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1366,7 +1367,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return fsyncSync(fd: number): void -Flushes data of a file to disk in synchronous mode. +Flushes data of a file to disk synchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1454,7 +1455,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return fdatasyncSync(fd: number): void -Synchronizes data in a file in synchronous mode. +Synchronizes data in a file synchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1560,6 +1561,239 @@ Synchronously creates a symbolic link based on a file path. fs.symlinkSync(srcFile, dstFile); ``` +## fs.listFile +listFile(path: string, options?: { + recursion?: boolean; + listNum?: number; + filter?: Filter; +}): Promise; + +Lists all files in a directory. This API uses a promise to return the result.
This API supports recursive listing of all files (including files in subdirectories) and file filtering. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| +| options | Object | No | File filtering options.| + +**options parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| +| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| +| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| Promise<string[]> | Promise used to return the files names listed.| + +**Example** + + ```js + let options = { + "recursion": false, + "listNum": 0, + "filter": { + "suffix": [".png", ".jpg", ".jpeg"], + "displayName": ["%abc", "efg%"], + "fileSizeOver": 1024, + "lastModifiedAfter": new Date().getTime(), + } + }; + fs.listFile(pathDir, options).then((filenames) => { + console.info("listFile succeed"); + for (let i = 0; i < filenames.size; i++) { + console.info("fileName: %s", filenames[i]); + } + }).catch((err) => { + console.info("list file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## fs.listFile +listFile(path: string, options?: { + recursion?: boolean; + listNum?: number; + filter?: Filter; +}, callback: AsyncCallback): void; + +Lists all files in a directory. This API uses an asynchronous callback to return the result.
This API supports recursive listing of all files (including files in subdirectories) and file filtering. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| +| options | Object | No | File filtering options.| +| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the file names listed. | + +**options parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| +| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| +| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| + +**Example** + + ```js + let options = { + "recursion": false, + "listNum": 0, + "filter": { + "suffix": [".png", ".jpg", ".jpeg"], + "displayName": ["%abc", "efg%"], + "fileSizeOver": 1024, + "lastModifiedAfter": new Date().getTime(), + } + }; + fs.listFile(pathDir, options, (err, filenames) => { + if (err) { + console.info("list file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("listFile succeed"); + for (let i = 0; i < filenames.size; i++) { + console.info("filename: %s", filenames[i]); + } + } + }); + ``` + +## listFileSync + +listFileSync(path: string, options?: { + recursion?: boolean; + listNum?: number; + filter?: Filter; +}): string[]; + +Lists all files in a directory synchronously. This API supports recursive listing of all files (including files in subdirectories) and file filtering. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| path | string | Yes | Path of the directory in the application sandbox.| +| options | Object | No | File filtering options.| + +**options parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| recursion | boolean | No | Whether to list all files in subdirectories recursively. The default value is **false**.| +| listNum | number | No | Number of file names to list. The default value **0** means to list all files.| +| filter | [Filter](#filter) | No | File filtering options. Currently, only the match by file name extension, fuzzy search by file name, and filter by file size or latest modification time are supported.| + +**Return value** + +| Type | Description | +| --------------------- | ---------- | +| string[] | File names listed.| + +**Example** + + ```js + let options = { + "recursion": false, + "listNum": 0, + "filter": { + "suffix": [".png", ".jpg", ".jpeg"], + "displayName": ["%abc", "efg%"], + "fileSizeOver": 1024, + "lastModifiedAfter": new Date().getTime(), + } + }; + let filenames = fs.listFileSync(pathDir, options); + console.info("listFile succeed"); + for (let i = 0; i < filenames.size; i++) { + console.info("filename: %s", filenames[i]); + } + ``` +## moveFile + +moveFile(src: string, dest: string, mode?: number): Promise; + +Moves a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| src | string | Yes | Path of the file to move in the application sandbox.| +| dest | string | Yes | Destination path of the file in the application sandbox.| +| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| + +**Example** + + ```js + fs.moveFile(srcPath, destPath, 0).then(() => { + console.info("move file succeed"); + }).catch((err) => { + console.info("move file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +## moveFile + +moveFile(src: string, dest: string, mode?: number, callback: AsyncCallback): void; + +Moves a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| src | string | Yes | Path of the file to move in the application sandbox.| +| dest | string | Yes | Destination path of the file in the application sandbox.| +| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is moved. | + +**Example** + + ```js + fs.moveFile(srcPath, destPath, 0, (err) => { + if (err) { + console.info("move file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.info("move file succeed"); + } + }); + ``` + +## moveFileSync + +moveFile(src: string, dest: string, mode?: number): void; + +Moves a file synchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------------------- | +| src | string | Yes | Path of the file to move in the application sandbox.| +| dest | string | Yes | Destination path of the file in the application sandbox.| +| mode | number | No | Whether to overwrite the file of the same name in the destination directory. The value **0** means to overwrite the file of the same name in the destination directory. The value **1** means to throw an exception if a file of the same name exists in the destination directory. The default value is **0**.| + +**Example** + + ```js + fs.moveFileSync(srcPath, destPath, 0); + console.info("move file succeed"); + ``` + ## fs.mkdtemp mkdtemp(prefix: string): Promise<string> @@ -2354,6 +2588,104 @@ Represents a **File** object opened by **open()**. | ---- | ------ | ---- | ---- | ------- | | fd | number | Yes | No | FD of the file.| +### lock + +lock(exclusive?: boolean): Promise; + +Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ------ | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + file.lock(true).then(() => { + console.log("lock file successful"); + }).catch((err) => { + console.info("lock file failed with error message: " + err.message + ", error code: " + err.code); + }); + ``` + +### lock + +lock(exclusive?: boolean, callback: AsyncCallback): void; + +Applies an exclusive lock or a shared lock on this file in blocking mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is locked. | + +**Example** + + ```js + let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + file.lock(true, (err) => { + if (err) { + console.info("lock file failed with error message: " + err.message + ", error code: " + err.code); + } else { + console.log("lock file successful"); + } + }); + ``` + +### tryLock + +tryLock(exclusive?: boolean): void; + +Applies an exclusive lock or a shared lock on this file in non-blocking mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------- | ---- | ---------------------------------------- | +| exclusive | boolean | No | Lock to apply. The value **true** means an exclusive lock, and the value **false** (default) means a shared lock. | + +**Example** + + ```js + let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + file.tryLock(true); + console.log("lock file successful"); + ``` + +### unlock + +unlock(): void; + +Unlocks this file synchronously. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + + ```js + let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + file.tryLock(true); + file.unlock(); + console.log("unlock file successful"); + ``` + ## OpenMode Defines the constants of the **mode** parameter used in **open()**. It species the mode for opening a file. @@ -2372,3 +2704,18 @@ Defines the constants of the **mode** parameter used in **open()**. It species t | DIR | number | 0o200000 | If **path** does not point to a directory, throw an exception.| | NOFOLLOW | number | 0o400000 | If **path** points to a symbolic link, throw an exception.| | SYNC | number | 0o4010000 | Open the file in synchronous I/O mode.| + +## Filter + +**System capability**: SystemCapability.FileManagement.File.FileIO + +Defines the file filtering configuration, which can be used by **listFile()**. + +| Name | Type | Description | +| ----------- | --------------- | ------------------ | +| suffix | Array<string> | Locate files that fully match the specified file name extensions, which are of the OR relationship. | +| displayName | Array<string> | Locate files that fuzzy match the specified file names, which are of the OR relationship.| +| mimeType | Array<string> | Locate files that fully match the specified MIME types, which are of the OR relationship. | +| fileSizeOver | number | Locate files that are greater than or equal to the specified size. | +| lastModifiedAfter | number | Locate files whose last modification time is the same or later than the specified time. | +| excludeMedia | boolean | Whether to exclude the files already in **Media**. | diff --git a/en/application-dev/reference/apis/js-apis-file-hash.md b/en/application-dev/reference/apis/js-apis-file-hash.md index fca5de996e882e8a568dd3851512ed5e8be18c9c..eb9247ab3ccc6ee628fbd12e8a8a51413abbda01 100644 --- a/en/application-dev/reference/apis/js-apis-file-hash.md +++ b/en/application-dev/reference/apis/js-apis-file-hash.md @@ -60,9 +60,9 @@ Calculates a hash value for a file. This API uses a promise to return the result **Return value** -| Type | Description | -| --------------------- | -------------------------- | -| Promise<string> | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + | Type | Description | + | --------------------- | -------------------------- | + | Promise<string> | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| **Example** @@ -93,6 +93,7 @@ Calculates a hash value for a file. This API uses an asynchronous callback to re **Example** ```js + let filePath = pathDir + "/test.txt"; Hash.hash(filePath, "sha256", (err, str) => { if (err) { console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code); diff --git a/en/application-dev/reference/apis/js-apis-file-statvfs.md b/en/application-dev/reference/apis/js-apis-file-statvfs.md index 8241f4734312251f1d4dce13888a2e8ce521ca90..f431f3cb17d8d82a88a0b9bde7e2a3e3d8e66c86 100644 --- a/en/application-dev/reference/apis/js-apis-file-statvfs.md +++ b/en/application-dev/reference/apis/js-apis-file-statvfs.md @@ -36,14 +36,14 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ```js let path = "/dev"; - statfs.getFreeSize(path).then((number) => { + statvfs.getFreeSize(path).then((number) => { console.info("getFreeSize promise successfully, Size: " + number); }).catch((err) => { console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); }); ``` -## statfs.getFreeSize +## statvfs.getFreeSize getFreeSize(path:string, callback:AsyncCallback<number>): void @@ -62,7 +62,7 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ```js let path = "/dev"; - statfs.getFreeSize(path, (err, number) => { + statvfs.getFreeSize(path, (err, number) => { if (err) { console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code); } else { @@ -71,7 +71,7 @@ Obtains the number of free bytes of the specified file system in asynchronous mo }); ``` -## statfs.getTotalSize +## statvfs.getTotalSize getTotalSize(path: string): Promise<number> @@ -95,14 +95,14 @@ Obtains the total number of bytes of the specified file system in asynchronous m ```js let path = "/dev"; - statfs.getTotalSize(path).then((number) => { + statvfs.getTotalSize(path).then((number) => { console.info("getTotalSize promise successfully, Size: " + number); }).catch((err) => { console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); }); ``` -## statfs.getTotalSize +## statvfs.getTotalSize getTotalSize(path: string, callback: AsyncCallback<number>): void @@ -121,7 +121,7 @@ Obtains the total number of bytes of the specified file system in asynchronous m ```js let path = "/dev"; - statfs.getTotalSize(path, (err, number) => { + statvfs.getTotalSize(path, (err, number) => { if (err) { console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code); } else { diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-file-storage-statistics.md similarity index 67% rename from en/application-dev/reference/apis/js-apis-storage-statistics.md rename to en/application-dev/reference/apis/js-apis-file-storage-statistics.md index d4e334afce241aba6a763a0050b7d22897753a4d..834bf7bcbdd703786d9bb43db8fe0b61956fdd52 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-file-storage-statistics.md @@ -1,29 +1,29 @@ -# @ohos.storageStatistics (Application Storage Statistics) +# @ohos.file.storageStatistics (Application Storage Statistics) The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import ```js -import storageStatistics from "@ohos.storageStatistics"; +import storageStatistics from "@ohos.file.storageStatistics"; ``` ## storageStatistics.getTotalSizeOfVolume getTotalSizeOfVolume(volumeUuid: string): Promise<number> -Asynchronously obtains the total size of the specified volume. This API uses a promise to return the result. +Obtains the total size (in bytes) of the specified volume in an external storage device. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -36,7 +36,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | --------------------- | ---------------- | - | Promise<number> | Promise used to return the total size of the volume.| + | Promise<number> | Promise used to return the total volume size obtained.| **Example** @@ -53,14 +53,14 @@ This is a system API and cannot be called by third-party applications. getTotalSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): void -Asynchronously obtains the total size of the specified volume. This API uses a callback to return the result. +Obtains the total size (in bytes) of the specified volume in an external storage device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -68,7 +68,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | volumeUuid | string | Yes | UUID of the volume. | - | callback | AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the total volume size obtained.| **Example** @@ -84,14 +84,14 @@ This is a system API and cannot be called by third-party applications. getFreeSizeOfVolume(volumeUuid: string): Promise<number> -Asynchronously obtains the available space of the specified volume. This API uses a promise to return the result. +Obtains the available space (in bytes) of the specified volume in an external storage device. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -104,7 +104,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the volume.| + | Promise<number> | Promise used to return the available volume space obtained.| **Example** @@ -122,14 +122,14 @@ This is a system API and cannot be called by third-party applications. getFreeSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): void -Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. +Obtains the available space (in bytes) of the specified volume in an external storage device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -137,7 +137,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | ---------------------------- | | volumeUuid | string | Yes | UUID of the volume. | - | callback | AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the available volume space obtained.| **Example** @@ -153,14 +153,14 @@ This is a system API and cannot be called by third-party applications. getBundleStats(packageName: string): Promise<BundleStats> -Asynchronously obtains space information of an application. This API uses a promise to return the result. +Obtains the space (in bytes) of an application. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -173,7 +173,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the space information obtained.| + | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the application space obtained.| **Example** @@ -190,14 +190,14 @@ This is a system API and cannot be called by third-party applications. getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>): void -Asynchronously obtains space information of an application. This API uses a callback to return the result. +Obtains the space (in bytes) of an application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** @@ -205,7 +205,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | packageName | string | Yes | Bundle name of the application.| - | callback | AsyncCallback<[Bundlestats](#bundlestats9)> | Yes | Callback invoked to return the space information obtained.| + | callback | AsyncCallback<[Bundlestats](#bundlestats9)> | Yes | Callback invoked to return the application space obtained.| **Example** @@ -221,7 +221,7 @@ This is a system API and cannot be called by third-party applications. getCurrentBundleStats(): Promise<BundleStats> -Asynchronously obtains space information of the current third-party application. This API uses a promise to return the result. +Obtains the space (in bytes) of this third-party application. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics @@ -229,7 +229,7 @@ Asynchronously obtains space information of the current third-party application. | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the space information obtained. | + | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the application space obtained. | **Example** @@ -242,7 +242,7 @@ Asynchronously obtains space information of the current third-party application. getCurrentBundleStats(callback: AsyncCallback<BundleStats>): void -Asynchronously obtains space information of the current third-party application. This API uses a callback to return the result. +Obtains the space (in bytes) of this third-party application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics @@ -250,7 +250,7 @@ Asynchronously obtains space information of the current third-party application. | Name | Type | Mandatory | Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | AsyncCallback<[BundleStats](#bundlestats9)> | Yes | Callback invoked to return the space information obtained. | + | callback | AsyncCallback<[BundleStats](#bundlestats9)> | Yes | Callback invoked to return the application space obtained. | **Example** @@ -268,34 +268,33 @@ Asynchronously obtains space information of the current third-party application. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. | Name | Type | Readable| Writable| Description | | --------- | ------ | --- | ---- | -------------- | -| appSize | number | Yes| No| Size of the application. | -| cacheSize | number | Yes| No| Cache size of the application. | -| dataSize | number | Yes| No| Total data size of the application.| +| appSize | number | Yes| No| Size of the application, in bytes. | +| cacheSize | number | Yes| No| Cache size of the application, in bytes. | +| dataSize | number | Yes| No| Total data size of the application, in bytes.| ## storageStatistics.getTotalSize9+ getTotalSize(): Promise<number> -Obtains the total space of the built-in memory card. This API uses a promise to return the result. +Obtains the total size (in bytes) of the built-in storage. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Return value** | Type | Description | | --------------------- | ------------------ | - | Promise<number> | Promise used to return the total space of the built-in memory card. | + | Promise<number> | Promise used to return the built-in storage size obtained. | **Example** @@ -308,21 +307,21 @@ This is a system API and cannot be called by third-party applications. getTotalSize(callback: AsyncCallback<number>): void -Obtains the total space of the built-in memory card. This API uses a callback to return the result. +Obtains the total size (in bytes) of the built-in storage. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** | Name | Type | Mandatory | Description | | -------- | ------------------------------------ | ---- | ------------------------ | - | callback | AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the built-in storage size obtained.| **Example** @@ -338,21 +337,21 @@ This is a system API and cannot be called by third-party applications. getFreeSize(): Promise<number> -Obtains the available space of the built-in memory card. This API uses a promise to return the result. +Obtains the available space (in bytes) of the built-in storage. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Return value** | Type | Description | | --------------------- | ------------------ | - | Promise<number> | Promise used to return the available space of the built-in memory card.| + | Promise<number> | Promise used to return the available space of the built-in storage obtained.| **Example** @@ -366,21 +365,21 @@ This is a system API and cannot be called by third-party applications. getFreeSize(callback: AsyncCallback<number>): void -Obtains the available space of the built-in memory card. This API uses a callback to return the result. +Obtains the available space (in bytes) of the built-in storage. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------- | - | callback | AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in storage obtained.| **Example** @@ -395,21 +394,21 @@ This is a system API and cannot be called by third-party applications. getSystemSize(): Promise<number> -Asynchronously obtains the system space. This API uses a promise to return the result. +Obtains the system data space, in bytes. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Return value** | Type | Description | | --------------------- | ---------------- | - | Promise<number> | Promise used to return the system space obtained.| + | Promise<number> | Promise used to return the system data space obtained.| **Example** @@ -425,21 +424,21 @@ This is a system API and cannot be called by third-party applications. getSystemSize(callback: AsyncCallback<number>): void -Asynchronously obtains the system space. This API uses a callback to return the result. +Obtains the system data space, in bytes. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | callback | AsyncCallback<number> | Yes | Callback used to return the system space obtained.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the system data space obtained.| **Example** @@ -452,23 +451,79 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getUserStorageStats9+ -getUserStorageStats(userId?: number): Promise<StorageStats> +getUserStorageStats(): Promise<StorageStats> + +Obtains the storage statistics (in bytes) of this user. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API. + + +**Return value** + + | Type | Description | + | --------------------- | ---------------- | + | Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| + +**Example** + + ```js + storageStatistics.getUserStorageStats().then(function(StorageStats){ + console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); + }).catch(function(err){ + console.info("getUserStorageStats failed with error:"+ err); + }); + ``` + +## storageStatistics.getUserStorageStats9+ + +getUserStorageStats(callback: AsyncCallback<StorageStats>): void + +Obtains the storage statistics (in bytes) of this user. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API. + + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------------------------------------ | ---- | -------------------------- | + | callback | AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| + +**Example** + + ```js + storageStatistics.getUserStorageStats(function(error, StorageStats){ + // Do something. + console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); + }); + ``` +getUserStorageStats(userId: number): Promise<StorageStats> -Asynchronously obtains the space occupied by each type of user data. This API uses a promise to return the result. +Obtains the storage statistics (in bytes) of the specified user. This API uses a promise to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| + | userId | number | Yes | User ID.| **Return value** @@ -479,7 +534,7 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - let userId = 1; + let userId = 100; storageStatistics.getUserStorageStats(userId).then(function(StorageStats){ console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); }).catch(function(err){ @@ -489,29 +544,29 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getUserStorageStats9+ -getUserStorageStats(userId?: number, callback: AsyncCallback<StorageStats>): void +getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>): void -Asynchronously obtains the space occupied by each type of user data. This API uses a callback to return the result. +Obtains the storage statistics (in bytes) of the specified user. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | + | userId | number | Yes | User ID.| | callback | AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| **Example** ```js - let userId = 1; + let userId = 100; storageStatistics.getUserStorageStats(userId, function(error, StorageStats){ // Do something. console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); @@ -526,13 +581,13 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -This is a system API and cannot be called by third-party applications. +This is a system API. | Name | Type | Readable | Writable | Description | | --------- | ------ | ---- | ----- | -------------- | -| total | number | Yes| No| Total space of the built-in memory card. | -| audio | number |Yes| No| Space occupied by audio data. | -| video | number | Yes| No| Space occupied by video data.| -| image | number | Yes| No| Space occupied by image data. | -| file | number | Yes| No| Space occupied by files. | -| app | number | Yes| No| Space occupied by application data.| +| total | number | Yes| No| Total size of the built-in storage, in bytes. | +| audio | number |Yes| No| Space occupied by audio data, in bytes. | +| video | number | Yes| No| Space occupied by video data, in bytes.| +| image | number | Yes| No| Space occupied by image data, in bytes. | +| file | number | Yes| No| Space occupied by files, in bytes. | +| app | number | Yes| No| Space occupied by application data, in bytes.| diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-file-volumemanager.md similarity index 94% rename from en/application-dev/reference/apis/js-apis-volumemanager.md rename to en/application-dev/reference/apis/js-apis-file-volumemanager.md index e6af2c7d1c7a12aa67c491fb468b7d81555c917b..bf1e5c9c417ecc5940e75d4876def5ffd7b4b210 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-file-volumemanager.md @@ -1,16 +1,17 @@ -# @ohos.volumeManager (Volume Management) +# @ohos.file.volumeManager (Volument Management) The volumeManager module provides APIs for volume and disk management, including obtaining volume information, mounting or unmounting volumes, partitioning disks, and formatting volumes. > **NOTE** > -> - The initial APIs of this module are supported since API version 9. -> - The APIs of this module are system APIs and cannot be called by third-party 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. +> - The APIs provided by this module are system APIs. +> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md). ## Modules to Import ```js -import volumemanager from "@ohos.volumeManager"; +import volumemanager from "@ohos.file.volumeManager"; ``` ## volumemanager.getAllVolumes @@ -65,7 +66,7 @@ Asynchronously obtains information about all available volumes. This API uses a ## volumemanager.mount -mount(volumeId: string): Promise<boolean> +mount(volumeId: string): Promise<void> Asynchronously mounts a volume. This API uses a promise to return the result. @@ -83,7 +84,7 @@ Asynchronously mounts a volume. This API uses a promise to return the result. | Type | Description | | ---------------------- | ---------- | - | Promise<boolean> | Promise used to return the execution result.| + | Promise<void> | Promise used to return the result.| **Example** @@ -96,7 +97,7 @@ Asynchronously mounts a volume. This API uses a promise to return the result. ## volumemanager.mount -mount(volumeId: string, callback:AsyncCallback<boolean>):void +mount(volumeId: string, callback:AsyncCallback<void>):void Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. @@ -109,7 +110,7 @@ Asynchronously obtains the available space of the specified volume. This API use | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -122,7 +123,7 @@ Asynchronously obtains the available space of the specified volume. This API use ## volumemanager.unmount -unmount(volumeId: string): Promise<boolean> +unmount(volumeId: string): Promise<void> Asynchronously unmounts a volume. This API uses a promise to return the result. @@ -140,7 +141,7 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. | Type | Description | | ---------------------- | ---------- | - | Promise<boolean> | Promise used to return the execution result.| + | Promise<void> | Promise used to return the result.| **Example** @@ -153,7 +154,7 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. ## volumemanager.unmount -unmount(volumeId: string, callback: AsyncCallback<boolean>): void +unmount(volumeId: string, callback: AsyncCallback<void>): void Asynchronously unmounts a volume. This API uses a callback to return the result. @@ -166,7 +167,7 @@ Asynchronously unmounts a volume. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md index 9d653bc4344c6f0262e55b557d72435620ba3d74..1532556e3516f3fa91b911ac74dd33e72caff7bb 100644 --- a/en/application-dev/reference/apis/js-apis-fileAccess.md +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -25,9 +25,9 @@ Obtains information about all wants with **extension** set to **fileAccess** in **Return value** -| Type| Description| -| --- | -- | -| Promise<Array<Want>> | Promise used to return the **want** information obtained.| + | Type| Description| + | --- | -- | + | Promise<Array<Want>> | Promise used to return the **want** information obtained.| **Example** @@ -55,9 +55,9 @@ Obtains information about all wants with **extension** set to **fileAccess** in **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| callback | AsyncCallback<Array<Want>> | Yes| Promise used to return the **want** information obtained.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | callback | AsyncCallback<Array<Want>> | Yes| Promise used to return the **want** information obtained.| **Example** @@ -89,16 +89,16 @@ Synchronously creates a **Helper** object to connect to the specified wants. The **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| context | Context | Yes| Context of the ability.| -| wants | Array<Want> | Yes| Wants to connect.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | context | Context | Yes| Context of the ability.| + | wants | Array<Want> | Yes| Wants to connect.| **Return value** -| Type| Description| -| --- | -- | -| FileAccessHelper | **Helper** object created.| + | Type| Description| + | --- | -- | + | FileAccessHelper | **Helper** object created.| **Example** @@ -136,26 +136,26 @@ Synchronously creates a **Helper** object to connect to all file management serv **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| context | Context | Yes| Context of the ability.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | context | Context | Yes| Context of the ability.| **Return value** -| Type| Description| -| --- | -- | -| FileAccessHelper | **Helper** object created.| + | Type| Description| + | --- | -- | + | FileAccessHelper | **Helper** object created.| **Example** ```js createFileAccessHelper() { - let fileAccesssHelperAllServer = null; + let fileAccessHelperAllServer = null; // Create a Helper object to interact with all file management services configured with fileAccess in the system. try { // this.context is passed by EntryAbility. - fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context); - if (!fileAccesssHelperAllServer) + fileAccessHelperAllServer = fileAccess.createFileAccessHelper(this.context); + if (!fileAccessHelperAllServer) console.error("createFileAccessHelper interface returns an undefined object"); } catch (error) { console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); @@ -175,9 +175,9 @@ Obtains information about the device root nodes of the file management service t **Return value** -| Type| Description| -| --- | -- | -| Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| + | Type| Description| + | --- | -- | + | Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| **Example** @@ -210,7 +210,9 @@ Obtains information about the device root nodes of the file management service t getRoots(callback:AsyncCallback<RootIterator>) : void; -Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result. The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext). +Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result. + +The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -218,9 +220,9 @@ Obtains information about the device root nodes of the file management service t **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| callback | AsyncCallback<RootIterator> | Yes| Promise used to return the **RootIterator** object obtained.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | callback | AsyncCallback<RootIterator> | Yes| Promise used to return the **RootIterator** object obtained.| **Example** @@ -253,7 +255,7 @@ Obtains information about the device root nodes of the file management service t listFile(filter?: Filter) : FileIterator -Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the device root node. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). +Synchronously obtains the **FileIterator** object of the first-level files (file directory) matching the conditions of the filter from the device root node. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -261,16 +263,16 @@ Synchronously obtains the **FileIterator** object of the first-level files (file **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -312,15 +314,15 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -354,7 +356,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit listFile(filter?: Filter) : FileIterator -Synchronously obtains the **FileIterator** object of the next-level files (file folders) matching the conditions of the filter from a directory. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). +Synchronously obtains the **FileIterator** object of the next-level files (file directories) matching the conditions of the filter from a directory. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -362,15 +364,15 @@ Synchronously obtains the **FileIterator** object of the next-level files (file **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -412,16 +414,16 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -463,10 +465,10 @@ Creates a file in a directory. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the parent directory for the file to create.| -| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the parent directory for the file to create.| + | displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| **Return value** @@ -508,11 +510,11 @@ Creates a file in a directory. This API uses an asynchronous callback to return **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the parent directory for the file to create.| -| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| -| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file created.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the parent directory for the file to create.| + | displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file created.| **Example** @@ -540,7 +542,7 @@ Creates a file in a directory. This API uses an asynchronous callback to return mkDir(parentUri: string, displayName: string) : Promise<string> -Creates a folder in a directory. This API uses a promise to return the result. +Creates a directory in a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -548,16 +550,16 @@ Creates a folder in a directory. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| parentUri | string | Yes| URI of the parent directory for the folder to create.| -| displayName | string | Yes| Name of the folder to create.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | parentUri | string | Yes| URI of the parent directory for the directory to create.| + | displayName | string | Yes| Name of the directory to create.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | Promise used to return the URI of the folder created.| +| Promise<string> | Promise used to return the URI of the directory created.| **Example** @@ -585,7 +587,7 @@ Creates a folder in a directory. This API uses a promise to return the result. mkDir(parentUri: string, displayName: string, callback: AsyncCallback<string>) : void; -Creates a folder in a directory. This API uses an asynchronous callback to return the result. +Creates a directory in a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -593,11 +595,11 @@ Creates a folder in a directory. This API uses an asynchronous callback to retur **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| parentUri | string | Yes| URI of the parent directory for the folder to create.| -| displayName | string | Yes| Name of the folder to create.| -| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the folder created.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | parentUri | string | Yes| URI of the parent directory for the directory to create.| + | displayName | string | Yes| Name of the directory to create.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the directory created.| **Example** @@ -633,10 +635,10 @@ Opens a file. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file to open.| -| flags | [OPENFLAGS](#openflags) | Yes| File open mode.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file to open.| + | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| **Return value** @@ -671,11 +673,11 @@ Opens a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file to open.| -| flags | [OPENFLAGS](#openflags) | Yes| File open mode.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the file descriptor of the file opened.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file to open.| + | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the file descriptor of the file opened.| **Example** @@ -702,7 +704,7 @@ Opens a file. This API uses an asynchronous callback to return the result. delete(uri: string) : Promise<number> -Deletes a file or folder. This API uses a promise to return the result. +Deletes a file or directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -710,9 +712,9 @@ Deletes a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to delete.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or directory to delete.| **Return value** @@ -741,7 +743,7 @@ Deletes a file or folder. This API uses a promise to return the result. delete(uri: string, callback: AsyncCallback<number>) : void; -Deletes a file or folder. This API uses an asynchronous callback to return the result. +Deletes a file or directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -749,10 +751,10 @@ Deletes a file or folder. This API uses an asynchronous callback to return the r **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to delete.| -| callback | AsyncCallback<number> | Yes| Promise used to return the result.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or directory to delete.| + | callback | AsyncCallback<number> | Yes| Promise used to return the result.| **Example** @@ -779,7 +781,7 @@ Deletes a file or folder. This API uses an asynchronous callback to return the r move(sourceFile: string, destFile: string) : Promise<string> -Moves a file or folder. This API uses a promise to return the result. +Moves a file or directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -787,22 +789,22 @@ Moves a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFile | string | Yes| URI of the file or folder to move.| -| destFile | string | Yes| URI of the folder to which the file or folder will be moved.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFile | string | Yes| URI of the file or directory to move.| + | destFile | string | Yes| URI of the directory, to which the file or directory will be moved.| **Return value** | Type| Description| | ----- | ------ | -| Promise<string> | Promise used to return the URI of the file or folder in the destination directory.| +| Promise<string> | Promise used to return the URI of the file or directory in the destination directory.| **Example** ```js // The media library URI is used as an example. - //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the URI in fileInfo. + //In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo. // You can use the URI obtained. let sourceFile = "datashare:///media/file/102"; let destFile = "datashare:///media/file/101"; @@ -819,7 +821,7 @@ Moves a file or folder. This API uses a promise to return the result. move(sourceFile: string, destFile: string, callback: AsyncCallback<string>) : void; -Moves a file or folder. This API uses an asynchronous callback to return the result. +Moves a file or directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -827,17 +829,17 @@ Moves a file or folder. This API uses an asynchronous callback to return the res **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFile | string | Yes| URI of the file or folder to move.| -| destFile | string | Yes| URI of the folder to which the file or folder will be moved.| -| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file or folder in the destination directory.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFile | string | Yes| URI of the file or directory to move.| + | destFile | string | Yes| URI of the directory, to which the file or directory will be moved.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file or directory in the destination directory.| **Example** ```js // The media library URI is used as an example. - //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the URI in fileInfo. + //In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo. // You can use the URI obtained. let sourceFile = "datashare:///media/file/102"; let destFile = "datashare:///media/file/101"; @@ -859,7 +861,7 @@ Moves a file or folder. This API uses an asynchronous callback to return the res rename(uri: string, displayName: string) : Promise<string> -Renames a file or folder. This API uses a promise to return the result. +Renames a file or directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -867,16 +869,16 @@ Renames a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to rename.| -| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or directory to rename.| + | displayName | string | Yes| New name of the file or directory, which can contain the file name extension.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | Promise used to return the URI of the renamed file or folder.| +| Promise<string> | Promise used to return the URI of the renamed file or directory.| **Example** @@ -898,7 +900,7 @@ Renames a file or folder. This API uses a promise to return the result. rename(uri: string, displayName: string, callback: AsyncCallback<string>) : void; -Renames a file or folder. This API uses an asynchronous callback to return the result. +Renames a file or directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -906,11 +908,11 @@ Renames a file or folder. This API uses an asynchronous callback to return the r **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to rename.| -| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| -| callback | AsyncCallback<string> | Yes| Promise used to return the URI of the renamed file or folder.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or directory to rename.| + | displayName | string | Yes| New name of the file or directory, which can contain the file name extension.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the renamed file or directory.| **Example** @@ -937,7 +939,7 @@ Renames a file or folder. This API uses an asynchronous callback to return the r access(sourceFileUri: string) : Promise<boolean> -Checks whether a file or folder exists. This API uses a promise to return the result. +Checks whether a file or directory exists. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -945,9 +947,9 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFileUri | string | Yes| URI of the file or folder.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFileUri | string | Yes| URI of the file or directory.| **Return value** @@ -978,7 +980,7 @@ Checks whether a file or folder exists. This API uses a promise to return the re access(sourceFileUri: string, callback: AsyncCallback<boolean>) : void; -Checks whether a file or folder exists. This API uses an asynchronous callback to return the result. +Checks whether a file or directory exists. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -986,10 +988,10 @@ Checks whether a file or folder exists. This API uses an asynchronous callback t **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFileUri | string | Yes| URI of the file or folder.| -| callback | AsyncCallback<boolean> | Yes| Promise used to return the result.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFileUri | string | Yes| URI of the file or directory.| + | callback | AsyncCallback<boolean> | Yes| Promise used to return the result.| **Example** @@ -1029,13 +1031,13 @@ Obtains the next-level device root directory. **RootIterator** is an iterator ob | Type| Description| | --- | -- | -| {value: RootInfo, done: boolean} | Root directory information obtained. This API traverses the folder until **done** returns **true**. The **value** field contains the root directory information.| +| {value: RootInfo, done: boolean} | Root directory information obtained. This API traverses the directory until **done** returns **true**. The **value** field contains the root directory information.| ## FileIterator.next next( ) : { value: FileInfo, done: boolean } -Obtains the information about the next-level file or folder. **FileIterator** is an iterator object of a folder. +Obtains the information about the next-level file or directory. **FileIterator** is an iterator object of a directory. **System capability**: SystemCapability.FileManagement.UserFileService @@ -1045,7 +1047,7 @@ Obtains the information about the next-level file or folder. **FileIterator** is | Type| Description| | --- | -- | -| {value: FileInfo, done: boolean} | File or folder information obtained. This API traverses the specified folder until **done** returns **true**. The **value** field contains the file or folder information obtained.| +| {value: FileInfo, done: boolean} | File or directory information obtained. This API traverses the specified directory until **done** returns **true**. The **value** field contains the file or directory information obtained.| ## RootInfo @@ -1066,7 +1068,7 @@ Represents the root attribute information and interface capabilities of a device ## FileInfo -Represents the file or folder attribute information and interface capabilities. +Represents the file or directory attribute information and interface capabilities. **System capability**: SystemCapability.FileManagement.UserFileService @@ -1076,12 +1078,12 @@ Represents the file or folder attribute information and interface capabilities. | Name| Type | Readable| Writable| Description | | ------ | ------ | -------- | ------ | -------- | -| uri | string | Yes| No| URI of the file or folder.| -| fileName | string | Yes| No| Name of a file or folder.| -| mode | number | Yes| No| Permissions on the file or folder.| -| size | number | Yes| No| Size of the file or folder.| -| mtime | number | Yes| No| Time when the file or folder was last modified.| -| mimeType | string | Yes| No| MIME type of the file or folder.| +| uri | string | Yes| No| URI of the file or directory.| +| fileName | string | Yes| No| Name of a file or directory.| +| mode | number | Yes| No| Permissions on the file or directory.| +| size | number | Yes| No| Size of the file or directory.| +| mtime | number | Yes| No| Time when the file or directory was last modified.| +| mimeType | string | Yes| No| MIME type of the file or directory.| ## OPENFLAGS diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 16b144f78ec85198dfc570336fcf021a9bc86028..c675e395d694b58c2d79bbc152344f98b2505e75 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -736,9 +736,15 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function Demo() { - await pixelmap.rotate(90.0); -} +var angle = 90.0; +pixelmap.rotate(angle, (err) => { + if (err) { + console.error("Failed to set rotation."); + return; + } else { + console.log("Succeeded in setting rotation."); + } +}) ``` ### rotate9+ @@ -942,7 +948,8 @@ Creates an **ImageSource** instance based on the URI. **Example** ```js -let path = this.context.getApplicationContext().fileDirs + "test.jpg"; +let context = featureAbility.getContext(); +let path = context.getCacheDir() + "test.jpg"; const imageSourceApi = image.createImageSource(path); ``` @@ -2039,7 +2046,7 @@ Creates an **ImageCreator** instance by specifying the image width, height, form | Type | Description | | ------------------------------ | --------------------------------------- | -| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| **Example** @@ -2524,7 +2531,7 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the following formats are supported: JPG, PNG, GIF, BMP, Webp, and RAW.| +| format | string | Yes | Yes | Format of the packed image.
Only the JPG and WebP formats are supported.| | quality | number | Yes | Yes | Quality of the output image in JPEG encoding. The value ranges from 1 to 100.| | bufferSize9+ | number | Yes | Yes | Buffer size, which is used to set the image size. The default value is 10 MB.| diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md index db0814fa146e09114eeb4fa635dfa78564ee595e..d311a6c175a5bea86be8635cf032839552b998f9 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -9,3 +9,26 @@ | onConnect7+ | function | Yes | Callback invoked when a connection is set up. | | onDisconnect7+ | function | Yes | Callback invoked when a connection is interrupted. | | onFailed7+ | function | Yes | Callback invoked when a connection fails.| + +**Example** + + ```ts + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' + }; + + let connectOptions = { + onConnect(elementName, remote) { + console.log('onConnect elementName: ${elementName}'); + }, + onDisconnect(elementName) { + console.log('onDisconnect elementName: ${elementName}'); + }, + onFailed(code) { + console.error('onFailed code: ${code}'); + } + }; + + let connection = this.context.connectAbility(want, connectOptions); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index d6b0c51051feb92f30495bdc552f84cae5e06018..818b1e8e324ba1ffa5aa5301dbe3843c8d4e4ba0 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -35,12 +35,12 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var mode = "rw"; -DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { - console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +let mode = 'rw'; +DAHelper.openFile('dataability:///com.example.DataAbility', mode, (err, data) => { + console.info('openFile err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -69,12 +69,12 @@ Opens a file with a specified URI. This API uses a promise to return a file desc ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var mode = "rw"; -DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { - console.info("openFile data: " + JSON.stringify(data)); +let mode = 'rw'; +DAHelper.openFile('dataability:///com.example.DataAbility', mode).then((data) => { + console.info('openFile data: ${JSON.stringify(data)}'); }); ``` @@ -90,7 +90,7 @@ Registers an observer to listen for changes in the data specified by a given URI | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | The value **dataChange** means data changes. | +| type | string | Yes | The value **'dataChange'** means data changes. | | uri | string | Yes | URI of the data.| | callback | AsyncCallback\ | Yes | Callback invoked when the data is changed. | @@ -98,15 +98,15 @@ Registers an observer to listen for changes in the data specified by a given URI ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); function onChangeNotify() { - console.info("onChangeNotify call back"); + console.info('onChangeNotify call back'); }; DAHelper.on( - "dataChange", - "dataability:///com.example.DataAbility", + 'dataChange', + 'dataability:///com.example.DataAbility', onChangeNotify ); ``` @@ -123,7 +123,7 @@ Deregisters the observer that listens for changes in the data specified by a giv | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | The value **dataChange** means data changes. | +| type | string | Yes | The value **'dataChange'** means data changes. | | uri | string | Yes | URI of the data.| | callback | AsyncCallback\ | No | Callback of the listener to deregister. If the callback is set to **null**, all data change listeners are canceled. | @@ -131,20 +131,20 @@ Deregisters the observer that listens for changes in the data specified by a giv ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); function onChangeNotify() { - console.info("onChangeNotify call back"); + console.info('onChangeNotify call back'); }; DAHelper.off( - "dataChange", - "dataability:///com.example.DataAbility", + 'dataChange', + 'dataability:///com.example.DataAbility', onChangeNotify ); DAHelper.off( - "dataChange", - "dataability:///com.example.DataAbility", + 'dataChange', + 'dataability:///com.example.DataAbility', ); ``` @@ -167,11 +167,11 @@ Obtains the media resource type of the data specified by a given URI. This API u ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { - console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.getType('dataability:///com.example.DataAbility', (err, data) => { + console.info('getType err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -199,11 +199,11 @@ Obtains the media resource type of the data specified by a given URI. This API u ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { - console.info("getType data: " + JSON.stringify(data)); +DAHelper.getType('dataability:///com.example.DataAbility').then((data) => { + console.info('getType data: ${JSON.stringify(data)}'); }); ``` @@ -227,11 +227,11 @@ Obtains the supported media resource types of a specified file. This API uses an ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => { - console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.getFileTypes( 'dataability:///com.example.DataAbility', 'image/*', (err, data) => { + console.info('getFileTypes err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -260,11 +260,11 @@ Obtains the supported media resource types of a specified file. This API uses a ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { - console.info("getFileTypes data: " + JSON.stringify(data)); +DAHelper.getFileTypes('dataability:///com.example.DataAbility', 'image/*').then((data) => { + console.info('getFileTypes data: ${JSON.stringify(data)}'); }); ``` @@ -287,11 +287,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { - console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.normalizeUri('dataability:///com.example.DataAbility', (err, data) => { + console.info('normalizeUri err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -319,11 +319,11 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { - console.info("normalizeUri data: " + JSON.stringify(data)); +DAHelper.normalizeUri('dataability:///com.example.DataAbility',).then((data) => { + console.info('normalizeUri data: ${JSON.stringify(data)}'); }); ``` @@ -346,11 +346,11 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { - console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.denormalizeUri('dataability:///com.example.DataAbility', (err, data) => { + console.info('denormalizeUri err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -378,11 +378,11 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { - console.info("denormalizeUri data: " + JSON.stringify(data)); +DAHelper.denormalizeUri('dataability:///com.example.DataAbility',).then((data) => { + console.info('denormalizeUri data: ${JSON.stringify(data)}'); }); ``` @@ -405,11 +405,11 @@ Notifies the registered observer of a change to the data specified by the URI. T ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { - console.info("==========================>Called=======================>"); +DAHelper.notifyChange('dataability:///com.example.DataAbility', (err) => { + console.info('==========================>Called=======================>'); }); ``` @@ -437,11 +437,11 @@ Notifies the registered observer of a change to the data specified by the URI. T ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => { - console.info("================>notifyChangeCallback================>"); +DAHelper.notifyChange('dataability:///com.example.DataAbility').then(() => { + console.info('================>notifyChangeCallback================>'); }); ``` @@ -465,17 +465,17 @@ Inserts a single data record into the database. This API uses an asynchronous ca ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const valueBucket = { - "name": "rose", - "age": 22, - "salary": 200.5, - "blobType": "u8", + 'name': 'rose', + 'age': 22, + 'salary': 200.5, + 'blobType': 'u8', }; -DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => { - console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.insert('dataability:///com.example.DataAbility', valueBucket, (err, data) => { + console.info('insert err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -504,17 +504,17 @@ Inserts a single data record into the database. This API uses a promise to retur ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const valueBucket = { - "name": "rose1", - "age": 221, - "salary": 20.5, - "blobType": "u8", + 'name': 'rose1', + 'age': 221, + 'salary': 20.5, + 'blobType': 'u8', }; -DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => { - console.info("insert data: " + JSON.stringify(data)); +DAHelper.insert('dataability:///com.example.DataAbility', valueBucket).then((data) => { + console.info('insert data: ${JSON.stringify(data)}'); }); ``` @@ -538,14 +538,14 @@ Inserts multiple data records into the database. This API uses an asynchronous c ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); -DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => { - console.info("batchInsert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe12', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}); +DAHelper.batchInsert('dataability:///com.example.DataAbility', cars, (err, data) => { + console.info('batchInsert err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -574,14 +574,14 @@ Inserts multiple data records into the database. This API uses a promise to retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); -DAHelper.batchInsert("dataability:///com.example.DataAbility", cars).then((data) => { - console.info("batchInsert data: " + JSON.stringify(data)); +let cars = new Array({'name': 'roe11', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe12', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}, + {'name': 'roe13', 'age': 21, 'salary': 20.5, 'blobType': 'u8',}); +DAHelper.batchInsert('dataability:///com.example.DataAbility', cars).then((data) => { + console.info('batchInsert data: ${JSON.stringify(data)}'); }); ``` @@ -606,12 +606,12 @@ Deletes one or more data records from the database. This API uses an asynchronou ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.delete("dataability:///com.example.DataAbility", da, (err, data) => { - console.info("delete err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.delete('dataability:///com.example.DataAbility', da, (err, data) => { + console.info('delete err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -641,12 +641,12 @@ Deletes one or more data records from the database. This API uses a promise to r ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => { - console.info("delete data: " + JSON.stringify(data)); +DAHelper.delete('dataability:///com.example.DataAbility', da).then((data) => { + console.info('delete data: ${JSON.stringify(data)}'); }); ``` @@ -672,18 +672,18 @@ Updates data records in the database. This API uses an asynchronous callback to ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": "u8", + 'name': 'roe1', + 'age': 21, + 'salary': 20.5, + 'blobType': 'u8', }; let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.update("dataability:///com.example.DataAbility", va, da, (err, data) => { - console.info("update err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.update('dataability:///com.example.DataAbility', va, da, (err, data) => { + console.info('update err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -714,18 +714,18 @@ Updates data records in the database. This API uses a promise to return the resu ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); const va = { - "name": "roe1", - "age": 21, - "salary": 20.5, - "blobType": "u8", + 'name': 'roe1', + 'age': 21, + 'salary': 20.5, + 'blobType': 'u8', }; let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => { - console.info("update data: " + JSON.stringify(data)); +DAHelper.update('dataability:///com.example.DataAbility', va, da).then((data) => { + console.info('update data: ${JSON.stringify(data)}'); }); ``` @@ -751,13 +751,13 @@ Queries data in the database. This API uses an asynchronous callback to return t ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var cars=new Array("value1", "value2", "value3", "value4"); +let cars=new Array('value1', 'value2', 'value3', 'value4'); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => { - console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +DAHelper.query('dataability:///com.example.DataAbility', cars, da, (err, data) => { + console.info('query err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -790,13 +790,13 @@ Queries data in the database. This API uses a promise to return the result. ```ts import featureAbility from '@ohos.ability.featureAbility'; import ohos_data_ability from '@ohos.data.dataAbility'; -var DAHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper( + 'dataability:///com.example.DataAbility' ); -var cars = new Array("value1", "value2", "value3", "value4"); +let cars = new Array('value1', 'value2', 'value3', 'value4'); let da = new ohos_data_ability.DataAbilityPredicates(); -DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => { - console.info("query data: " + JSON.stringify(data)); +DAHelper.query('dataability:///com.example.DataAbility', cars, da).then((data) => { + console.info('query data: ${JSON.stringify(data)}'); }); ``` @@ -812,7 +812,7 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | method | string | Yes | Name of the API to call. | | arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | @@ -824,15 +824,15 @@ Calls an extended API of the DataAbility. This API uses an asynchronous callback import featureAbility from '@ohos.ability.featureAbility'; let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" + 'dataability:///com.example.jsapidemo.UserDataAbility' ); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", - "method", "arg", {"key1":"value1"}, (err, data) => { +dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', + 'method', 'arg', {'key1':'value1'}, (err, data) => { if (err) { - console.error('Operation failed. Cause: ' + err); + console.error('Operation failed. Cause: ${err}'); return; } - console.info('Operation succeeded: ' + data); + console.info('Operation succeeded: ${data}'); }); ``` @@ -848,7 +848,7 @@ Calls an extended API of the DataAbility. This API uses a promise to return the | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | method | string | Yes | Name of the API to call. | | arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | @@ -865,13 +865,13 @@ Calls an extended API of the DataAbility. This API uses a promise to return the import featureAbility from '@ohos.ability.featureAbility'; let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" + 'dataability:///com.example.jsapidemo.UserDataAbility' ); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", - "method", "arg", {"key1":"value1"}).then((data) => { - console.info('Operation succeeded: ' + data); +dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility', + 'method', 'arg', {'key1':'value1'}).then((data) => { + console.info('Operation succeeded: ${data}'); }).catch((error) => { - console.error('Operation failed. Cause: ' + error); + console.error('Operation failed. Cause: ${error}'); }); ``` @@ -887,7 +887,7 @@ Operates data in the database in batches. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | ----------| ---------------------------------| ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| +| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'.| | operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. | | callback | AsyncCallback\> | Yes | Callback used to return the result of each operation in the **DataAbilityResult** array. | @@ -899,14 +899,14 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" + 'dataability:///com.example.jsapidemo.UserDataAbility' ); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { +dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op, (err, data) => { if (err) { - console.error('Operation failed. Cause: ' + err); + console.error('Operation failed. Cause: ${err}'); return; } - console.info('Operation succeeded: ' + data); + console.info('Operation succeeded: ${data}'); }); ``` @@ -922,7 +922,7 @@ Operates data in the database in batches. This API uses a promise to return the | Name | Type | Mandatory| Description | | ---------- | -------------------------------| ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| +| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'.| | operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. | **Return value** @@ -939,12 +939,12 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( - "dataability:///com.example.jsapidemo.UserDataAbility" + 'dataability:///com.example.jsapidemo.UserDataAbility' ); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => { - console.info('Operation succeeded: ' + data); +dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op).then((data) => { + console.info('Operation succeeded: ${data}'); }).catch((error) => { - console.error('Operation failed. Cause: ' + error); + console.error('Operation failed. Cause: ${error}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md index 0b96b8caa97bb28e7515bbc00ee1d7852ad2d21a..48be29362cfae78060f98aa2440a442e89ea2715 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md @@ -11,7 +11,7 @@ The **DataAbilityOperation** module defines the operation on DataAbilities. It c | Name | Template | Mandatory| Description | | -------- | -------- | --------| -------- | -| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | type | featureAbility.DataAbilityOperationType | Yes | Operation type. | | valuesBucket? | rdb.ValuesBucket | No | Data value to set. | | valueBackReferences? | rdb.ValuesBucket | No | **ValuesBucket** object that contains a set of key-value pairs. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md index 49b14bebedfaa76b495e8a127e3f4bd243c649b7..2b90cd54ed08d8a8c954c0598049019d5673b2fa 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -11,33 +11,33 @@ The **DataAbilityResult** module defines the operation result on DataAbilities. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| uri? | string | No | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| uri? | string | No | URI of the DataAbility. Example: 'dataability:///com.example.xxx.xxxx'. | | count? | number | No | Number of rows affected by the operation. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; // Perform database operations in batches. function executeBatchOperation() { - let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); + let dataAbilityUri = ('dataability:///com.example.myapplication.TestDataAbility'); let DAHelper; try { DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); - if (DAHelper == null) { + if (DAHelper === null) { console.error('DAHelper is null'); return; } } catch (err) { - console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); + console.error('acquireDataAbilityHelper fail, error: ${JSON.stringify(err)}'); return; } let valueBucket = { - "name": "DataAbilityHelperTest", - "age": 24, - "salary": 2024.20, + 'name': 'DataAbilityHelperTest', + 'age': 24, + 'salary': 2024.20, }; let operations = [ { @@ -64,14 +64,14 @@ function executeBatchOperation() { DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { for (let i = 0; i < data.length; i++) { let dataAbilityResult = data[i]; - console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); - console.log('dataAbilityResult.count: ' + dataAbilityResult.count); + console.log('dataAbilityResult.uri: ${dataAbilityResult.uri}'); + console.log('dataAbilityResult.count: ${dataAbilityResult.count}'); } }).catch(err => { - console.error('executeBatch error: ' + JSON.stringify(err)); + console.error('executeBatch error: ${JSON.stringify(err)}'); }); } catch (err) { - console.error('executeBatch error: ' + JSON.stringify(err)); + console.error('executeBatch error: ${JSON.stringify(err)}'); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md index 71b8d529703d28e01072d8f18f92ebe30b82c556..c7462af45a51405c58e90e7811ba2e1078d1d177 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -16,31 +16,31 @@ The **StartAbilityParameter** module defines the parameters for starting an abil **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; let Want = { - bundleName: "com.example.abilityStartSettingApp2", - abilityName: "com.example.abilityStartSettingApp.EntryAbility", -} + bundleName: 'com.example.abilityStartSettingApp2', + abilityName: 'com.example.abilityStartSettingApp.EntryAbility', +}; let abilityStartSetting ={ [featureAbility.AbilityStartSetting.BOUNDS_KEY] : [100,200,300,400], [featureAbility.AbilityStartSetting.WINDOW_MODE_KEY] : featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED, [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, -} +}; let startAbilityParameter = { want : Want, abilityStartSetting : abilityStartSetting -} +}; try { featureAbility.startAbility(startAbilityParameter, (err, data) => { - console.log('errCode : ' + JSON.stringify(err)); - console.log('data : ' + JSON.stringify(data)); + console.log('errCode : ${JSON.stringify(err)}'); + console.log('data : ${JSON.stringify(data)}'); }); } catch(error) { - console.log("startAbility error: " + JSON.stringify(error)); + console.log('startAbility error: ${JSON.stringify(error)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index afb331b3fc2cb610025dd741e94abe0392fe4a5b..dd1a489ac590c1be8c182532aa875ef13b1e6103 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-want.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -4,7 +4,7 @@ Want is a carrier for information transfer between objects (application componen > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 6 and deprecated since API version 9. You are advised to use [@ohos.app.ability.Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. **System capability**: SystemCapability.Ability.AbilityBase @@ -14,10 +14,10 @@ Want is a carrier for information transfer between objects (application componen | bundleName | string | No | Bundle name.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | +| type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags). | -| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | -| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information.
- **component.startup.newRules**: whether to enable the new control rule.
- **moduleName**: module name of the caller. No matter what this field is set to, the correct module name will be sent to the peer.
- **ohos.dlp.params.sandbox**: available only for DLP files. | | entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | | moduleName9+ | string | No | Module to which the ability belongs.| @@ -27,15 +27,15 @@ Want is a carrier for information transfer between objects (application componen ```ts let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry" // moduleName is optional. + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.example.myapplication', + 'abilityName': 'EntryAbility', + 'moduleName': 'entry' // moduleName is optional. }; this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + console.log('error.code = ${error.code}'); + }); ``` - Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility): @@ -46,26 +46,26 @@ Want is a carrier for information transfer between objects (application componen // ... let fd; try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + fd = fileio.openSync('/data/storage/el2/base/haps/pic.png'); } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); + console.log('openSync fail: ${JSON.stringify(e)}'); } let want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.example.myapplication", - "abilityName": "EntryAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} + 'deviceId': '', // An empty deviceId indicates the local device. + 'bundleName': 'com.example.myapplication', + 'abilityName': 'EntryAbility', + 'moduleName': 'entry', // moduleName is optional. + 'parameters': { + 'keyFd':{'type':'FD', 'value':fd} } }; this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + console.log('error.code = ${error.code}'); + }); // ... ``` - For more details and examples, see [Want](../../application-models/want-overview.md). - + diff --git a/en/application-dev/reference/apis/js-apis-inner-app-context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md index ec729194807c24ea49b7b117cb308628c031a75a..4b22df32e51f014e4697c88dab634fa234407760 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -14,9 +14,9 @@ The **Context** object is created in a **featureAbility** and returned through i ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { - console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); + console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}'); }); ``` @@ -40,9 +40,9 @@ If this API is called for the first time, a root directory will be created. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateLocalDir((err, data)=>{ - console.info("getOrCreateLocalDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getOrCreateLocalDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -68,9 +68,9 @@ If this API is called for the first time, a root directory will be created. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { - console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); + console.info('getOrCreateLocalDir data: ${JSON.stringify(data)}'); }); ``` @@ -95,10 +95,10 @@ Verifies whether a specific PID and UID have the given permission. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle.bundleManager'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ - context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ - console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + context.verifyPermission('com.example.permission', {uid:datainfo.appInfo.uid}, (err, data) =>{ + console.info('verifyPermission err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); }); ``` @@ -125,9 +125,9 @@ Verifies whether the current PID and UID have the given permission. This API use ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -context.verifyPermission("com.example.permission", (err, data) =>{ - console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +let context = featureAbility.getContext(); +context.verifyPermission('com.example.permission', (err, data) =>{ + console.info('verifyPermission err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -156,10 +156,10 @@ Verifies whether a specific PID and UID have the given permission. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var Permission = {pid:1}; +let context = featureAbility.getContext(); +let Permission = {pid:1}; context.verifyPermission('com.context.permission',Permission).then((data) => { - console.info("verifyPermission data: " + JSON.stringify(data)); + console.info('verifyPermission data: ${JSON.stringify(data)}'); }); ``` @@ -185,16 +185,16 @@ Requests certain permissions from the system. This API uses an asynchronous call ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.requestPermissionsFromUser( - ["com.example.permission1", - "com.example.permission2", - "com.example.permission3", - "com.example.permission4", - "com.example.permission5"], + ['com.example.permission1', + 'com.example.permission2', + 'com.example.permission3', + 'com.example.permission4', + 'com.example.permission5'], 1, (err, data) => { - console.info("requestPermissionsFromUser err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('requestPermissionsFromUser err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); } ); ``` @@ -225,15 +225,15 @@ Requests certain permissions from the system. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.requestPermissionsFromUser( - ["com.example.permission1", - "com.example.permission2", - "com.example.permission3", - "com.example.permission4", - "com.example.permission5"], + ['com.example.permission1', + 'com.example.permission2', + 'com.example.permission3', + 'com.example.permission4', + 'com.example.permission5'], 1).then((data)=>{ - console.info("requestPermissionsFromUser data: " + JSON.stringify(data)); + console.info('requestPermissionsFromUser data: ${JSON.stringify(data)}'); } ); ``` @@ -258,9 +258,9 @@ Obtains information about the current application. This API uses an asynchronous ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getApplicationInfo((err, data) => { - console.info("getApplicationInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getApplicationInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -284,9 +284,9 @@ Obtains information about the current application. This API uses a promise to re ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getApplicationInfo().then((data) => { - console.info("getApplicationInfo data: " + JSON.stringify(data)); + console.info('getApplicationInfo data: ${JSON.stringify(data)}'); }); ``` @@ -310,9 +310,9 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getBundleName((err, data) => { - console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getBundleName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -336,9 +336,9 @@ Obtains the bundle name of this ability. This API uses a promise to return the r ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getBundleName().then((data) => { - console.info("getBundleName data: " + JSON.stringify(data)); + console.info('getBundleName data: ${JSON.stringify(data)}'); }); ``` @@ -360,9 +360,9 @@ Obtains the display orientation of this ability. This API uses an asynchronous c ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getDisplayOrientation((err, data) => { - console.info("getDisplayOrientation err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getDisplayOrientation err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -384,9 +384,9 @@ Obtains the display orientation of this ability. This API uses a promise to retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getDisplayOrientation().then((data) => { - console.info("getDisplayOrientation data: " + JSON.stringify(data)); + console.info('getDisplayOrientation data: ${JSON.stringify(data)}'); }); ``` @@ -408,9 +408,9 @@ Obtains the external cache directory of the application. This API uses an asynch ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getExternalCacheDir((err, data) => { - console.info("getExternalCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getExternalCacheDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -432,9 +432,9 @@ Obtains the external cache directory of the application. This API uses a promise ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getExternalCacheDir().then((data) => { - console.info("getExternalCacheDir data: " + JSON.stringify(data)); + console.info('getExternalCacheDir data: ${JSON.stringify(data)}'); }); ``` @@ -458,10 +458,10 @@ Sets the display orientation for this ability. This API uses an asynchronous cal ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -var context = featureAbility.getContext(); -var orientation = bundle.DisplayOrientation.UNSPECIFIED; +let context = featureAbility.getContext(); +let orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation, (err) => { - console.info("setDisplayOrientation err: " + JSON.stringify(err)); + console.info('setDisplayOrientation err: ${JSON.stringify(err)}'); }); ``` @@ -485,10 +485,10 @@ Sets the display orientation for this ability. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; -var context = featureAbility.getContext(); -var orientation = bundle.DisplayOrientation.UNSPECIFIED; +let context = featureAbility.getContext(); +let orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation).then((data) => { - console.info("setDisplayOrientation data: " + JSON.stringify(data)); + console.info('setDisplayOrientation data: ${JSON.stringify(data)}'); }); ``` @@ -511,10 +511,10 @@ Sets whether to show this feature at the top of the lock screen so that the feat ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var show = true; +let context = featureAbility.getContext(); +let show = true; context.setShowOnLockScreen(show, (err) => { - console.info("setShowOnLockScreen err: " + JSON.stringify(err)); + console.info('setShowOnLockScreen err: ${JSON.stringify(err)}'); }); ``` @@ -542,10 +542,10 @@ Sets whether to show this feature at the top of the lock screen so that the feat ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var show = true; +let context = featureAbility.getContext(); +let show = true; context.setShowOnLockScreen(show).then((data) => { - console.info("setShowOnLockScreen data: " + JSON.stringify(data)); + console.info('setShowOnLockScreen data: ${JSON.stringify(data)}'); }); ``` @@ -568,10 +568,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var wakeUp = true; +let context = featureAbility.getContext(); +let wakeUp = true; context.setWakeUpScreen(wakeUp, (err) => { - console.info("setWakeUpScreen err: " + JSON.stringify(err)); + console.info('setWakeUpScreen err: ${JSON.stringify(err)}'); }); ``` @@ -599,10 +599,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); -var wakeUp = true; +let context = featureAbility.getContext(); +let wakeUp = true; context.setWakeUpScreen(wakeUp).then((data) => { - console.info("setWakeUpScreen data: " + JSON.stringify(data)); + console.info('setWakeUpScreen data: ${JSON.stringify(data)}'); }); ``` @@ -627,9 +627,9 @@ Obtains information about the current process, including the PID and process nam ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo((err, data) => { - console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getProcessInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -653,9 +653,9 @@ Obtains information about the current process, including the PID and process nam ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo().then((data) => { - console.info("getProcessInfo data: " + JSON.stringify(data)); + console.info('getProcessInfo data: ${JSON.stringify(data)}'); }); ``` @@ -681,9 +681,9 @@ This API is available only to Page abilities. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getElementName((err, data) => { - console.info("getElementName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getElementName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -709,9 +709,9 @@ This API is available only to Page abilities. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getElementName().then((data) => { - console.info("getElementName data: " + JSON.stringify(data)); + console.info('getElementName data: ${JSON.stringify(data)}'); }); ``` @@ -733,9 +733,9 @@ Obtains the name of the current process. This API uses an asynchronous callback ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessName((err, data) => { - console.info("getProcessName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getProcessName err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -759,9 +759,9 @@ Obtains the name of the current process. This API uses a promise to return the r ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessName().then((data) => { - console.info("getProcessName data: " + JSON.stringify(data)); + console.info('getProcessName data: ${JSON.stringify(data)}'); }); ``` @@ -785,9 +785,9 @@ Obtains the bundle name of the caller ability. This API uses an asynchronous cal ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCallingBundle((err, data) => { - console.info("getCallingBundle err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getCallingBundle err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -811,9 +811,9 @@ Obtains the bundle name of the caller ability. This API uses a promise to return ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCallingBundle().then((data) => { - console.info("getCallingBundle data: " + JSON.stringify(data)); + console.info('getCallingBundle data: ${JSON.stringify(data)}'); }); ``` @@ -835,9 +835,9 @@ Obtains the cache directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCacheDir((err, data) => { - console.info("getCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getCacheDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -859,9 +859,9 @@ Obtains the cache directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getCacheDir().then((data) => { - console.info("getCacheDir data: " + JSON.stringify(data)); + console.info('getCacheDir data: ${JSON.stringify(data)}'); }); ``` @@ -883,9 +883,9 @@ Obtains the file directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getFilesDir((err, data) => { - console.info("getFilesDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getFilesDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -907,9 +907,9 @@ Obtains the file directory of the application in the internal storage. This API ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getFilesDir().then((data) => { - console.info("getFilesDir data: " + JSON.stringify(data)); + console.info('getFilesDir data: ${JSON.stringify(data)}'); }); ``` @@ -933,9 +933,9 @@ If the distributed file path does not exist, the system will create one and retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateDistributedDir((err, data) => { - console.info("getOrCreateDistributedDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getOrCreateDistributedDir err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -959,9 +959,9 @@ If the distributed file path does not exist, the system will create one and retu ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getOrCreateDistributedDir().then((data) => { - console.info("getOrCreateDistributedDir data: " + JSON.stringify(data)); + console.info('getOrCreateDistributedDir data: ${JSON.stringify(data)}'); }); ``` @@ -983,9 +983,9 @@ Obtains the application type. This API uses an asynchronous callback to return t ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppType((err, data) => { - console.info("getAppType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getAppType err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -1007,9 +1007,9 @@ Obtains the application type. This API uses a promise to return the result. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppType().then((data) => { - console.info("getAppType data: " + JSON.stringify(data)); + console.info('getAppType data: ${JSON.stringify(data)}'); }); ``` @@ -1031,9 +1031,9 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getHapModuleInfo((err, data) => { - console.info("getHapModuleInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getHapModuleInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -1055,9 +1055,9 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getHapModuleInfo().then((data) => { - console.info("getHapModuleInfo data: " + JSON.stringify(data)); + console.info('getHapModuleInfo data: ${JSON.stringify(data)}'); }); ``` @@ -1079,9 +1079,9 @@ Obtains the version information of the application. This API uses an asynchronou ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppVersionInfo((err, data) => { - console.info("getAppVersionInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getAppVersionInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -1103,9 +1103,9 @@ Obtains the version information of the application. This API uses a promise to r ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAppVersionInfo().then((data) => { - console.info("getAppVersionInfo data: " + JSON.stringify(data)); + console.info('getAppVersionInfo data: ${JSON.stringify(data)}'); }); ``` @@ -1127,9 +1127,9 @@ Obtains information about this ability. This API uses an asynchronous callback t ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAbilityInfo((err, data) => { - console.info("getAbilityInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('getAbilityInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -1151,9 +1151,9 @@ Obtains information about this ability. This API uses a promise to return the re ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getAbilityInfo().then((data) => { - console.info("getAbilityInfo data: " + JSON.stringify(data)); + console.info('getAbilityInfo data: ${JSON.stringify(data)}'); }); ``` @@ -1175,7 +1175,7 @@ Obtains the context of the application. ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext().getApplicationContext(); +let context = featureAbility.getContext().getApplicationContext(); ``` ## Context.isUpdatingConfigurations7+ @@ -1196,9 +1196,9 @@ Checks whether the configuration of this ability is being updated. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.isUpdatingConfigurations((err, data) => { - console.info("isUpdatingConfigurations err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + console.info('isUpdatingConfigurations err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); }); ``` @@ -1220,9 +1220,9 @@ Checks whether the configuration of this ability is being updated. This API uses ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.isUpdatingConfigurations().then((data) => { - console.info("isUpdatingConfigurations data: " + JSON.stringify(data)); + console.info('isUpdatingConfigurations data: ${JSON.stringify(data)}'); }); ``` @@ -1244,9 +1244,9 @@ Notifies the system of the time required to draw this page function. This API us ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.printDrawnCompleted((err) => { - console.error('printDrawnCompleted err: ' + JSON.stringify(err)); + console.error('printDrawnCompleted err: ${JSON.stringify(err)}'); }); ``` @@ -1268,9 +1268,9 @@ Notifies the system of the time required to draw this page function. This API us ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.printDrawnCompleted().then((data) => { - console.info("printDrawnCompleted data: " + JSON.stringify(data)); + console.info('printDrawnCompleted data: ${JSON.stringify(data)}'); }); ``` @@ -1293,13 +1293,3 @@ context.printDrawnCompleted().then((data) => { | requestCode | Read-only | number | Yes | Request code passed.| | permissions | Read-only | Array\ | Yes | Permissions requested. | | authResults | Read-only | Array\ | Yes | Permission request result. | - -## AppVersionInfo7+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Readable | Writable | Description | -| ----------- | ------ | ---- | ---- | ------- | -| appName | string | Yes | No | Module name. | -| versionCode | number | Yes | No | Module description.| -| versionName | string | Yes | No | Module description ID.| diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md index 351d6ad145824d0eba37a3a1eadc846034763c97..d210666803caa4e6d7e2571badacca9072f725a6 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -3,10 +3,8 @@ The **ProcessInfo** module defines process information. You can use [getProcessInfo](js-apis-inner-app-context.md#contextgetprocessinfo7) to obtain information about the processes running on the current ability. > **NOTE** -> -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs of this module can be used only in the FA model. +> +> The initial APIs of this module are supported since API version 7. The APIs of this module can be used only in the FA model. Newly added APIs will be marked with a superscript to indicate their earliest API version. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -19,10 +17,12 @@ The **ProcessInfo** module defines process information. You can use [getProcessI ```ts import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext(); +let context = featureAbility.getContext(); context.getProcessInfo((err, data) => { - console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); - let pid = data.pid; - let processName = data.processName; + if (err.code !== 0) { + console.info('getProcessInfo err: ${JSON.stringify(err)}, data: ${JSON.stringify(data)}'); + let pid = data.pid; + let processName = data.processName; + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 70aefed8b0d382421459175f3b19e10304917c3b..24aef5e428f373b57d1c1208d9005eba1f3b689d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -38,17 +38,17 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor, (err : any) => { - console.info("addAbilityMonitor callback"); + console.info('addAbilityMonitor callback'); }); ``` @@ -78,17 +78,17 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor).then(() => { - console.info("addAbilityMonitor promise"); + console.info('addAbilityMonitor promise'); }); ``` @@ -113,17 +113,17 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { - console.info("removeAbilityMonitor callback"); + console.info('removeAbilityMonitor callback'); }); ``` @@ -153,17 +153,17 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.removeAbilityMonitor(monitor).then(() => { - console.info("removeAbilityMonitor promise"); + console.info('removeAbilityMonitor promise'); }); ``` @@ -188,17 +188,17 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => { - console.info("waitAbilityMonitor callback"); + console.info('waitAbilityMonitor callback'); }); ``` @@ -225,17 +225,17 @@ let abilityDelegator; let timeout = 100; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => { - console.info("waitAbilityMonitor callback"); + console.info('waitAbilityMonitor callback'); }); ``` @@ -268,17 +268,17 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - abilityName: "abilityname", + abilityName: 'abilityname', onAbilityCreate: onAbilityCreateCallback -} +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { - console.info("waitAbilityMonitor promise"); + console.info('waitAbilityMonitor promise'); }); ``` @@ -333,10 +333,10 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; let state = abilityDelegator.getAbilityState(ability); - console.info("getAbilityState" + state); + console.info('getAbilityState ${state}'); }); ``` @@ -362,7 +362,7 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; }); ``` @@ -389,7 +389,7 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility().then((data : any) => { - console.info("getCurrentTopAbility promise"); + console.info('getCurrentTopAbility promise'); ability = data; }); ``` @@ -414,13 +414,13 @@ Starts an ability. This API uses an asynchronous callback to return the result. ```ts let abilityDelegator; let want = { - bundleName: "bundleName", - abilityName: "abilityName" + bundleName: 'bundleName', + abilityName: 'abilityName' }; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.startAbility(want, (err : any, data : any) => { - console.info("startAbility callback"); + console.info('startAbility callback'); }); ``` @@ -449,13 +449,13 @@ Starts an ability. This API uses a promise to return the result. ```ts let abilityDelegator; let want = { - bundleName: "bundleName", - abilityName: "abilityName" + bundleName: 'bundleName', + abilityName: 'abilityName' }; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.startAbility(want).then((data: any) => { - console.info("startAbility promise"); + console.info('startAbility promise'); }); ``` @@ -482,10 +482,10 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; abilityDelegator.doAbilityForeground(ability, (err : any, data : any) => { - console.info("doAbilityForeground callback"); + console.info('doAbilityForeground callback'); }); }); ``` @@ -518,10 +518,10 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; abilityDelegator.doAbilityForeground(ability).then((data : any) => { - console.info("doAbilityForeground promise"); + console.info('doAbilityForeground promise'); }); }); ``` @@ -549,10 +549,10 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; abilityDelegator.doAbilityBackground(ability, (err : any, data : any) => { - console.info("doAbilityBackground callback"); + console.info('doAbilityBackground callback'); }); }); ``` @@ -585,10 +585,10 @@ let ability; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.getCurrentTopAbility((err : any, data : any) => { - console.info("getCurrentTopAbility callback"); + console.info('getCurrentTopAbility callback'); ability = data; abilityDelegator.doAbilityBackground(ability).then((data : any) => { - console.info("doAbilityBackground promise"); + console.info('doAbilityBackground promise'); }); }); ``` @@ -611,7 +611,7 @@ Prints log information to the unit test console. ```ts let abilityDelegator; -let msg = "msg"; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.printSync(msg); @@ -636,11 +636,11 @@ Prints log information to the unit test console. This API uses an asynchronous c ```ts let abilityDelegator; -let msg = "msg"; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.print(msg, (err : any) => { - console.info("print callback"); + console.info('print callback'); }); ``` @@ -668,11 +668,11 @@ Prints log information to the unit test console. This API uses a promise to retu ```ts let abilityDelegator; -let msg = "msg"; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.print(msg).then(() => { - console.info("print promise"); + console.info('print promise'); }); ``` @@ -695,11 +695,11 @@ Executes a shell command. This API uses an asynchronous callback to return the r ```ts let abilityDelegator; -let cmd = "cmd"; +let cmd = 'cmd'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { - console.info("executeShellCommand callback"); + console.info('executeShellCommand callback'); }); ``` @@ -723,12 +723,12 @@ Executes a shell command with the timeout period specified. This API uses an asy ```ts let abilityDelegator; -let cmd = "cmd"; +let cmd = 'cmd'; let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { - console.info("executeShellCommand callback"); + console.info('executeShellCommand callback'); }); ``` @@ -757,12 +757,12 @@ Executes a shell command with the timeout period specified. This API uses a prom ```ts let abilityDelegator; -let cmd = "cmd"; +let cmd = 'cmd'; let timeout = 100; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { - console.info("executeShellCommand promise"); + console.info('executeShellCommand promise'); }); ``` @@ -786,11 +786,11 @@ Finishes the test and prints log information to the unit test console. This API ```ts let abilityDelegator; -let msg = "msg"; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.finishTest(msg, 0, (err : any) => { - console.info("finishTest callback"); + console.info('finishTest callback'); }); ``` @@ -819,11 +819,11 @@ Finishes the test and prints log information to the unit test console. This API ```ts let abilityDelegator; -let msg = "msg"; +let msg = 'msg'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.finishTest(msg, 0).then(() => { - console.info("finishTest promise"); + console.info('finishTest promise'); }); ``` @@ -848,13 +848,13 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes let abilityDelegator; let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityStageMonitor(monitor, (err : any) => { - console.info("addAbilityStageMonitor callback"); + console.info('addAbilityStageMonitor callback'); }); ``` @@ -884,13 +884,13 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes let abilityDelegator; let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityStageMonitor(monitor).then(() => { - console.info("addAbilityStageMonitor promise"); + console.info('addAbilityStageMonitor promise'); }); ``` @@ -915,13 +915,13 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP let abilityDelegator; let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => { - console.info("removeAbilityStageMonitor callback"); + console.info('removeAbilityStageMonitor callback'); }); ``` @@ -951,13 +951,13 @@ Removes an **AbilityStageMonitor** object from the application memory. This API let abilityDelegator; let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.removeAbilityStageMonitor(monitor).then(() => { - console.info("removeAbilityStageMonitor promise"); + console.info('removeAbilityStageMonitor promise'); }); ``` @@ -982,17 +982,17 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => { - console.info("waitAbilityStageMonitor callback"); + console.info('waitAbilityStageMonitor callback'); }); ``` @@ -1023,17 +1023,17 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A let abilityDelegator; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor).then((data : any) => { - console.info("waitAbilityStageMonitor promise"); + console.info('waitAbilityStageMonitor promise'); }); ``` @@ -1060,16 +1060,16 @@ let abilityDelegator; let timeout = 100; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } let monitor = { - moduleName: "moduleName", - srcEntrance: "srcEntrance", -} + moduleName: 'moduleName', + srcEntrance: 'srcEntrance', +}; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : any) => { - console.info("waitAbilityStageMonitor callback"); + console.info('waitAbilityStageMonitor callback'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index 737a5bc8c3ba7daa37af06f92a843fea27b40b8a..b6c5bc7be8e686a99baf3211f06f12bb48818c9a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -28,5 +28,5 @@ Describes the ability delegator arguments. ```ts import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; -var args = AbilityDelegatorRegistry.getArguments(); +let args = AbilityDelegatorRegistry.getArguments(); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md index 3185bd98b51260135e6b3bf1524d6bab8187d2bf..1069fcf2d43c9675ff70efd2c0e2756475db312e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -19,6 +19,7 @@ Describes an ability monitor. | Name | Type | Readable| Writable| Description | | ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | | abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor.| +| moduleName? | string | Yes | Yes | Name of the module bound to the ability monitor.| | onAbilityCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| | onAbilityForeground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the foreground.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| | onAbilityBackground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the background.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| @@ -33,16 +34,17 @@ Describes an ability monitor. import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { - console.info("onAbilityCreateCallback"); + console.info('onAbilityCreateCallback'); } -var monitor = { - abilityName: "abilityname", +let monitor = { + abilityName: 'abilityname', + moduleName: "moduleName", onAbilityCreate: onAbilityCreateCallback -} +}; -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor, (err : any) => { - console.info("addAbilityMonitor callback"); + console.info('addAbilityMonitor callback'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index e076913ed7dda35586084acdad77df1e94720e83..8340c33dbaa77848d90200e37b5ee309efe53697 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -31,15 +31,15 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( import abilitymanager from '@ohos.app.ability.abilityManager'; abilitymanager.getAbilityRunningInfos((err,data) => { - console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); + console.log('getAbilityRunningInfos err: ${err}, data: ${JSON.stringify(data)}'); for (let i = 0; i < data.length; i++) { let abilityinfo = data[i]; - console.log("abilityinfo.ability: " + JSON.stringify(abilityinfo.ability)); - console.log("abilityinfo.pid: " + JSON.stringify(abilityinfo.pid)); - console.log("abilityinfo.uid: " + JSON.stringify(abilityinfo.uid)); - console.log("abilityinfo.processName: " + JSON.stringify(abilityinfo.processName)); - console.log("abilityinfo.startTime: " + JSON.stringify(abilityinfo.startTime)); - console.log("abilityinfo.abilityState: " + JSON.stringify(abilityinfo.abilityState)); + console.log('abilityinfo.ability: ${JSON.stringify(abilityinfo.ability)}'); + console.log('abilityinfo.pid: ${JSON.stringify(abilityinfo.pid)}'); + console.log('abilityinfo.uid: ${JSON.stringify(abilityinfo.uid)}'); + console.log('abilityinfo.processName: ${JSON.stringify(abilityinfo.processName)}'); + console.log('abilityinfo.startTime: ${JSON.stringify(abilityinfo.startTime)}'); + console.log('abilityinfo.abilityState: ${JSON.stringify(abilityinfo.abilityState)}'); } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 5237e134c8500cec81840e14c7d5153ee59d27a0..4d537d507764cd540e122beebd995f442d3a00fc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -1,6 +1,6 @@ # AbilityStageContext -The **AbilityStageContext** module, inherited from [Context](js-apis-application-context.md), implements the context of an ability stage. +The **AbilityStageContext** module, inherited from [Context](js-apis-inner-application-context.md), implements the context of an ability stage. This module provides APIs for accessing a specific ability stage. You can use the APIs to obtain the **ModuleInfo** object and environment configuration of an ability stage. @@ -29,5 +29,5 @@ class MyAbilityStage extends AbilityStage { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md index a8b67e09b0d6809cf9b79e08e09f466a62d46b44..896b619f524ccc98b1150949b44fba3878bd268a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -14,12 +14,12 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let monitor = { - moduleName: "feature_as1", - srcEntrance: "./ets/Application/MyAbilityStage.ts", + moduleName: 'feature_as1', + srcEntrance: './ets/Application/MyAbilityStage.ts', }; let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { - console.info("stageMonitor waitAbilityStageMonitor, abilityStage = " + JSON.stringify(data)); + console.info('stageMonitor waitAbilityStageMonitor, abilityStage = ${JSON.stringify(data)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md index 63336a289f7804e9f69f1f0cf7db95b19a01d080..1263f44e2db490c648decd54b93ba831a9a57e72 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -15,7 +15,7 @@ You can use the APIs of this module to configure the concerned information, obta Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. ```ts -import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'; let axContext; class EntryAbility extends AccessibilityExtensionAbility { onConnect(): void { @@ -103,10 +103,10 @@ try { axContext.setTargetBundleName(targetNames).then(() => { console.info('set target bundle names success'); }).catch((err) => { - console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + console.error('failed to set target bundle names, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); + console.error('failed to set target bundle names, because ${JSON.stringify(exception)}'); }; ``` @@ -132,13 +132,13 @@ let targetNames = ['com.ohos.xyz']; try { axContext.setTargetBundleName(targetNames, (err, data) => { if (err) { - console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + console.error('failed to set target bundle names, because ${JSON.stringify(err)}'); return; } console.info('set target bundle names success'); }); } catch (exception) { - console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); + console.error('failed to set target bundle names, because ${JSON.stringify(exception)}'); }; ``` @@ -179,10 +179,10 @@ try { focusElement = data; console.log('get focus element success'); }).catch((err) => { - console.error('failed to get focus element, because ' + JSON.stringify(err)); + console.error('failed to get focus element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.error('failed to get focus element, because ' + JSON.stringify(exception)); + console.error('failed to get focus element, because ${JSON.stringify(exception)}'); } ``` @@ -215,14 +215,14 @@ let focusElement; try { axContext.getFocusElement((err, data) => { if (err) { - console.error('failed to get focus element, because ' + JSON.stringify(err)); + console.error('failed to get focus element, because ${JSON.stringify(err)}'); return; } focusElement = data; console.info('get focus element success'); }); } catch (exception) { - console.error('failed to get focus element, because ' + JSON.stringify(exception)); + console.error('failed to get focus element, because ${JSON.stringify(exception)}'); } ``` @@ -249,14 +249,14 @@ let isAccessibilityFocus = true; try { axContext.getFocusElement(isAccessibilityFocus, (err, data) => { if (err) { - console.error('failed to get focus element, because ' + JSON.stringify(err)); + console.error('failed to get focus element, because ${JSON.stringify(err)}'); return; } focusElement = data; console.info('get focus element success'); }); } catch (exception) { - console.error('failed to get focus element, because ' + JSON.stringify(exception)); + console.error('failed to get focus element, because ${JSON.stringify(exception)}'); } ``` ## AccessibilityExtensionContext.getWindowRootElement @@ -296,10 +296,10 @@ try { rootElement = data; console.log('get root element of the window success'); }).catch((err) => { - console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.error('failed to get root element of the window, ' + JSON.stringify(exception)); + console.error('failed to get root element of the window, ${JSON.stringify(exception)}'); } ``` @@ -332,14 +332,14 @@ let rootElement; try { axContext.getWindowRootElement((err, data) => { if (err) { - console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); return; } rootElement = data; console.info('get root element of the window success'); }); } catch (exception) { - console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); + console.error('failed to get root element of the window, because ${JSON.stringify(exception)}'); } ``` @@ -374,14 +374,14 @@ let windowId = 10; try { axContext.getWindowRootElement(windowId, (err, data) => { if (err) { - console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + console.error('failed to get root element of the window, because ${JSON.stringify(err)}'); return; } rootElement = data; console.info('get root element of the window success'); }); } catch (exception) { - console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); + console.error('failed to get root element of the window, because ${JSON.stringify(exception)}'); } ``` @@ -422,10 +422,10 @@ try { windows = data; console.log('get windows success'); }).catch((err) => { - console.error('failed to get windows, because ' + JSON.stringify(err)); + console.error('failed to get windows, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.error('failed to get windows, because ' + JSON.stringify(exception)); + console.error('failed to get windows, because ${JSON.stringify(exception)}'); } ``` @@ -458,14 +458,14 @@ let windows; try { axContext.getWindows((err, data) => { if (err) { - console.error('failed to get windows, because ' + JSON.stringify(err)); + console.error('failed to get windows, because ${JSON.stringify(err)}'); return; } windows = data; console.info('get windows success'); }); } catch (exception) { - console.error('failed to get windows, because ' + JSON.stringify(exception)); + console.error('failed to get windows, because ${JSON.stringify(exception)}'); } ``` @@ -500,14 +500,14 @@ let displayId = 10; try { axContext.getWindows(displayId, (err, data) => { if (err) { - console.error('failed to get windows, because ' + JSON.stringify(err)); + console.error('failed to get windows, because ${JSON.stringify(err)}'); return; } windows = data; console.info('get windows success'); }); } catch (exception) { - console.error('failed to get windows, because ' + JSON.stringify(exception)); + console.error('failed to get windows, because ${JSON.stringify(exception)}'); } ``` @@ -542,7 +542,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes **Example** ```ts -import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePath from '@ohos.accessibility.GesturePath'; import GesturePoint from '@ohos.accessibility.GesturePoint'; let gesturePath = new GesturePath.GesturePath(100); try { @@ -553,10 +553,10 @@ try { axContext.injectGesture(gesturePath).then(() => { console.info('inject gesture success'); }).catch((err) => { - console.error('failed to inject gesture, because ' + JSON.stringify(err)); + console.error('failed to inject gesture, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.error('failed to inject gesture, because ' + JSON.stringify(exception)); + console.error('failed to inject gesture, because ${JSON.stringify(exception)}'); } ``` ## AccessibilityExtensionContext.injectGesture @@ -585,7 +585,7 @@ For details about the error codes, see [Accessibility Error Codes](../errorcodes **Example** ```ts -import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePath from '@ohos.accessibility.GesturePath'; import GesturePoint from '@ohos.accessibility.GesturePoint'; let gesturePath = new GesturePath.GesturePath(100); try { @@ -595,13 +595,13 @@ try { } axContext.injectGesture(gesturePath, (err, data) => { if (err) { - console.error('failed to inject gesture, because ' + JSON.stringify(err)); + console.error('failed to inject gesture, because ${JSON.stringify(err)}'); return; } console.info('inject gesture success'); }); } catch (exception) { - console.error('failed to inject gesture, because ' + JSON.stringify(exception)); + console.error('failed to inject gesture, because ${JSON.stringify(exception)}'); } ``` ## AccessibilityElement9+ @@ -633,7 +633,7 @@ rootElement.attributeNames().then((data) => { console.log('get attribute names success'); attributeNames = data; }).catch((err) => { - console.log('failed to get attribute names, because ' + JSON.stringify(err)); + console.log('failed to get attribute names, because ${JSON.stringify(err)}'); }); ``` ## attributeNames @@ -657,7 +657,7 @@ let rootElement; let attributeNames; rootElement.attributeNames((err, data) => { if (err) { - console.error('failed to get attribute names, because ' + JSON.stringify(err)); + console.error('failed to get attribute names, because ${JSON.stringify(err)}'); return; } attributeNames = data; @@ -703,10 +703,10 @@ try { console.log('get attribute value by name success'); attributeValue = data; }).catch((err) => { - console.log('failed to get attribute value, because ' + JSON.stringify(err)); + console.log('failed to get attribute value, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to get attribute value, because ' + JSON.stringify(exception)); + console.log('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` ## AccessibilityElement.attributeValue @@ -742,14 +742,14 @@ let attributeName = 'name'; try { rootElement.attributeValue(attributeName, (err, data) => { if (err) { - console.error('failed to get attribute value, because ' + JSON.stringify(err)); + console.error('failed to get attribute value, because ${JSON.stringify(err)}'); return; } attributeValue = data; console.info('get attribute value success'); }); } catch (exception) { - console.log('failed to get attribute value, because ' + JSON.stringify(exception)); + console.log('failed to get attribute value, because ${JSON.stringify(exception)}'); } ``` ## actionNames @@ -775,7 +775,7 @@ rootElement.actionNames().then((data) => { console.log('get action names success'); actionNames = data; }).catch((err) => { - console.log('failed to get action names because ' + JSON.stringify(err)); + console.log('failed to get action names because ${JSON.stringify(err)}'); }); ``` ## actionNames @@ -799,7 +799,7 @@ let rootElement; let actionNames; rootElement.actionNames((err, data) => { if (err) { - console.error('failed to get action names, because ' + JSON.stringify(err)); + console.error('failed to get action names, because ${JSON.stringify(err)}'); return; } actionNames = data; @@ -843,10 +843,10 @@ try { rootElement.performAction('action').then((data) => { console.info('perform action success'); }).catch((err) => { - console.log('failed to perform action, because ' + JSON.stringify(err)); + console.log('failed to perform action, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to perform action, because ' + JSON.stringify(exception)); + console.log('failed to perform action, because ${JSON.stringify(exception)}'); } ``` ## performAction @@ -879,13 +879,13 @@ let rootElement; try { rootElement.performAction('action', (err, data) => { if (err) { - console.error('failed to perform action, because ' + JSON.stringify(err)); + console.error('failed to perform action, because ${JSON.stringify(err)}'); return; } console.info('perform action success'); }); } catch (exception) { - console.log('failed to perform action, because ' + JSON.stringify(exception)); + console.log('failed to perform action, because ${JSON.stringify(exception)}'); } ``` ## performAction @@ -923,13 +923,13 @@ let parameters = { try { rootElement.performAction(actionName, parameters, (err, data) => { if (err) { - console.error('failed to perform action, because ' + JSON.stringify(err)); + console.error('failed to perform action, because ${JSON.stringify(err)}'); return; } console.info('perform action success'); }); } catch (exception) { - console.log('failed to perform action, because ' + JSON.stringify(exception)); + console.log('failed to perform action, because ${JSON.stringify(exception)}'); } ``` ## findElement('content') @@ -965,10 +965,10 @@ try { elements = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element, because ' + JSON.stringify(err)); + console.log('failed to find element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to find element, because ' + JSON.stringify(exception)); + console.log('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('content') @@ -997,14 +997,14 @@ let elements; try { rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element, because ' + JSON.stringify(err)); + console.error('failed to find element, because ${JSON.stringify(err)}'); return; } elements = data; console.info('find element success'); }); } catch (exception) { - console.log('failed to find element, because ' + JSON.stringify(exception)); + console.log('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusType') @@ -1040,10 +1040,10 @@ try { element = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element, because ' + JSON.stringify(err)); + console.log('failed to find element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to find element, because ' + JSON.stringify(exception)); + console.log('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusType') @@ -1072,14 +1072,14 @@ let element; try { rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element, because ' + JSON.stringify(err)); + console.error('failed to find element, because ${JSON.stringify(err)}'); return; } element = data; console.info('find element success'); }); } catch (exception) { - console.log('failed to find element, because ' + JSON.stringify(exception)); + console.log('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusDirection') @@ -1115,10 +1115,10 @@ try { element = data; console.log('find element success'); }).catch((err) => { - console.log('failed to find element, because ' + JSON.stringify(err)); + console.log('failed to find element, because ${JSON.stringify(err)}'); }); } catch (exception) { - console.log('failed to find element, because ' + JSON.stringify(exception)); + console.log('failed to find element, because ${JSON.stringify(exception)}'); } ``` ## findElement('focusDirection') @@ -1147,13 +1147,13 @@ let elements; try { rootElement.findElement(type, condition, (err, data) => { if (err) { - console.error('failed to find element, because ' + JSON.stringify(err)); + console.error('failed to find element, because ${JSON.stringify(err)}'); return; } elements = data; console.info('find element success'); }); } catch (exception) { - console.log('failed to find element, because ' + JSON.stringify(exception)); + console.log('failed to find element, because ${JSON.stringify(exception)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md index c281c62ff040c74bdc84def40b9db824ce95492a..23328be8945eb8c1aa55ba993077ff64f99b8fcc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md @@ -15,20 +15,19 @@ The **AppStateData** module defines the application state data, which can be obt **Example** ```ts -import appManager from "@ohos.app.ability.appManager" +import appManager from '@ohos.app.ability.appManager'; function getForegroundAppInfos() { appManager.getForegroundApplications((error, data) => { if (error && error.code) { - console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } for (let i = 0; i < data.length; i++) { let appStateData = data[i]; - console.log('appStateData.bundleName: ' + appStateData.bundleName); - console.log('appStateData.uid: ' + appStateData.uid); - console.log('appStateData.state: ' + appStateData.state); + console.log('appStateData.bundleName: ${appStateData.bundleName}'); + console.log('appStateData.uid: ${appStateData.uid}'); + console.log('appStateData.state: ${appStateData.state}'); } }); } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index 73b2a329f018d64bf93ac8f64ece86792e4eff59..c19d499f4a28f1d68817ef517ebeb0dc5ff0e807 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -15,9 +15,9 @@ Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContex let applicationContext = this.context.getApplicationContext(); ``` -## ApplicationContext.registerAbilityLifecycleCallback +## ApplicationContext.on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback) -registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number**; +on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): **number**; Registers a listener to monitor the ability lifecycle of the application. @@ -27,6 +27,7 @@ Registers a listener to monitor the ability lifecycle of the application. | Name | Type | Mandatory| Description | | ------------------------ | -------- | ---- | ------------------------------ | +| type | 'abilityLifecycle' | Yes | Event type.| | callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.| **Return value** @@ -40,56 +41,56 @@ Registers a listener to monitor the ability lifecycle of the application. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var lifecycleId; +let lifecycleId; export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate'); let AbilityLifecycleCallback = { onAbilityCreate(ability) { - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityCreate ability: ${ability}'); }, onWindowStageCreate(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageCreate ability: ${ability}'); + console.log('AbilityLifecycleCallback onWindowStageCreate windowStage: ${windowStage}'); }, onWindowStageActive(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageActive ability: ${ability}'); + console.log('AbilityLifecycleCallback onWindowStageActive windowStage: ${windowStage}'); }, onWindowStageInactive(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageInactive ability: ${ability}'); + console.log('AbilityLifecycleCallback onWindowStageInactive windowStage: ${windowStage}'); }, onWindowStageDestroy(ability, windowStage) { - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + console.log('AbilityLifecycleCallback onWindowStageDestroy ability: ${ability}'); + console.log('AbilityLifecycleCallback onWindowStageDestroy windowStage: ${windowStage}'); }, onAbilityDestroy(ability) { - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityDestroy ability: ${ability}'); }, onAbilityForeground(ability) { - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityForeground ability: ${ability}'); }, onAbilityBackground(ability) { - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityBackground ability: ${ability}'); }, onAbilityContinue(ability) { - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); + console.log('AbilityLifecycleCallback onAbilityContinue ability: ${ability}'); } } // 1. Obtain applicationContext through the context attribute. let applicationContext = this.context.getApplicationContext(); // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + lifecycleId = applicationContext.on('abilityLifecycle', AbilityLifecycleCallback); + console.log('registerAbilityLifecycleCallback number: ' + JSON.stringify(lifecycleId)); } } ``` -## ApplicationContext.unregisterAbilityLifecycleCallback +## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback) -unregisterAbilityLifecycleCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; +off(type: 'abilityLifecycle', callbackId: **number**, callback: AsyncCallback<**void**>): **void**; Deregisters the listener that monitors the ability lifecycle of the application. @@ -99,6 +100,7 @@ Deregisters the listener that monitors the ability lifecycle of the application. | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | +| type | 'abilityLifecycle' | Yes | Event type.| | callbackId | number | Yes | ID of the listener to deregister.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -107,22 +109,53 @@ Deregisters the listener that monitors the ability lifecycle of the application. ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var lifecycleId; +let lifecycleId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + console.log('stage applicationContext: ' + applicationContext); + applicationContext.off(type: 'abilityLifecycle', lifecycleId, (error, data) => { + console.log('unregisterAbilityLifecycleCallback success, err: ' + JSON.stringify(error)); }); } } ``` -## ApplicationContext.registerEnvironmentCallback +## ApplicationContext.off(type: 'abilityLifecycle', callbackId: number) -registerEnvironmentCallback(callback: EnvironmentCallback): **number**; +off(type: 'abilityLifecycle', callbackId: **number**): **void**; + +Deregisters the listener that monitors the ability lifecycle of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | -------------------------- | +| type | 'abilityLifecycle' | Yes | Event type.| +| callbackId | number | Yes | ID of the listener to deregister.| + +**Example** + +```ts +import Ability from '@ohos.app.ability.UIAbility'; + +let lifecycleId; + +export default class MyAbility extends Ability { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + console.log('stage applicationContext: ' + applicationContext); + applicationContext.off(type: 'abilityLifecycle', lifecycleId); + } +} +``` + +## ApplicationContext.on(type: 'environment', callback: EnvironmentCallback) + +on(type: 'environment', callback: EnvironmentCallback): **number**; Registers a listener for system environment changes. This API uses an asynchronous callback to return the result. @@ -132,6 +165,7 @@ Registers a listener for system environment changes. This API uses an asynchrono | Name | Type | Mandatory| Description | | ------------------------ | -------- | ---- | ------------------------------ | +| type | 'environment' | Yes | Event type.| | callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| **Return value** @@ -145,32 +179,32 @@ Registers a listener for system environment changes. This API uses an asynchrono ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbility onCreate") + console.log('MyAbility onCreate') globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ - console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + console.log('onConfigurationUpdated config:' + JSON.stringify(config)); }, onMemoryLevel(level){ - console.log("onMemoryLevel level:" + level); + console.log('onMemoryLevel level:' + level); } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); - console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + callbackId = applicationContext.on('environment', EnvironmentCallback); + console.log('registerEnvironmentCallback number: ' + JSON.stringify(callbackId)); } } ``` -## ApplicationContext.unregisterEnvironmentCallback +## ApplicationContext.off(type: 'environment', callbackId: number, callback: AsyncCallback) -unregisterEnvironmentCallback(callbackId: **number**, callback: AsyncCallback<**void**>): **void**; +off(type: 'environment', callbackId: **number**, callback: AsyncCallback<**void**>): **void**; Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. @@ -180,6 +214,7 @@ Deregisters the listener for system environment changes. This API uses an asynch | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | +| type | 'environment' | Yes | Event type.| | callbackId | number | Yes | ID of the listener to deregister. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -188,14 +223,148 @@ Deregisters the listener for system environment changes. This API uses an asynch ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -var callbackId; +let callbackId; export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + applicationContext.off('environment', callbackId, (error, data) => { + console.log('unregisterEnvironmentCallback success, err: ' + JSON.stringify(error)); }); } } ``` + +## ApplicationContext.off(type: 'environment', callbackId: number) + +off(type: 'environment', callbackId: **number**, callback: AsyncCallback<**void**>): **void**; + +Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | -------------------------- | +| type | 'environment' | Yes | Event type.| +| callbackId | number | Yes | ID of the listener to deregister. | + +**Example** + +```ts +import Ability from '@ohos.app.ability.UIAbility'; + +let callbackId; + +export default class MyAbility extends Ability { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.off('environment', callbackId); + } +} +``` + +## ApplicationContext.getRunningProcessInformation9+ + +getRunningProcessInformation(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Example** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.getRunningProcessInformation().then((data) => { + console.log('The process running information is: ${JSON.stringify(data)}'); +}).catch((error) => { + console.log('error: ${JSON.stringify(error)}'); +}); +``` + +## ApplicationContext.getRunningProcessInformation9+ + +getRunningProcessInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +|AsyncCallback\> | Callback used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Example** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.getRunningProcessInformation((err, data) => { + if (err.code !== 0) { + console.error('getRunningProcessInformation faile, err: ${JSON.stringify(err)}'); + } else { + console.log('The process running information is: ${JSON.stringify(data)}'); + } +}) +``` + +## ApplicationContext.killAllProcesses9+ + +killAllProcesses(): Promise\; + +Kills all the processes where the application is located. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.killAllProcesses(); +``` + +## ApplicationContext.killAllProcesses9+ + +killAllProcesses(callback: AsyncCallback\); + +Kills all the processes where the application is located. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +|AsyncCallback\ | Callback used to return the result.| + +**Example** + +```ts +let applicationContext = this.context.getApplicationContext(); +applicationContext.killAllProcesses(err => { + console.error('killAllProcesses result: ${JSON.stringify(err)}'); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md index d8e4688d78931edf9018eed4c5a092a84f9d15e8..336811e398b21be7ac11e73047fdee15be67fedc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -16,24 +16,24 @@ The **ApplicationStateObserver** module defines an observer to listen for applic **Example** ```ts -import appManager from "@ohos.app.ability.appManager"; +import appManager from '@ohos.app.ability.appManager'; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { - console.log('onForegroundApplicationChanged appStateData: ' + JSON.stringify(appStateData)); + console.log('onForegroundApplicationChanged appStateData: ${JSON.stringify(appStateData)}'); }, onAbilityStateChanged(abilityStateData) { - console.log('onAbilityStateChanged onAbilityStateChanged: ' + JSON.stringify(abilityStateData)); + console.log('onAbilityStateChanged onAbilityStateChanged: ${JSON.stringify(abilityStateData)}'); }, onProcessCreated(processData) { - console.log('onProcessCreated onProcessCreated: ' + JSON.stringify(processData)); + console.log('onProcessCreated onProcessCreated: ${JSON.stringify(processData)}'); }, onProcessDied(processData) { - console.log('onProcessDied onProcessDied: ' + JSON.stringify(processData)); + console.log('onProcessDied onProcessDied: ${JSON.stringify(processData)}'); }, onProcessStateChanged(processData) { - console.log('onProcessStateChanged onProcessStateChanged: ' + JSON.stringify(processData)); + console.log('onProcessStateChanged onProcessStateChanged: ${JSON.stringify(processData)}'); } -} +}; let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md index 3c0e5e3806181cbff0492cfe4faa387f315e516b..f30e7733060ad505d88ad80fab618133c2a3b35e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -22,7 +22,7 @@ import UIAbility from '@ohos.app.ability.UIAbility'; class EntryAbility extends UIAbility { onCreate(want, launchParam) { // EntryAbility onCreate, isStageMode: true - console.log("EntryAbility onCreate, isStageMode: " + this.context.stageMode); + console.log('EntryAbility onCreate, isStageMode: ${this.context.stageMode}'); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md index 2a4fe5eaaf05dd8f7e6c907966a8a411382a6daa..eb9ed63890d99338a57c18613eb37c59f753be0e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -22,8 +22,8 @@ The **Context** module provides context for abilities or applications. It allows | preferencesDir | string | Yes | No | Preferences directory.| | bundleCodeDir | string | Yes | No | Bundle code directory.| | distributedFilesDir | string | Yes | No | Distributed file directory.| -| eventHub | string | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| -| area | [AreaMode](#areamode) | Yes | No | Area in which the file to be access is located.| +| eventHub | [EventHub](js-apis-inner-application-eventHub.md) | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| +| area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | Yes | No | Area in which the file to be access is located.| ## Context.createBundleContext @@ -60,10 +60,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts let bundleContext; try { - bundleContext = this.context.createBundleContext("com.example.test"); + bundleContext = this.context.createBundleContext('com.example.test'); } catch (error) { - console.log('createBundleContext failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('createBundleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` @@ -100,13 +99,14 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts let moduleContext; try { - moduleContext = this.context.createModuleContext("entry"); + moduleContext = this.context.createModuleContext('entry'); } catch (error) { - console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` +## Context.createModuleContext + createModuleContext(bundleName: string, moduleName: string): Context; Creates the context based on the bundle name and module name. @@ -139,10 +139,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts let moduleContext; try { - moduleContext = this.context.createModuleContext("com.example.test", "entry"); + moduleContext = this.context.createModuleContext('com.example.test', 'entry'); } catch (error) { - console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` @@ -167,18 +166,6 @@ let applicationContext; try { applicationContext = this.context.getApplicationContext(); } catch (error) { - console.log('getApplicationContext failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('getApplicationContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` - -## AreaMode - -Enumerates the areas in which the file to be access can be located. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Value| Description| -| -------- | -------- | -------- | -| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| -| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md index b67c612c1b3b6dd82537b6dd5e6e7fcad2d6bdcb..448212035ad08f63371b001ab305cadf0153c807 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -19,28 +19,27 @@ Called when the mission continuation is complete. **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager' + import distributedMissionManager from '@ohos.distributedMissionManager'; let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", + srcDeviceId: '123', + dstDeviceId: '456', missionId: 123, wantParam: { - "key":"value" + 'key':'value' } }; let continueCallback = { onContinueDone(result) { - console.log('onContinueDone, result: ' + JSON.stringify(result)); + console.log('onContinueDone, result: ${JSON.stringify(result)}'); } }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { if (error && error.code) { - console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('continueMission failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } console.log('continueMission finished'); - }) + }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md index 5582132e3f610a76175cbb73796b6283498c4395..424456ba9bf4d52f0e9696b4268fe743b8a0fd8e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -14,28 +14,27 @@ The **ContinueDeviceInfo** module defines the parameters required for initiating **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager' + import distributedMissionManager from '@ohos.distributedMissionManager'; let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", + srcDeviceId: '123', + dstDeviceId: '456', missionId: 123, wantParam: { - "key":"value" + 'key':'value' } }; let continueCallback = { onContinueDone(result) { - console.log('onContinueDone, result: ' + JSON.stringify(result)); + console.log('onContinueDone, result: ${JSON.stringify(result)}'); } }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { if (error && error.code) { - console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('continueMission failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } console.log('continueMission finished'); - }) + }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md index 271f2697803dde9d0b3f78c3bb661a03d925b95e..85b9503b48dc15a49c19cd74be00f071e93e3969 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -19,18 +19,17 @@ Called when an unhandled exception occurs in the JS runtime. **Example** ```ts -import errorManager from '@ohos.app.ability.errorManager' +import errorManager from '@ohos.app.ability.errorManager'; let observer = { - onUnhandledException(errorMsg) { - console.log('HXW onUnhandledException, errorMsg: ', errorMsg); - } -} + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg); + } +}; try { - errorManager.on("error", observer); + errorManager.on('error', observer); } catch (error) { - console.log('registerErrorObserver' + ' failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('registerErrorObserver failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md index 8b580177c7622b33b0d2c06749a928e825ae84bc..cda73945ba6930d438635761e0924559261a281a 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md @@ -16,11 +16,11 @@ import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { eventFunc(){ - console.log("eventFunc is called"); + console.log('eventFunc is called'); } onForeground() { - this.context.eventHub.on("myEvent", this.eventFunc); + this.context.eventHub.on('myEvent', this.eventFunc); } } ``` @@ -47,19 +47,19 @@ import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { onForeground() { - this.context.eventHub.on("myEvent", this.eventFunc); + this.context.eventHub.on('myEvent', this.eventFunc); // Anonymous functions can be used to subscribe to events. - this.context.eventHub.on("myEvent", () => { - console.log("call anonymous eventFunc"); + this.context.eventHub.on('myEvent', () => { + console.log('call anonymous eventFunc'); }); // Result // eventFunc is called // call anonymous eventFunc - this.context.eventHub.emit("myEvent"); + this.context.eventHub.emit('myEvent'); } eventFunc() { - console.log("eventFunc is called"); + console.log('eventFunc is called'); } } ``` @@ -88,19 +88,19 @@ import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { onForeground() { - this.context.eventHub.on("myEvent", this.eventFunc1); - this.context.eventHub.off("myEvent", this.eventFunc1); // Unsubscribe from the myEvent event with the callback eventFunc1. - this.context.eventHub.on("myEvent", this.eventFunc1); - this.context.eventHub.on("myEvent", this.eventFunc2); - this.context.eventHub.off("myEvent"); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2). + this.context.eventHub.on('myEvent', this.eventFunc1); + this.context.eventHub.off('myEvent', this.eventFunc1); // Unsubscribe from the myEvent event with the callback eventFunc1. + this.context.eventHub.on('myEvent', this.eventFunc1); + this.context.eventHub.on('myEvent', this.eventFunc2); + this.context.eventHub.off('myEvent'); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2). } eventFunc1() { - console.log("eventFunc1 is called"); + console.log('eventFunc1 is called'); } eventFunc2() { - console.log("eventFunc2 is called"); + console.log('eventFunc2 is called'); } } ``` @@ -127,20 +127,20 @@ import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { onForeground() { - this.context.eventHub.on("myEvent", this.eventFunc); + this.context.eventHub.on('myEvent', this.eventFunc); // Result // eventFunc is called,undefined,undefined - this.context.eventHub.emit("myEvent"); + this.context.eventHub.emit('myEvent'); // Result // eventFunc is called,1,undefined - this.context.eventHub.emit("myEvent", 1); + this.context.eventHub.emit('myEvent', 1); // Result // eventFunc is called,1,2 - this.context.eventHub.emit("myEvent", 1, 2); + this.context.eventHub.emit('myEvent', 1, 2); } eventFunc(argOne, argTwo) { - console.log("eventFunc is called," + argOne + "," + argTwo); + console.log('eventFunc is called, ${argOne}, ${argTwo}'); } } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index 85fff22533b515eba4bb36c274e2d8782f28a356..e4d28bb0823439d40b84be13c98a0b9758493a08 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -36,22 +36,22 @@ import Want from '@ohos.app.ability.Want'; export default class TheServiceExtension extends ServiceExtension { onCreate(want:Want) { - console.log('ServiceAbility onCreate, want: ' + want.abilityName); + console.log('ServiceAbility onCreate, want: ${want.abilityName}'); // Pass ExtensionContext to entry via globalThis. globalThis.ExtensionContext = this.context; } onRequest(want, startId) { - console.log('ServiceAbility onRequest, want: ' + want.abilityName + ', startId: ' + startId); + console.log('ServiceAbility onRequest, want: ${want.abilityName}, startId: ${startId}'); } onConnect(want) { - console.log('ServiceAbility onConnect, want:' + want.abilityName); + console.log('ServiceAbility onConnect, want: ${want.abilityName}'); return null; } onDisconnect(want) { - console.log('ServiceAbility onDisconnect, want:' + want.abilityName); + console.log('ServiceAbility onDisconnect, want: ${want.abilityName}'); } onDestroy() { @@ -66,11 +66,11 @@ import UIAbility from '@ohos.app.ability.UIAbility'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] EntryAbility onCreate"); + console.log('[Demo] EntryAbility onCreate'); let wantExt = { - deviceId: "", - bundleName: "com.example.TheServiceExtension", - abilityName: "TheServiceExtension", + deviceId: '', + bundleName: 'com.example.TheServiceExtension', + abilityName: 'TheServiceExtension', }; this.context.startServiceExtensionAbility(wantExt); } @@ -85,29 +85,29 @@ export default class ServiceModel { constructor() {} executeTask() { - if (globalThis.ExtensionContext == undefined) { - console.log("ERROR, ServiceExtension does not exist"); + if (globalThis.ExtensionContext === undefined) { + console.log('ERROR, ServiceExtension does not exist'); return; } - var moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; + let moduleInfo = globalThis.ExtensionContext.currentHapModuleInfo; this.moduleName = moduleInfo.name; // Execute service logic based on the module name, which differentiates devices with different performance. switch (this.moduleName) { - case "highPerformance": - console.log("This is high performance device."); + case 'highPerformance': + console.log('This is high performance device.'); // Execute the corresponding service logic. break; - case "midPerformance": - console.log("This is mid performance device."); + case 'midPerformance': + console.log('This is mid performance device.'); // Execute the corresponding service logic. break; - case "lowPerformance": - console.log("This is low performance device."); + case 'lowPerformance': + console.log('This is low performance device.'); // Execute the corresponding service logic. break; default: - console.log("ERROR, invalid moduleName."); + console.log('ERROR, invalid moduleName.'); break; } } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md index 9485de9efd0dc76d78a905725fb742225b50340f..1e3003c9410c1bea9f0e8ef4f930966e9a6e5f4e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -27,26 +27,25 @@ Import the **abilityManager** module and obtain the ExtensionAbility running inf **Example** ```ts -import abilityManager from '@ohos.app.ability.abilityManager' +import abilityManager from '@ohos.app.ability.abilityManager'; -var upperLimit = 1; +let upperLimit = 1; function getExtensionInfos() { abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { if (error && error.code) { - console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } for (let i = 0; i < data.length; i++) { let extensionRunningInfo = data[i]; - console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension)); - console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid)); - console.log("extensionRunningInfo.uid: " + JSON.stringify(extensionRunningInfo.uid)); - console.log("extensionRunningInfo.processName: " + JSON.stringify(extensionRunningInfo.processName)); - console.log("extensionRunningInfo.startTime: " + JSON.stringify(extensionRunningInfo.startTime)); - console.log("extensionRunningInfo.clientPackage: " + JSON.stringify(extensionRunningInfo.clientPackage)); - console.log("extensionRunningInfo.type: " + JSON.stringify(extensionRunningInfo.type)); + console.log('extensionRunningInfo.extension: ${JSON.stringify(extensionRunningInfo.extension)}'); + console.log('extensionRunningInfo.pid: ${JSON.stringify(extensionRunningInfo.pid)}'); + console.log('extensionRunningInfo.uid: ${JSON.stringify(extensionRunningInfo.uid)}'); + console.log('extensionRunningInfo.processName: ${JSON.stringify(extensionRunningInfo.processName)}'); + console.log('extensionRunningInfo.startTime: ${JSON.stringify(extensionRunningInfo.startTime)}'); + console.log('extensionRunningInfo.clientPackage: ${JSON.stringify(extensionRunningInfo.clientPackage)}'); + console.log('extensionRunningInfo.type: ${JSON.stringify(extensionRunningInfo.type)}'); } }); } diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index d888ccdc51bef996937e9d2e6ef891980ffe457c..71d91c1fab2864341105c2ae3a636133c8a33208 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -22,8 +22,8 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { let formContext = this.context; // Obtain a FormExtensionContext instance. // ... let dataObj1 = { - temperature: "11c", - "time": "11:00" + temperature: '11c', + 'time': '11:00' }; let obj1 = formBindingData.createFormBindingData(dataObj1); return obj1; @@ -56,18 +56,18 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onFormEvent(formId, message) { // Call startAbility() when the message event is triggered. - console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + console.log('FormExtensionAbility onFormEvent, formId: ${formId}, message:${message}'); let want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "EntryAbility", + deviceId: '', + bundleName: 'com.example.formstartability', + abilityName: 'EntryAbility', parameters: { - "message": message + 'message': message } }; this.context.startAbility(want, (error, data) => { if (error) { - console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + console.log('FormExtensionContext startAbility, error:${JSON.stringify(error)}'); } else { console.log('FormExtensionContext startAbility success'); } @@ -106,19 +106,19 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; export default class MyFormExtensionAbility extends FormExtensionAbility { onFormEvent(formId, message) { // Call startAbility() when the message event is triggered. - console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + console.log('FormExtensionAbility onFormEvent, formId:${formId}, message:${message}'); let want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "EntryAbility", + deviceId: '', + bundleName: 'com.example.formstartability', + abilityName: 'EntryAbility', parameters: { - "message": message + 'message': message } }; this.context.startAbility(want).then(() => { - console.info("StartAbility Success"); + console.info('StartAbility Success'); }).catch((error) => { - console.info("StartAbility failed"); + console.info('StartAbility failed'); }); } }; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md index 7ccae03fa363d0850338d07f1318a377f10fc293..2f3ff7b63edd1d6ce46b86c741c895e04538eb31 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md @@ -15,19 +15,19 @@ The **MissionCallback** module defines the callbacks invoked after synchronizati import distributedMissionManager from '@ohos.distributedMissionManager'; let missionDeviceInfo = { - deviceId: "123456" + deviceId: '123456' }; let missionCallback = { notifyMissionsChanged: function (deviceId) { - console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + console.log('notifyMissionsChanged deviceId: ${JSON.stringify(deviceId)}'); }, notifySnapshot: function (deviceId, mission) { - console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); - console.log("notifySnapshot mission: " + JSON.stringify(mission)); + console.log('notifySnapshot deviceId: ${JSON.stringify(deviceId)}'); + console.log('notifySnapshot mission: ${JSON.stringify(mission)}'); }, notifyNetDisconnect: function (deviceId, state) { - console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId)); - console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + console.log('notifyNetDisconnect deviceId: ${JSON.stringify(deviceId)}'); + console.log('notifyNetDisconnect state: ${JSON.stringify(state)}'); } }; distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md index 9157fc697346087895870a5bbd6e4a0368d6bde7..8f513e50e5d1c51a04f31ec36de0f6d060804e81 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md @@ -13,19 +13,19 @@ The **MissionDeviceInfo** module defines the parameters required for registering import distributedMissionManager from '@ohos.distributedMissionManager'; let missionDeviceInfo = { - deviceId: "123456" + deviceId: '123456' }; let missionCallback = { notifyMissionsChanged: function (deviceId) { - console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + console.log('notifyMissionsChanged deviceId: ${JSON.stringify(deviceId)}'); }, notifySnapshot: function (mission, deviceId) { - console.log("notifySnapshot mission: " + JSON.stringify(mission)); - console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + console.log('notifySnapshot mission: ${JSON.stringify(mission)}'); + console.log('notifySnapshot deviceId: ${JSON.stringify(deviceId)}'); }, notifyNetDisconnect: function (mission, state) { - console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); - console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + console.log('notifyNetDisconnect mission: ${JSON.stringify(mission)}'); + console.log('notifyNetDisconnect state: ${JSON.stringify(state)}'); } }; distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md index afefb70c5a3e0b0059e4712992c3f736516bc2f7..ff8c880a0db0f67a8fc184bb9986245bfd9ad7af 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -19,27 +19,26 @@ The **MissionInfo** module defines detailed information about a mission. The inf **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager' +import missionManager from '@ohos.app.ability.missionManager'; try { - missionManager.getMissionInfo("", 1, (error, data) => { + missionManager.getMissionInfo('', 1, (error, data) => { if (error.code) { // Process service logic errors. - console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfo failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); - console.log('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); - console.log('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); - console.log('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); - console.log('getMissionInfo want is:' + JSON.stringify(data.want)); - console.log('getMissionInfo label is:' + JSON.stringify(data.label)); - console.log('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); - console.log('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); + console.log('getMissionInfo missionId is: ${JSON.stringify(data.missionId)}'); + console.log('getMissionInfo runningState is: ${JSON.stringify(data.runningState)}'); + console.log('getMissionInfo lockedState is: ${JSON.stringify(data.lockedState)}'); + console.log('getMissionInfo timestamp is: ${JSON.stringify(data.timestamp)}'); + console.log('getMissionInfo want is: ${JSON.stringify(data.want)}'); + console.log('getMissionInfo label is: ${JSON.stringify(data.label)}'); + console.log('getMissionInfo iconPath is: ${JSON.stringify(data.iconPath)}'); + console.log('getMissionInfo continuable is: ${JSON.stringify(data.continuable)}'); }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md index a9f9e6cf9540c02ada58ea7e89f76b9c9c297efb..84aa5294ce48be5388103945bfb417284cfa297e 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -16,32 +16,32 @@ The **MissionListener** module defines the listeners used to observe the mission **Example** ```ts -import missionManager from '@ohos.app.ability.missionManager' +import missionManager from '@ohos.app.ability.missionManager'; let listener = { onMissionCreated: function (mission) { - console.log("onMissionCreated mission: " + JSON.stringify(mission)); + console.log('onMissionCreated mission: ${JSON.stringify(mission)}'); }, onMissionDestroyed: function (mission) { - console.log("onMissionDestroyed mission: " + JSON.stringify(mission)); + console.log('onMissionDestroyed mission: ${JSON.stringify(mission)}'); }, onMissionSnapshotChanged: function (mission) { - console.log("onMissionSnapshotChanged mission: " + JSON.stringify(mission)); + console.log('onMissionSnapshotChanged mission: ${JSON.stringify(mission)}'); }, onMissionMovedToFront: function (mission) { - console.log("onMissionMovedToFront mission: " + JSON.stringify(mission)); + console.log('onMissionMovedToFront mission: ${JSON.stringify(mission)}'); }, onMissionIconUpdated: function (mission, icon) { - console.log("onMissionIconUpdated mission: " + JSON.stringify(mission)); + console.log('onMissionIconUpdated mission: ${JSON.stringify(mission)}'); }, onMissionClosed: function (mission) { - console.log("onMissionClosed mission: " + JSON.stringify(mission)); + console.log('onMissionClosed mission: ${JSON.stringify(mission)}'); } }; try { - let listenerId = missionManager.on("mission", listener); + let listenerId = missionManager.on('mission', listener); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md index 9e2e2aa23a6589c0eb80075f8de60f65261e6903..40e8cc3f92791f09b505912b3a391080aa6465bc 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md @@ -15,17 +15,17 @@ The **MissionParameter** module defines the parameters required for mission sync import distributedMissionManager from '@ohos.distributedMissionManager'; let missionParameter = { - deviceId: "123456", + deviceId: '123456', fixConflict: true, tag: 123 }; try { distributedMissionManager.startSyncRemoteMissions(missionParameter, (err, data) => { - console.log("startSyncRemoteMissions, data: " + JSON.stringify(data)); + console.log('startSyncRemoteMissions, data: ${JSON.stringify(data)}'); } ); } catch (err) { - console.error('startSyncRemoteMissions fail: ' + JSON.stringify(err)); + console.error('startSyncRemoteMissions fail: ${JSON.stringify(err)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md index a97f3b32b71f90078cb03f32fa46262f5cf6b770..6176bd77631cff48db82b5463fe8f55452736cb6 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -25,28 +25,26 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** import missionManager from '@ohos.app.ability.missionManager'; try { - missionManager.getMissionInfos("", 10, (error, missions) => { + missionManager.getMissionInfos('', 10, (error, missions) => { if (error.code) { - console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + - "error.message:" + JSON.stringify(error.message)); + console.log('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; + console.log('size = ${missions.length}'); + console.log('missions = ${JSON.stringify(missions)}'); + let id = missions[0].missionId; - missionManager.getMissionSnapShot("", id, (err, snapshot) => { + missionManager.getMissionSnapShot('', id, (err, snapshot) => { if (err.code) { - console.log("getMissionInfos failed, err.code:" + JSON.stringify(err.code) + - "err.message:" + JSON.stringify(err.message)); + console.log('getMissionInfos failed, err.code: ${JSON.stringify(err.code)}, err.message: ${JSON.stringify(err.message)}'); return; } // Carry out normal service processing. - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) + console.log('bundleName = ${snapshot.ability.bundleName}'); + }); + }); } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); + console.log('error: ${paramError.code}, ${paramError.message}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-permissionRequestResult.md b/en/application-dev/reference/apis/js-apis-inner-application-permissionRequestResult.md deleted file mode 100644 index 7a415835191f7d66bdbd7d433df150d52c3d88ac..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-inner-application-permissionRequestResult.md +++ /dev/null @@ -1,40 +0,0 @@ -# PermissionRequestResult - -The **PermissionRequestResult** module provides the result of a permission request. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module can be used only in the stage model. - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. | - -## How to Use - -The permission request result is obtained through an **AbilityStage** instance. - -**Example** -```ts -import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - var permissions=['com.example.permission'] - var permissionRequestResult; - this.context.requestPermissionsFromUser(permissions,(err,result) => { - if(err){ - console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); - }else{ - permissionRequestResult=result; - console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); - } - }); - } -} -``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processData.md b/en/application-dev/reference/apis/js-apis-inner-application-processData.md index 41401037a32bb0231b721bb470dec7f2e7a3d175..076fdb4f2c0310aa9d53e8d303258672a8afc8e7 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -21,24 +21,24 @@ import appManager from '@ohos.app.ability.appManager'; let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { - console.log('onForegroundApplicationChanged appStateData: ' + JSON.stringify(appStateData)); + console.log('onForegroundApplicationChanged appStateData: ${JSON.stringify(appStateData)}'); }, onAbilityStateChanged(abilityStateData) { - console.log('onAbilityStateChanged onAbilityStateChanged: ' + JSON.stringify(abilityStateData)); + console.log('onAbilityStateChanged onAbilityStateChanged: ${JSON.stringify(abilityStateData)}'); }, onProcessCreated(processData) { - console.log('onProcessCreated onProcessCreated: ' + JSON.stringify(processData)); + console.log('onProcessCreated onProcessCreated: ${JSON.stringify(processData)}'); }, onProcessDied(processData) { - console.log('onProcessDied onProcessDied: ' + JSON.stringify(processData)); + console.log('onProcessDied onProcessDied: ${JSON.stringify(processData)}'); }, onProcessStateChanged(processData) { - console.log('onProcessStateChanged processData.pid : ' + JSON.stringify(processData.pid)); - console.log('onProcessStateChanged processData.bundleName : ' + JSON.stringify(processData.bundleName)); - console.log('onProcessStateChanged processData.uid : ' + JSON.stringify(processData.uid)); - console.log('onProcessStateChanged processData.isContinuousTask : ' + JSON.stringify(processData.isContinuousTask)); - console.log('onProcessStateChanged processData.isKeepAlive : ' + JSON.stringify(processData.isKeepAlive)); + console.log('onProcessStateChanged processData.pid : ${JSON.stringify(processData.pid)}'); + console.log('onProcessStateChanged processData.bundleName : ${JSON.stringify(processData.bundleName)}'); + console.log('onProcessStateChanged processData.uid : ${JSON.stringify(processData.uid)}'); + console.log('onProcessStateChanged processData.isContinuousTask : ${JSON.stringify(processData.isContinuousTask)}'); + console.log('onProcessStateChanged processData.isKeepAlive : ${JSON.stringify(processData.isKeepAlive)}'); } -} +}; let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md similarity index 55% rename from en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md rename to en/application-dev/reference/apis/js-apis-inner-application-processInformation.md index a376446b2af90c8cc13f6eee80a10a5399dae041..19c8f42e7de0b8c354c14d44300a65ce7f0ac208 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md @@ -1,6 +1,6 @@ -# ProcessRunningInformation +# ProcessInformation -The **ProcessRunningInformation** module defines the running information of a process. +The **ProcessInformation** module defines the running information of a process. > **NOTE** > @@ -8,13 +8,13 @@ The **ProcessRunningInformation** module defines the running information of a pr ## How to Use -The process running information is obtained through [getProcessRunningInformation](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9) in **appManager**. +The process information is obtained by calling [getRunningProcessInformation](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9) of the **appManager** module. ```ts -import appManager from '@ohos.application.appManager'; +import appManager from '@ohos.app.ability.appManager'; -appManager.getProcessRunningInformation((error, data) => { - console.log("error: " + error.code + " data: " + JSON.stringify(data)); +appManager.getRunningProcessInformation((error, data) => { + console.log('error: ${error.code}, data: ${JSON.stringify(data)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index 16dd713d9bf284ce001df342c4a963920977f112..f0025296af4ced3c2c7c344e395478df608366a5 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -3,7 +3,7 @@ The **ProcessRunningInfo** module defines the running information of a process. > **NOTE** -> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-inner-application-processRunningInformation.md) instead. +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessInformation9+](js-apis-inner-application-processInformation.md) instead. > - The initial APIs of this module are supported since API version 8. ## Attributes @@ -26,8 +26,8 @@ The process running information is obtained by using [getProcessRunningInfos](js import appManager from '@ohos.app.ability.appManager'; appManager.getProcessRunningInfos().then((data) => { - console.log('success:' + JSON.stringify(data)); + console.log('success: ${JSON.stringify(data)}'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('failed: ${JSON.stringify(error)}'); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index ae6beb1357d9d25dfcd06cbcd1d65df660fa44bb..6203c272773910aeab2b6f29041ec4aa21168872 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -16,7 +16,7 @@ Before using the **ServiceExtensionContext** module, you must define a child cla ```ts import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; - let context = undefined; + let context; class EntryAbility extends ServiceExtensionAbility { onCreate() { context = this.context; // Obtain a ServiceExtensionContext instance. @@ -68,17 +68,16 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; try { this.context.startAbility(want, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -86,8 +85,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -141,11 +139,11 @@ Starts an ability. This API uses a promise to return the result. **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; - var options = { + let options = { windowMode: 0, }; @@ -157,13 +155,11 @@ Starts an ability. This API uses a promise to return the result. }) .catch((error) => { // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -212,12 +208,12 @@ Starts an ability with the start options specified. This API uses an asynchronou **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var options = { + let options = { windowMode: 0 }; @@ -225,8 +221,7 @@ Starts an ability with the start options specified. This API uses an asynchronou this.context.startAbility(want, options, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -234,8 +229,7 @@ Starts an ability with the start options specified. This API uses an asynchronou }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -290,19 +284,18 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -310,8 +303,7 @@ Observe the following when using this API: }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -367,13 +359,13 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -381,8 +373,7 @@ Observe the following when using this API: this.context.startAbilityWithAccount(want, accountId, options, (error) => { if (error.code) { // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -390,8 +381,7 @@ Observe the following when using this API: }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -453,13 +443,13 @@ Observe the following when using this API: **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; - var options = { + let accountId = 100; + let options = { windowMode: 0 }; @@ -471,13 +461,11 @@ Observe the following when using this API: }) .catch((error) => { // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -518,18 +506,17 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; try { this.context.startServiceExtensionAbility(want, (error) => { if (error.code) { // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -537,8 +524,7 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -584,10 +570,10 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; try { @@ -598,13 +584,11 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu }) .catch((error) => { // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -650,19 +634,18 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -670,8 +653,7 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -721,12 +703,12 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.startServiceExtensionAbilityWithAccount(want, accountId) @@ -736,13 +718,11 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use }) .catch((error) => { // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -780,18 +760,17 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; try { this.context.stopServiceExtensionAbility(want, (error) => { if (error.code) { // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('stopServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -799,8 +778,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -843,10 +821,10 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; try { @@ -857,13 +835,11 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise }) .catch((error) => { // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('stopServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -905,19 +881,18 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code), error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -925,8 +900,7 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -973,12 +947,12 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' }; - var accountId = 100; + let accountId = 100; try { this.context.stopServiceExtensionAbilityWithAccount(want, accountId) @@ -988,13 +962,11 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec }) .catch((error) => { // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1031,8 +1003,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re this.context.terminateSelf((error) => { if (error.code) { // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('terminateSelf failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -1075,8 +1046,7 @@ Terminates this ability. This API uses a promise to return the result. console.log('terminateSelf succeed'); }).catch((error) => { // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('terminateSelf failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); ``` @@ -1118,23 +1088,22 @@ Connects this ability to a ServiceAbility. **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + let want = { + bundleName: 'com.example.myapp', + abilityName: 'MyAbility' }; - var options = { + let options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } - } + }; - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbility(want, options); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1178,25 +1147,24 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "EntryAbility" + let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }; + let accountId = 100; + let options = { + onConnect(elementName, remote) { console.log('----------- onConnect -----------'); }, + onDisconnect(elementName) { console.log('----------- onDisconnect -----------'); }, + onFailed(code) { console.log('----------- onFailed -----------'); } }; - var accountId = 100; - var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } - } - var connection = null; + let connection = null; try { connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1214,7 +1182,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Number returned after **connectAbility** is called.| +| connection | number | Yes| Number returned after **connectServiceExtensionAbility** is called.| | callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -1232,14 +1200,13 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous ```ts // connection is the return value of connectServiceExtensionAbility. - var connection = 1; + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection, (error) => { if (error.code) { // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('disconnectServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); return; } // Carry out normal service processing. @@ -1247,8 +1214,7 @@ Disconnects this ability from the ServiceAbility. This API uses an asynchronous }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1266,7 +1232,7 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Number returned after **connectAbility** is called.| +| connection | number | Yes| Number returned after **connectServiceExtensionAbility** is called.| **Return value** @@ -1288,8 +1254,8 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret **Example** ```ts - // connection is the return value of connectAbility. - var connection = 1; + // connection is the return value of connectServiceExtensionAbility. + let connection = 1; try { this.context.disconnectServiceExtensionAbility(connection) @@ -1299,13 +1265,11 @@ Disconnects this ability from the ServiceAbility. This API uses a promise to ret }) .catch((error) => { // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('disconnectServiceExtensionAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` @@ -1355,14 +1319,14 @@ Observe the following when using this API: Start an ability in the background. ```ts - var caller = undefined; + let caller; // Start an ability in the background by not passing parameters. - var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "EntryAbility", - deviceId: "" + let wantBackground = { + bundleName: 'com.example.myservice', + moduleName: 'entry', + abilityName: 'EntryAbility', + deviceId: '' }; try { @@ -1373,29 +1337,27 @@ Observe the following when using this API: console.log('startAbilityByCall succeed'); }).catch((error) => { // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbilityByCall failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` Start an ability in the foreground. ```ts - var caller = undefined; - - // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. - var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "EntryAbility", - deviceId: "", + let caller; + + // Start an ability in the foreground with 'ohos.aafwk.param.callAbilityToForeground' in parameters set to true. + let wantForeground = { + bundleName: 'com.example.myservice', + moduleName: 'entry', + abilityName: 'EntryAbility', + deviceId: '', parameters: { - "ohos.aafwk.param.callAbilityToForeground": true + 'ohos.aafwk.param.callAbilityToForeground': true } }; @@ -1407,12 +1369,10 @@ Observe the following when using this API: console.log('startAbilityByCall succeed'); }).catch((error) => { // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.log('startAbilityByCall failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 8db813f610095cb4b19412291f34f3bf53c5dc57..435d799676e7924e7366fdbec93373f55313a86d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -19,13 +19,13 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio **Example** ```ts -import AbilityDelegatorRegistry from "@ohos.app.ability.abilityDelegatorRegistry"; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; let abilityDelegator; -let cmd = "cmd"; +let cmd = 'cmd'; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { - console.info("executeShellCommand callback, result: ", err); - console.info("executeShellCommand callback, data: ", data); + console.info('executeShellCommand callback, result: ', err); + console.info('executeShellCommand callback, data: ', data); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index f8528cc1bf6c8b4468c5c475934fe1c91c70490a..f735fb4b0f84720e1150f219b04ff0b79e63b3ed 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -18,7 +18,8 @@ | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| UIAbility configuration, such as the language and color mode.| > **NOTE** -> - In the sample code provided in this topic, **this.context** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** capabilities on pages, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). +> +> In the sample code provided in this topic, **this.context** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** APIs on pages, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). ## UIAbilityContext.startAbility @@ -44,50 +45,42 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" - }; - - try { - this.context.startAbility(want, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; + +try { + this.context.startAbility(want, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbility failed failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbility @@ -115,54 +108,46 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbility(want, options, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0 +}; + +try { + this.context.startAbility(want, options, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbility failed failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbility @@ -195,60 +180,55 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" - }; - var options = { - windowMode: 0, - }; - - try { - this.context.startAbility(want, options) - .then(() => { - // Carry out normal service processing. - console.log('startAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0, +}; + +try { + this.context.startAbility(want, options) + .then(() => { + // Carry out normal service processing. + console.info('startAbility succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. The following situations may be possible for a started ability: + - Normally, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller. + - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller. + - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an error message, in which **resultCode** is **-1**, is returned to others. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -268,58 +248,53 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - - try { - this.context.startAbilityForResult(want, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; + +try { + this.context.startAbilityForResult(want, (err, result) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbilityForResult succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. The following situations may be possible for a started ability: + - Normally, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller. + - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller. + - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an error message, in which **resultCode** is **-1**, is returned to others. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -340,54 +315,46 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var options = { - windowMode: 0, - }; - - try { - this.context.startAbilityForResult(want, options, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0, +}; + +try { + this.context.startAbilityForResult(want, options, (err, result) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbilityForResult succeed'); + }); +} catch (paramError) { + // Process input parameter errors. + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -395,7 +362,10 @@ Observe the following when using this API: startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. +Starts an ability. This API uses a promise to return the result when the ability is terminated. The following situations may be possible to an ability after it is started: + - Normally, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability. The result is returned to the caller. + - If an exception occurs, for example, the ability is killed, an error message, in which **resultCode** is **-1**, is returned to the caller. + - If different applications call this API to start an ability that uses the singleton mode and then call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability, the normal result is returned to the last caller, and an error message, in which **resultCode** is **-1**, is returned to others. Observe the following when using this API: - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. @@ -422,53 +392,45 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var options = { - windowMode: 0, - }; - - try { - this.context.startAbilityForResult(want, options) - .then((result) => { - // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let options = { + windowMode: 0, +}; + +try { + this.context.startAbilityForResult(want, options) + .then((result) => { + // Carry out normal service processing. + console.info('startAbilityForResult succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityForResult failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbilityForResultWithAccount @@ -500,54 +462,44 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var accountId = 100; - - try { - this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode + ' result.want = ' + JSON.stringify(result.want)) - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let accountId = 100; + +try { + this.context.startAbilityForResultWithAccount(want, accountId, (err, result) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbilityForResultWithAccount succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -581,56 +533,47 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityForResultWithAccount(want, accountId, options, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed") - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let accountId = 100; +let options = { + windowMode: 0 +}; + +try { + this.context.startAbilityForResultWithAccount(want, accountId, options, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbilityForResultWithAccount succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -669,57 +612,47 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityForResultWithAccount(want, accountId, options) - .then((result) => { - // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let accountId = 100; +let options = { + windowMode: 0 +}; + +try { + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((result) => { + // Carry out normal service processing. + console.info('startAbilityForResultWithAccount succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityForResultWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startServiceExtensionAbility @@ -742,44 +675,38 @@ Starts a ServiceExtensionAbility. This API uses an asynchronous callback to retu | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - - try { - this.context.startServiceExtensionAbility(want, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; + +try { + this.context.startServiceExtensionAbility(want) + .then(() => { // Carry out normal service processing. - console.log('startServiceExtensionAbility succeed'); + console.info('startServiceExtensionAbility succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); }); - } catch (paramError) { - // Process input parameter errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +} catch (err) { + // Process input parameter errors. + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startServiceExtensionAbility @@ -802,44 +729,38 @@ Starts a ServiceExtensionAbility. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - - try { - this.context.startServiceExtensionAbility(want) - .then(() => { - // Carry out normal service processing. - console.log('startServiceExtensionAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; + +try { + this.context.startServiceExtensionAbility(want) + .then(() => { + // Carry out normal service processing. + console.info('startServiceExtensionAbility succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (paramError) { + // Process input parameter errors. + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startServiceExtensionAbilityWithAccount @@ -866,42 +787,39 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses an | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - var accountId = 100; - - try { - this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startServiceExtensionAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; +let accountId = 100; + +try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startServiceExtensionAbilityWithAccount succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startServiceExtensionAbilityWithAccount @@ -927,46 +845,39 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses a | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - var accountId = 100; - - try { - this.context.startServiceExtensionAbilityWithAccount(want, accountId) - .then((data) => { - // Carry out normal service processing. - console.log('startServiceExtensionAbilityWithAccount succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; +let accountId = 100; + +try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then(() => { + // Carry out normal service processing. + console.info('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.stopServiceExtensionAbility @@ -989,41 +900,37 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - - try { - this.context.stopServiceExtensionAbility(want, (error) => { - if (error.code) { - // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('stopServiceExtensionAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; + +try { + this.context.stopServiceExtensionAbility(want, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`stopServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('stopServiceExtensionAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`stopServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.stopServiceExtensionAbility @@ -1046,41 +953,37 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - - try { - this.context.stopServiceExtensionAbility(want) - .then((data) => { - // Carry out normal service processing. - console.log('stopServiceExtensionAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; + +try { + this.context.stopServiceExtensionAbility(want) + .then(() => { + // Carry out normal service processing. + console.info('stopServiceExtensionAbility succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`stopServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`stopServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.stopServiceExtensionAbilityWithAccount @@ -1107,43 +1010,38 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - var accountId = 100; - - try { - this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { - if (error.code) { - // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('stopServiceExtensionAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; +let accountId = 100; + +try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('stopServiceExtensionAbilityWithAccount succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.stopServiceExtensionAbilityWithAccount @@ -1169,43 +1067,38 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - var accountId = 100; - - try { - this.context.stopServiceExtensionAbilityWithAccount(want, accountId) - .then((data) => { - // Carry out normal service processing. - console.log('stopServiceExtensionAbilityWithAccount succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; +let accountId = 100; + +try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then(() => { + // Carry out normal service processing. + console.info('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`stopServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.terminateSelf @@ -1226,31 +1119,29 @@ Terminates this ability. This API uses an asynchronous callback to return the re | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts try { - this.context.terminateSelf((error) => { - if (error.code) { + this.context.terminateSelf((err) => { + if (err.code) { // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); return; } // Carry out normal service processing. - console.log('terminateSelf succeed'); + console.info('terminateSelf succeed'); }); - } catch (error) { + } catch (err) { // Capture the synchronization parameter error. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -1273,12 +1164,12 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** @@ -1287,17 +1178,15 @@ Terminates this ability. This API uses a promise to return the result. this.context.terminateSelf() .then(() => { // Carry out normal service processing. - console.log('terminateSelf succeed'); + console.info('terminateSelf succeed'); }) - .catch((error) => { + .catch((err) => { // Process service logic errors. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); }); } catch (error) { // Capture the synchronization parameter error. - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`); } ``` @@ -1306,7 +1195,7 @@ Terminates this ability. This API uses a promise to return the result. terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of an asynchronous callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1321,43 +1210,41 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - var want = { - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - } - var resultCode = 100; - // AbilityResult information returned to the caller. - var abilityResult = { - want, - resultCode - } - - try { - this.context.terminateSelfWithResult(abilityResult, (error) => { - if (error.code) { - // Process service logic errors. - console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('terminateSelfWithResult succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let resultCode = 100; +// AbilityResult information returned to the caller. +let abilityResult = { + want, + resultCode +}; + +try { + this.context.terminateSelfWithResult(abilityResult, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('terminateSelfWithResult succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -1385,44 +1272,41 @@ Terminates this ability. If the ability is started by calling [startAbilityForRe | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | - +| 16000001 | The specified ability does not exist. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - var want = { - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - } - var resultCode = 100; - // AbilityResult information returned to the caller. - var abilityResult = { - want, - resultCode - } - - try { - this.context.terminateSelfWithResult(abilityResult) - .then((data) => { - // Carry out normal service processing. - console.log('terminateSelfWithResult succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let resultCode = 100; +// AbilityResult information returned to the caller. +let abilityResult = { + want, + resultCode +}; + +try { + this.context.terminateSelfWithResult(abilityResult) + .then(() => { + // Carry out normal service processing. + console.info('terminateSelfWithResult succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`terminateSelfWithResult failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.connectServiceExtensionAbility @@ -1433,8 +1317,6 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| @@ -1452,42 +1334,38 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - var options = { - onConnect(elementName, remote) { - console.log('----------- onConnect -----------') - }, - onDisconnect(elementName) { - console.log('----------- onDisconnect -----------') - }, - onFailed(code) { - console.log('----------- onFailed -----------') - } - } - - var connection = null; - try { - connection = this.context.connectServiceExtensionAbility(want, options); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; +let options = { + onConnect(elementName, remote) { + console.info('onConnect...') + }, + onDisconnect(elementName) { + console.info('onDisconnect...') + }, + onFailed(code) { + console.info('onFailed...') } +}; + +let connection = null; +try { + connection = this.context.connectServiceExtensionAbility(want, options); +} catch (err) { + // Process input parameter errors. + console.error(`connectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -1521,44 +1399,39 @@ Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERV | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000002 | Ability type error. The specified ability type is wrong. | -| 16000004 | Visibility verification failed. | -| 16000006 | Can not cross user operations. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "ServiceExtensionAbility" - }; - var accountId = 100; - var options = { - onConnect(elementName, remote) { - console.log('----------- onConnect -----------') - }, - onDisconnect(elementName) { - console.log('----------- onDisconnect -----------') - }, - onFailed(code) { - console.log('----------- onFailed -----------') - } - } - - var connection = null; - try { - connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'ServiceExtensionAbility' +}; +let accountId = 100; +let options = { + onConnect(elementName, remote) { + console.info('onConnect...') + }, + onDisconnect(elementName) { + console.info('onDisconnect...') + }, + onFailed(code) { + console.info('onFailed...') } +}; + +let connection = null; +try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); +} catch (err) { + // Process input parameter errors. + console.error(`connectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.disconnectServiceExtensionAbility @@ -1569,8 +1442,6 @@ Disconnects from a ServiceExtensionAbility. This API uses a promise to return th **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| @@ -1587,35 +1458,31 @@ Disconnects from a ServiceExtensionAbility. This API uses a promise to return th | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000003 | Input error. The specified id does not exist. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - // connection is the return value of connectServiceExtensionAbility. - var connection = 1; +// connection is the return value of connectServiceExtensionAbility. +let connection = 1; - try { - this.context.disconnectServiceExtensionAbility(connection) - .then((data) => { - // Carry out normal service processing. - console.log('disconnectServiceExtensionAbility succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +try { + this.context.disconnectServiceExtensionAbility(connection, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('disconnectServiceExtensionAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.disconnectServiceExtensionAbility @@ -1626,8 +1493,6 @@ Disconnects from a ServiceExtensionAbility. This API uses an asynchronous callba **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| @@ -1639,35 +1504,31 @@ Disconnects from a ServiceExtensionAbility. This API uses an asynchronous callba | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000003 | Input error. The specified id does not exist. | -| 16000011 | Context does not exist. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000005 | The specified process does not have the permission. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - // connection is the return value of connectServiceExtensionAbility. - var connection = 1; +// connection is the return value of connectServiceExtensionAbility. +let connection = 1; - try { - this.context.disconnectServiceExtensionAbility(connection, (error) => { - if (error.code) { - // Process service logic errors. - console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('disconnectServiceExtensionAbility succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +try { + this.context.disconnectServiceExtensionAbility(connection, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('disconnectServiceExtensionAbility succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`disconnectServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbilityByCall @@ -1695,71 +1556,85 @@ Observe the following when using this API: | -------- | -------- | | Promise<Caller> | Promise used to return the caller object to communicate with.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | + **Example** Start an ability in the background. ```ts - var caller = undefined; - - // Start an ability in the background by not passing parameters. - var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "" - }; - - try { - this.context.startAbilityByCall(wantBackground) - .then((obj) => { - // Carry out normal service processing. - caller = obj; - console.log('startAbilityByCall succeed'); - }).catch((error) => { - // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let caller; + +// Start an ability in the background by not passing parameters. +let wantBackground = { + bundleName: 'com.example.myapplication', + moduleName: 'entry', + abilityName: 'EntryAbility', + deviceId: '' +}; + +try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // Carry out normal service processing. + caller = obj; + console.info('startAbilityByCall succeed'); + }).catch((err) => { + // Process service logic errors. + console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); +} ``` - Start an ability in the foreground. +Start an ability in the foreground. ```ts - var caller = undefined; - - // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. - var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "", - parameters: { - "ohos.aafwk.param.callAbilityToForeground": true - } - }; - - try { - this.context.startAbilityByCall(wantForeground) - .then((obj) => { - // Carry out normal service processing. - caller = obj; - console.log('startAbilityByCall succeed'); - }).catch((error) => { - // Process service logic errors. - console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); +let caller; + +// Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. +let wantForeground = { + bundleName: 'com.example.myapplication', + moduleName: 'entry', + abilityName: 'EntryAbility', + deviceId: '', + parameters: { + 'ohos.aafwk.param.callAbilityToForeground': true } +}; + +try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // Carry out normal service processing. + caller = obj; + console.info('startAbilityByCall succeed'); + }).catch((error) => { + // Process service logic errors. + console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (paramError) { + // Process input parameter errors. + console.error(`startAbilityByCall failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.startAbilityWithAccount @@ -1791,53 +1666,44 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var accountId = 100; - - try { - this.context.startAbilityWithAccount(want, accountId, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let accountId = 100; + +try { + this.context.startAbilityWithAccount(want, accountId, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbilityWithAccount succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -1871,56 +1737,47 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityWithAccount(want, accountId, options, (error) => { - if (error.code) { - // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // Carry out normal service processing. - console.log('startAbilityWithAccount succeed'); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let accountId = 100; +let options = { + windowMode: 0 +}; + +try { + this.context.startAbilityWithAccount(want, accountId, options, (err) => { + if (err.code) { + // Process service logic errors. + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('startAbilityWithAccount succeed'); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` @@ -1953,63 +1810,54 @@ Observe the following when using this API: | ID| Error Message| | ------- | -------------------------------- | -| 201 | The application does not have permission to call the interface. | -| 401 | Invalid input parameter. | -| 16000001 | Input error. The specified ability name does not exist. | -| 16000004 | Visibility verification failed. | -| 16000005 | Static permission denied. The specified process does not have the permission. | -| 16000006 | Can not cross user operations. | -| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | -| 16000008 | Crowdtest App Expiration. | -| 16000009 | Can not start ability in wukong mode. | -| 16000010 | Can not operation with continue flag. | -| 16000011 | Context does not exist. | -| 16000051 | Network error. The network is abnormal. | -| 16000052 | Free install not support. The application does not support freeinstall | -| 16000053 | Not top ability. The application is not top ability. | -| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | -| 16000055 | Free install timeout. | -| 16000056 | Can not free install other ability. | -| 16000057 | Not support cross device free install. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Can not start invisible component. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000009 | An ability cannot be started or stopped in Wukong mode. | +| 16000010 | The call with the continuation flag is forbidden. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | +| 16000053 | The ability is not on the top of the UI. | +| 16000055 | Installation-free timed out. | +| 16200001 | The caller has been released. | **Example** ```ts - var want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "MainAbility" - }; - var accountId = 100; - var options = { - windowMode: 0 - }; - - try { - this.context.startAbilityWithAccount(want, accountId, options) - .then((data) => { - // Carry out normal service processing. - console.log('startAbilityWithAccount succeed'); - }) - .catch((error) => { - // Process service logic errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); - } catch (paramError) { - // Process input parameter errors. - console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); - } +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility' +}; +let accountId = 100; +let options = { + windowMode: 0 +}; + +try { + this.context.startAbilityWithAccount(want, accountId, options) + .then(() => { + // Carry out normal service processing. + console.info('startAbilityWithAccount succeed'); + }) + .catch((err) => { + // Process service logic errors. + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`startAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); +} ``` ## UIAbilityContext.setMissionLabel setMissionLabel(label: string, callback:AsyncCallback<void>): void; -Sets a label for this ability in the mission. This API uses an asynchronous callback to return the result. +Sets a label for this UIAbility in the mission. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2023,8 +1871,8 @@ Sets a label for this ability in the mission. This API uses an asynchronous call **Example** ```ts - this.context.setMissionLabel("test", (result) => { - console.log('setMissionLabel:' + JSON.stringify(result)); + this.context.setMissionLabel('test', (result) => { + console.info(`setMissionLabel: ${JSON.stringify(result)}`); }); ``` @@ -2032,7 +1880,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call setMissionLabel(label: string): Promise<void>; -Sets a label for this ability in the mission. This API uses a promise to return the result. +Sets a label for this UIAbility in the mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2048,13 +1896,20 @@ Sets a label for this ability in the mission. This API uses a promise to return | -------- | -------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + **Example** ```ts - this.context.setMissionLabel("test").then(() => { - console.log('success'); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + this.context.setMissionLabel('test').then(() => { + console.info('success'); + }).catch((err) => { + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); }); ``` ## UIAbilityContext.setMissionIcon @@ -2074,13 +1929,21 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call | icon | image.PixelMap | Yes| Icon of the ability to set.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + **Example** ```ts import image from '@ohos.multimedia.image'; - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -2091,10 +1954,10 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call imagePixelMap = data; }) .catch((err) => { - console.log('--------- createPixelMap fail, err: ---------', err) + console.error(`createPixelMap failed, code is ${err.code}, message is ${err.message}`); }); this.context.setMissionIcon(imagePixelMap, (err) => { - console.log('---------- setMissionIcon fail, err: -----------', err); + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -2121,12 +1984,19 @@ Sets an icon for this ability in the mission. This API uses a promise to return | -------- | -------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + **Example** ```ts - var imagePixelMap; - var color = new ArrayBuffer(0); - var initializationOptions = { + let imagePixelMap; + let color = new ArrayBuffer(0); + let initializationOptions = { size: { height: 100, width: 100 @@ -2137,21 +2007,21 @@ Sets an icon for this ability in the mission. This API uses a promise to return imagePixelMap = data; }) .catch((err) => { - console.log('--------- createPixelMap fail, err: ---------', err) + console.error(`createPixelMap failed, code is ${err.code}, message is ${err.message}`); }); this.context.setMissionIcon(imagePixelMap) .then(() => { - console.log('-------------- setMissionIcon success -------------'); + console.info('setMissionIcon succeed'); }) .catch((err) => { - console.log('-------------- setMissionIcon fail, err: -------------', err); + console.error(`setMissionLabel failed, code is ${err.code}, message is ${err.message}`); }); ``` ## UIAbilityContext.restoreWindowStage restoreWindowStage(localStorage: LocalStorage) : void; -Restores the window stage data for this ability. +Restores the WindowStage data in the UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2161,10 +2031,17 @@ Restores the window stage data for this ability. | -------- | -------- | -------- | -------- | | localStorage | image.LocalStorage | Yes| Storage used to store the restored window stage.| +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + **Example** ```ts - var storage = new LocalStorage(); + let storage = new LocalStorage(); this.context.restoreWindowStage(storage); ``` @@ -2172,7 +2049,7 @@ Restores the window stage data for this ability. isTerminating(): boolean; -Checks whether this ability is in the terminating state. +Checks whether this UIAbility is in the terminating state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2180,11 +2057,117 @@ Checks whether this ability is in the terminating state. | Type| Description| | -------- | -------- | -| boolean| The value **true** means that the ability is in the terminating state, and **false** means the opposite.| +| boolean| The value **true** means that the UIAbility is in the terminating state, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | **Example** ```ts - var isTerminating = this.context.isTerminating(); - console.log('ability state :' + isTerminating); + let isTerminating = this.context.isTerminating(); + console.info(`ability state is ${isTerminating}`); + ``` + +## UIAbilityContext.requestDialogService + +requestDialogService(want: Want, result: AsyncCallback<dialogRequest.RequestResult>): void; + +Starts a ServiceExtensionAbility that supports modal dialog boxes. After the ServiceExtensionAbility is started, the application displays a modal dialog box. You can call [setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult) to obtain the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| result | AsyncCallback<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Yes| Callback used to return the result.| + +**Example** + + ```ts +import dialogRequest from '@ohos.app.ability.dialogRequest'; + +let want = { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'AuthAccountServiceExtension' +}; + +try { + this.context.requestDialogService(want, (err, result) => { + if (err.code) { + // Process service logic errors. + console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); + return; + } + // Carry out normal service processing. + console.info('requestDialogService succeed, result = ' + JSON.stringify(result)); + }); +} catch (err) { + // Process input parameter errors. + console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); +} + ``` + + ## UIAbilityContext.requestDialogService + +requestDialogService(want: Want): Promise<dialogRequest.RequestResult>; + +Starts a ServiceExtensionAbility that supports modal dialog boxes. After the ServiceExtensionAbility is started, the application displays a modal dialog box. You can call [setRequestResult](js-apis-app-ability-dialogRequest.md#requestcallbacksetrequestresult) to obtain the result, which is returned to the caller in promise mode. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[dialogRequest.RequestResult](js-apis-app-ability-dialogRequest.md)> | Promise used to return the result. + +**Example** + + ```ts +import dialogRequest from '@ohos.app.ability.dialogRequest'; + +let want = { + bundleName: 'com.example.myapplication', + abilityName: 'AuthAccountServiceExtension' +}; + +try { + this.context.requestDialogService(want) + .then((result) => { + // Carry out normal service processing. + console.info('requestDialogService succeed, result = ' + JSON.stringify(result)); + }) + .catch((err) => { + // Process service logic errors. + console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); + }); +} catch (err) { + // Process input parameter errors. + console.error(`requestDialogService failed, code is ${err.code}, message is ${err.message}`); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..602766048157ebee6dfaee6192a7120f051c00dc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @@ -0,0 +1,119 @@ +# WindowExtensionContext + +The **WindowExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WindowExtensionAbility. + +The **WindowExtensionContext** module provides the capabilities of the [WindowExtensionAbility](js-apis-application-windowExtensionAbility.md), including starting the ability. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. +> +> - The APIs of this module can be used only in the stage model. + +## Usage + +Before using the **WindowExtensionContext** module, you must define a child class that inherits from **WindowExtensionAbility**. + +```ts + import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; + + let context; + class WindowExtAbility extends WindowExtensionAbility { + onConnect() { + context = this.context; // Obtain a WindowExtensionContext instance. + } + } +``` + +## WindowExtensionContext.startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void + +Starts an ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + var want = { + bundleName: 'com.example.myapplication', + abilityName: 'MainAbility' + }; + var options = { + windowMode: 102 + }; + + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + return; + } + // Carry out normal service processing. + console.log('startAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + } + ``` + +## WindowExtensionContext.startAbility + +startAbility(want: Want, options?: StartOptions): Promise\ + +Starts an ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```ts + var want = { + bundleName: 'com.example.myapp', + abilityName: 'MainAbility' + }; + var options = { + windowMode: 102, + }; + + try { + this.context.startAbility(want, options) + .then((data) => { + // Carry out normal service processing. + console.log('startAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbility failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}'); + }); + } catch (paramError) { + // Process input parameter errors. + console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}'); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md index 8facc43fc842570c3eb0ea95a141bdaa77dcf252..289a5ebef3d8095fd599e630e0236935551246d1 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -7,7 +7,7 @@ The **WantAgentInfo** module defines the information required for triggering a * | Name | Type | Mandatory| Description | | -------------- | ------------------------------- | ---- | ---------------------- | | wants | Array\ | Yes | Array of all **Want** objects. | -| operationType | wantAgent.OperationType | Yes | Operation type. | +| operationType | [wantAgent.OperationType](js-apis-app-ability-wantAgent.md#operationtype) | Yes | Operation type. | | requestCode | number | Yes | Request code defined by the user.| | wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object. | | extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-InputMethodCommon.md b/en/application-dev/reference/apis/js-apis-inputmethod-InputMethodCommon.md new file mode 100644 index 0000000000000000000000000000000000000000..ed0c80507f40597592206e195dd6780de7133401 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethod-InputMethodCommon.md @@ -0,0 +1,41 @@ +# InputMethodCommon + +> **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. + +The **InputMethodCommon** module provides the common attributes defined by the input method framework. + +## Direction + +Enumerates the directions of cursor movement. + + **System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name | Value | Description | +| ------------ | ---- | ---------- | +| CURSOR_UP | 1 | The cursor moves upward.| +| CURSOR_DOWN | 2 | The cursor moves downward.| +| CURSOR_LEFT | 3 | The caret moves leftward.| +| CURSOR_RIGHT | 4 | The caret moves rightward.| + +## Range + +Describes the range of the selected text. + + **System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name | Type | Readable| Writable| Description | +| ----- | ------ | ---- | ---- | ---------------------------------- | +| start | number | Yes | Yes | Index of the first selected character in the text box.| +| end | number | Yes | Yes | Index of the last selected character in the text box.| + +## Movement + +Describes the direction in which the cursor moves when the text is selected. + + **System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------- | ---- | ---- | ---------------------------------- | +| direction | [Direction](#direction) | Yes | Yes | Direction in which the cursor moves when the text is selected.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index bdc166cd9d3b5a60636214b72311a2c8368c8d6d..be7f5edb92e6b7345a69551ce269fa197c524f24 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -839,6 +839,92 @@ inputMethodController.stopInput().then((result) => { }) ``` +### on('selectByRange')10+ + +on(type: 'selectByRange', callback: Callback<Range>): void + +Enables listening for the selection-by-range event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **selectByRange** indicates the selection-by-range event.| +| callback | Callback<[Range](./js-apis-inputmethod-InputMethodCommon.md#range)> | Yes | Callback used to return the range of the text to be selected.
Your application needs to select the text in the returned range in the text box.| + +**Example** + +```js +inputMethodController.on('selectByRange', (range) => { + console.info('Succeeded in subscribing selectByRange: start: ' + range.start + " , end: " + range.end); +}); +``` + +### off('selectByRange')10+ + +off(type: 'selectByRange'): void + +Disables listening for the selection-by-range event. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **selectByRange** indicates the selection-by-range event.| + +**Example** + +```js +inputMethodController.off('selectByRange'); +``` + +### on('selectByMovement')10+ + +on(type: 'selectByMovement', callback: Callback<Range>): void + +Enables listening for the selection-by-cursor-movement event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **selectByMovement** indicates the selection-by-cursor-movement event.| +| callback | Callback<[Movement](./js-apis-inputmethod-InputMethodCommon.md#movement)> | Yes | Callback used to return the range of the text to be selected.
Your application needs to select the text in the returned range in the text box.| + +**Example** + +```js +inputMethodController.on('selectByMovement', (movement) => { + console.info('Succeeded in subscribing selectByMovement: direction: ' + movement.direction); +}); +``` + +### off('selectByMovement')10+ + +off(type: 'selectByMovement'): void + +Disables listening for the selection-by-cursor-movement event. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **selectByMovement** indicates the selection-by-cursor-movement event.| + +**Example** + +```js +inputMethodController.off('selectByMovement'); +``` + ## InputMethodSetting8+ In the following API examples, you must first use [getSetting](#inputmethodgetsetting9) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 7cfb76e570ae3faf57fdf3ff31cd6cbcb9103eae..fd98e98d1f748ef094d7dd096033fc0459e8ac8b 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1495,6 +1495,241 @@ try { } ``` +### selectByRange10+ + +selectByRange(range: Range, callback: AsyncCallback<void>): void + +Selects text based on the specified range. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| range | [Range](./js-apis-inputmethod-InputMethodCommon.md#range) | Yes | Range of the selected text. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the selection event is sent, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**Example** + +```js +try { + inputClient.selectByRange({start: 0, end: 1}, (err) => { + if (err !== undefined) { + console.error('Failed to selectByRange: ${err.message}'); + return; + } + console.info('Succeeded in selecting by range.'); + }); +} catch (err) { + console.error('Failed to selectByRange: ${err.message}'); +} +``` + +### selectByRange10+ + +selectByRange(range: Range): Promise<void> + +Selects text based on the specified range. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------------------- | ---- | ---------------- | +| range | [Range](./js-apis-inputmethod-InputMethodCommon.md#range) | Yes | Range of the selected text.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**Example** + +```js +try { + inputClient.selectByRange({start: 0, end:1}).then(() => { + console.log('Succeeded in selecting by range.'); + }).catch((err) => { + console.error('Failed to selectByRange: ${err.message}'); + }); +} catch (err) { + console.log('Failed to selectByRange: ${err.message}'); +} +``` + +### selectByMovement10+ + +selectByMovement(movement: Movement, callback: AsyncCallback<void>): void + +Selects text based on the cursor movement direction. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| movement | [Movement](./js-apis-inputmethod-InputMethodCommon.md#movement) | Yes | Direction in which the cursor moves when the text is selected. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the selection event is sent, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**Example** + +```js +try { + inputClient.selectByMovement({direction: 1}, (err) => { + if (err !== undefined) { + console.error('Failed to selectByMovement: ${err.message}'); + return; + } + console.info('Succeeded in selecting by movement.'); + }); +} catch (err) { + console.error('Failed to selectByMovement: ${err.message}'); +} +``` + +### selectByMovement10+ + +selectByMovement(range: Range): Promise<void> + +Selects text based on the specified range. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| movement | [Movement](./js-apis-inputmethod-InputMethodCommon.md#movement) | Yes | Direction in which the cursor moves when the text is selected.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 401 | parameter error. | +| 12800003 | Input method client error. | + +**Example** + +```js +try { + inputClient.selectByMovement({direction: 1}).then(() => { + console.log('Succeeded in selecting by movement.'); + }).catch((err) => { + console.error('Failed to selectByMovement: ${err.message}'); + }); +} catch (err) { + console.log('Failed to selectByMovement: ${err.message}'); +} +``` + +### getTextIndexAtCursor10+ + +getTextIndexAtCursor(callback: AsyncCallback<number>): void + +Obtains the index of the text where the cursor is located. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the text index is obtained, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 401 | parameter error. | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**Example** + +```js +inputClient.getTextIndexAtCursor((err, index) => { + if (err !== undefined) { + console.error('Failed to getTextIndexAtCursor: ${err.message}'); + return; + } + console.info('Succeeded in getTextIndexAtCursor: ' + index); +}); +``` + +### getTextIndexAtCursor10+ + +getTextIndexAtCursor(): Promise<number> + +Obtains the index of the text where the cursor is located. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| --------------------- | --------------------------------------- | +| Promise<number> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**Example** + +```js +inputClient.getTextIndexAtCursor().then((index) => { + console.info('Succeeded in getTextIndexAtCursor: ' + index); +}).catch((err) => { + console.error('Failed to getTextIndexAtCursor: ${err.message}'); +}); +``` + ## EditorAttribute Attribute of the edit box. diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 3dc9a22442c07759d3b594297f7828cb7d5cc95b..5081673fb64f13171a596fd2ed163d4bd8d3c7c9 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -116,8 +116,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | 17700015 | Failed to install the HAPs because they have different configuration information. | | 17700016 | Failed to install the HAP because of insufficient system disk space. | | 17700017 | Failed to install the HAP since the version of the HAP to install is too early. | -| 17700101 | The system service is excepted. | -| 17700103 | I/O operation is failed. | +| 17700018 | Failed to install because the dependent module does not exist. | +| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 8298770c17f71299078a9bc1e541abef94cd6d0b..0ee9b746e29fd8bb0473b664a1acabd0f2f157ae 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,6 +1,7 @@ # @ohos.multimedia.medialibrary (Media Library Management) > **NOTE** +> > The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -118,14 +119,14 @@ media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { console.error('Failed to get first object: ' + err); return; } - console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); for (let i = 1; i < count; i++) { fetchFileResult.getNextObject((err, fileAsset) => { if (fileAsset == undefined) { console.error('Failed to get next object: ' + err); return; } - console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); }) } }); @@ -174,10 +175,10 @@ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { } console.info('Get fetchFileResult success, count: ' + count); fetchFileResult.getFirstObject().then(function(fileAsset) { - console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); for (let i = 1; i < count; i++) { fetchFileResult.getNextObject().then(function(fileAsset) { - console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName); }).catch(function(err) { console.error('Failed to get next object: ' + err); }) @@ -264,9 +265,9 @@ async function example() { const path = await media.getPublicDirectory(DIR_IMAGE); media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => { if (fileAsset != undefined) { - console.info('createAsset successfully, message = ' + err); + console.info('createAsset successfully, message'); } else { - console.info('createAsset failed, message = ' + err); + console.error('createAsset failed, message = ' + err); } }); } @@ -307,7 +308,7 @@ async function example() { media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); }).catch((err) => { - console.info('createAsset failed, message = ' + err); + console.error('createAsset failed, message = ' + err); }); } ``` @@ -354,7 +355,7 @@ async function example() { media.deleteAsset(asset.uri).then(() => { console.info("deleteAsset successfully"); }).catch((err) => { - console.info("deleteAsset failed with error:"+ err); + console.error("deleteAsset failed with error:"+ err); }); } ``` @@ -397,7 +398,7 @@ async function example() { if (err != undefined) { console.info("deleteAsset successfully"); } else { - console.info("deleteAsset failed with error:"+ err); + console.error("deleteAsset failed with error:"+ err); } }); } @@ -426,7 +427,7 @@ media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { if (dicResult == 'Camera/') { console.info('mediaLibraryTest : getPublicDirectory passed'); } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); + console.error('mediaLibraryTest : getPublicDirectory failed'); } }); ``` @@ -460,7 +461,7 @@ async function example() { if (dicResult == 'Camera/') { console.info('MediaLibraryTest : getPublicDirectory'); } else { - console.info('MediaLibraryTest : getPublicDirectory failed'); + console.error('MediaLibraryTest : getPublicDirectory failed'); } } ``` @@ -495,7 +496,7 @@ media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { console.info('album.albumName = ' + album.albumName); console.info('album.count = ' + album.count); } else { - console.info('getAlbum fail, message = ' + err); + console.error('getAlbum fail, message = ' + err); } }) ``` @@ -532,7 +533,7 @@ let AlbumNoArgsfetchOp = { media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ console.info("getAlbums successfully:"+ JSON.stringify(albumList)); }).catch(function(err){ - console.info("getAlbums failed with error:"+ err); + console.error("getAlbums failed with error: " + err); }); ``` @@ -609,10 +610,10 @@ let option = { }; mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { if (err) { - console.log("An error occurred when storing the media asset."); + console.error("An error occurred when storing media resources."); return; } - console.log("Media asset stored."); + console.info("Media resources stored. "); // Obtain the URI that stores the media asset. }); ``` @@ -651,10 +652,10 @@ let option = { relativePath : "Pictures/" }; mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { - console.log("Media asset stored."); + console.info("Media resources stored."); // Obtain the URI that stores the media asset. }).catch((err) => { - console.log("An error occurred when storing the media assets."); + console.error("An error occurred when storing media resources."); }); ``` @@ -695,10 +696,10 @@ let images = [ let index = 1; mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { if (err) { - console.log("An error occurred when previewing the images."); + console.error("An error occurred when previewing the images."); return; } - console.log("Succeeded in previewing the images."); + console.info("Succeeded in previewing the images."); }); ``` @@ -737,10 +738,10 @@ let images = [ */ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { if (err) { - console.log("An error occurred when previewing the images."); + console.error("An error occurred when previewing the images."); return; } - console.log("Succeeded in previewing the images."); + console.info("Succeeded in previewing the images."); }); ``` @@ -785,9 +786,9 @@ let images = [ */ let index = 1; mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { - console.log("Succeeded in previewing the images."); + console.info("Succeeded in previewing the images."); }).catch((err) => { - console.log("An error occurred when previewing the images."); + console.error("An error occurred when previewing the images."); }); ``` @@ -820,10 +821,10 @@ let option : mediaLibrary.MediaSelectOption = { }; mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { if (err) { - console.log("An error occurred when selecting the media asset."); + console.error("An error occurred when selecting media resources."); return; } - console.log("Media asset selected."); + console.info("Media resources selected."); // Obtain the media selection value. }); ``` @@ -861,10 +862,10 @@ let option : mediaLibrary.MediaSelectOption = { count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { - console.log("Media asset selected."); + console.info("Media resources selected."); // Obtain the media selection value. }).catch((err) => { - console.log("An error occurred when selecting the media assets."); + console.error("An error occurred when selecting media resources."); }); ``` @@ -899,7 +900,7 @@ async function example() { console.info('get distributed info is undefined!') } }).catch((err) => { - console.info("get distributed info failed with error:" + err); + console.error("get distributed info failed with error:" + err); }); } ``` @@ -932,7 +933,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail, message = ' + err) + console.error('get distributed fail, message = ' + err) } }) } @@ -970,7 +971,7 @@ async function example() { console.info('get distributed info is undefined!') } }).catch((err) => { - console.info("get distributed info failed with error:" + err); + console.error("get distributed info failed with error: " + err); }); } ``` @@ -1003,7 +1004,7 @@ async function example() { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail, message = ' + err) + console.error('get distributed fail, message = ' + err) } }) } @@ -1033,9 +1034,9 @@ Provides APIs for encapsulating file asset attributes. | relativePath8+ | string | Yes | Yes | Relative public directory of the file. | | parent8+ | number | Yes | No | Parent directory ID. | | size | number | Yes | No | File size, in bytes. | -| dateAdded | number | Yes | No | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| dateModified | number | Yes | No | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| dateTaken | number | Yes | No | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| dateAdded | number | Yes | No | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| dateModified | number | Yes | No | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| +| dateTaken | number | Yes | No | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | | artist8+ | string | Yes | No | Artist of the file. | | audioAlbum8+ | string | Yes | No | Audio album. | | width | number | Yes | No | Image width, in pixels. | @@ -1116,7 +1117,7 @@ async function example() { asset.isDirectory().then(function(isDirectory){ console.info("isDirectory result:"+ isDirectory); }).catch(function(err){ - console.info("isDirectory failed with error:"+ err); + console.error("isDirectory failed with error: " + err); }); } ``` @@ -1212,7 +1213,7 @@ Opens this file asset. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ----------------------------------- | | mode | string | Yes | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).| -| callback | AsyncCallback<number> | Yes | Callback used to return the file handle. | +| callback | AsyncCallback<number> | Yes | Callback used to return the file descriptor. | **Example** @@ -1226,7 +1227,7 @@ async function example() { if(fd > 0){ asset.close(fd); }else{ - console.info('File Open Failed!' + openError); + console.error('File Open Failed!' + openError); } }); } @@ -1256,7 +1257,7 @@ Opens this file asset. This API uses a promise to return the result. | Type | Description | | --------------------- | ------------- | -| Promise<number> | Promise used to return the file handle.| +| Promise<number> | Promise used to return the file descriptor.| **Example** @@ -1271,7 +1272,7 @@ async function example() { console.info('File fd!' + fd); }) .catch((err) => { - console.info('File err!' + err); + console.error('File err!' + err); }); } ``` @@ -1311,15 +1312,15 @@ async function example() { console.info('File fd!' + fd); asset.close(fd, (closeErr) => { if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + console.error('mediaLibraryTest : close : FAIL ' + closeErr); + console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); } else { console.info("=======asset.close success====>"); } }); }) .catch((err) => { - console.info('File err!' + err); + console.error('File err!' + err); }); } ``` @@ -1364,8 +1365,8 @@ async function example() { console.info('File fd!' + fd); asset.close(fd).then((closeErr) => { if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + console.error('mediaLibraryTest : close : FAIL ' + closeErr); + console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL'); } else { console.info("=======asset.close success====>"); @@ -1373,7 +1374,7 @@ async function example() { }); }) .catch((err) => { - console.info('File err!' + err); + console.error('File err!' + err); }); } ``` @@ -1494,7 +1495,7 @@ async function example() { console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); }) .catch((err) => { - console.info('mediaLibraryTest : getThumbnail fail'+ err); + console.error('mediaLibraryTest : getThumbnail fail, err: ' + err); }); } ``` @@ -1575,7 +1576,7 @@ async function example() { asset.favorite(true).then(function() { console.info("favorite successfully"); }).catch(function(err){ - console.info("favorite failed with error:"+ err); + console.error("favorite failed with error: " + err); }); } ``` @@ -1653,7 +1654,7 @@ async function example() { asset.isFavorite().then(function(isFavorite){ console.info("isFavorite result:"+ isFavorite); }).catch(function(err){ - console.info("isFavorite failed with error:"+ err); + console.error("isFavorite failed with error: " + err); }); } ``` @@ -1739,7 +1740,7 @@ async function example() { asset.trash(true).then(function() { console.info("trash successfully"); }).catch(function(err){ - console.info("trash failed with error:"+ err); + console.error("trash failed with error: " + err); }); } ``` @@ -1894,7 +1895,6 @@ async function example() { console.info('mediaLibraryTest : isAfterLast:' + result); console.info('mediaLibraryTest : isAfterLast end'); fetchFileResult.close(); - } } } @@ -1957,7 +1957,7 @@ async function example() { console.error('Failed '); return; } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1992,7 +1992,7 @@ async function example() { fetchFileResult.getFirstObject().then(function(fileAsset){ console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); }).catch(function(err){ - console.info("getFirstObject failed with error:"+ err); + console.error("getFirstObject failed with error: " + err); }); } ``` @@ -2099,7 +2099,7 @@ async function example() { console.error('Failed '); return; } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -2168,7 +2168,7 @@ async function example() { console.error('Failed '); return; } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -2207,9 +2207,9 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.log('fileAsset.displayName : ' + fileAsset.displayName); + console.info('fileAsset.displayName : ' + fileAsset.displayName); }).catch(function (err) { - console.info("getFileAssets failed with error:" + err); + console.error("getFileAssets failed with error: " + err); }); } ``` @@ -2247,7 +2247,7 @@ async function example() { return; } for (let i = 0; i < fetchFileResult.getCount(); i++) { - console.log('fileAsset.displayName : ' + fileAsset[i].displayName); + console.info('fileAsset.displayName : ' + fileAsset[i].displayName); } }) } @@ -2334,7 +2334,7 @@ async function example() { console.error('Failed '); return; } - console.log('Modify successful.'); + console.info('Modify successful.'); }) } ``` @@ -2369,7 +2369,7 @@ async function example() { album.commitModify().then(function() { console.info("commitModify successfully"); }).catch(function(err){ - console.info("commitModify failed with error:"+ err); + console.error("commitModify failed with error: " + err); }); } ``` @@ -2449,9 +2449,9 @@ async function example() { const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + console.info("getFileAssets successfully: " + JSON.stringify(albumFetchFileResult)); }).catch(function(err){ - console.info("getFileAssets failed with error:"+ err); + console.error("getFileAssets failed with error: " + err); }); } ``` @@ -2505,9 +2505,9 @@ Enumerates key file information. | MIME_TYPE | "mime_type" | Extended file attributes. | | MEDIA_TYPE | "media_type" | Media type. | | SIZE | "size" | File size, in bytes. | -| DATE_ADDED | "date_added" | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_MODIFIED | "date_modified" | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_TAKEN | "date_taken" | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_ADDED | "date_added" | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | "date_modified" | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| +| DATE_TAKEN | "date_taken" | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | | TITLE | "title" | Title in the file. | | ARTIST | "artist" | Artist of the file. | | AUDIOALBUM | "audio_album" | Audio album. | @@ -2581,6 +2581,8 @@ Describes the image size. Implements the media asset option. +> **NOTE** +> > This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 06bd296eab73896a8034d3d8245bf05e09d9548c..2ad181cfd753f7ba9c2a3c42328f3d318e0af1e2 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -35,7 +35,7 @@ Publishes a notification. This API uses an asynchronous callback to return the r // publish callback function publishCallback(err) { if (err.code) { - console.info("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}`); } else { console.info("publish success"); } @@ -55,8 +55,6 @@ let notificationRequest = { Notification.publish(notificationRequest, publishCallback); ``` - - ## Notification.publish publish(request: NotificationRequest): Promise\ @@ -118,7 +116,7 @@ Publishes a notification to a specified user. This API uses an asynchronous call // publish callback function publishCallback(err) { if (err.code) { - console.info("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}`); } else { console.info("publish success"); } @@ -298,8 +296,6 @@ function cancelAllCallback(err) { Notification.cancelAll(cancelAllCallback); ``` - - ## Notification.cancelAll cancelAll(): Promise\ @@ -316,8 +312,6 @@ Notification.cancelAll().then(() => { }); ``` - - ## Notification.addSlot addSlot(slot: NotificationSlot, callback: AsyncCallback\): void @@ -355,8 +349,6 @@ let notificationSlot = { Notification.addSlot(notificationSlot, addSlotCallBack); ``` - - ## Notification.addSlot addSlot(slot: NotificationSlot): Promise\ @@ -387,8 +379,6 @@ Notification.addSlot(notificationSlot).then(() => { }); ``` - - ## Notification.addSlot addSlot(type: SlotType, callback: AsyncCallback\): void @@ -418,8 +408,6 @@ function addSlotCallBack(err) { Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack); ``` - - ## Notification.addSlot addSlot(type: SlotType): Promise\ @@ -442,8 +430,6 @@ Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { }); ``` - - ## Notification.addSlots addSlots(slots: Array\, callback: AsyncCallback\): void @@ -485,8 +471,6 @@ notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray, addSlotsCallBack); ``` - - ## Notification.addSlots addSlots(slots: Array\): Promise\ @@ -521,8 +505,6 @@ Notification.addSlots(notificationSlotArray).then(() => { }); ``` - - ## Notification.getSlot getSlot(slotType: SlotType, callback: AsyncCallback\): void @@ -553,8 +535,6 @@ let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType, getSlotCallback); ``` - - ## Notification.getSlot getSlot(slotType: SlotType): Promise\ @@ -584,8 +564,6 @@ Notification.getSlot(slotType).then((data) => { }); ``` - - ## Notification.getSlots getSlots(callback: AsyncCallback>): void @@ -614,8 +592,6 @@ function getSlotsCallback(err, data) { Notification.getSlots(getSlotsCallback); ``` - - ## Notification.getSlots getSlots(): Promise\> @@ -638,8 +614,6 @@ Notification.getSlots().then((data) => { }); ``` - - ## Notification.removeSlot removeSlot(slotType: SlotType, callback: AsyncCallback\): void @@ -670,8 +644,6 @@ let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType,removeSlotCallback); ``` - - ## Notification.removeSlot removeSlot(slotType: SlotType): Promise\ @@ -695,8 +667,6 @@ Notification.removeSlot(slotType).then(() => { }); ``` - - ## Notification.removeAllSlots removeAllSlots(callback: AsyncCallback\): void @@ -724,8 +694,6 @@ function removeAllCallBack(err) { Notification.removeAllSlots(removeAllCallBack); ``` - - ## Notification.removeAllSlots removeAllSlots(): Promise\ @@ -742,8 +710,6 @@ Notification.removeAllSlots().then(() => { }); ``` - - ## Notification.subscribe subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void @@ -787,8 +753,6 @@ let info = { Notification.subscribe(subscriber, info, subscribeCallback); ``` - - ## Notification.subscribe subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void @@ -827,8 +791,6 @@ let subscriber = { Notification.subscribe(subscriber, subscribeCallback); ``` - - ## Notification.subscribe subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise\ @@ -862,8 +824,6 @@ Notification.subscribe(subscriber).then(() => { }); ``` - - ## Notification.unsubscribe unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void @@ -902,8 +862,6 @@ let subscriber = { Notification.unsubscribe(subscriber, unsubscribeCallback); ``` - - ## Notification.unsubscribe unsubscribe(subscriber: NotificationSubscriber): Promise\ @@ -936,8 +894,6 @@ Notification.unsubscribe(subscriber).then(() => { }); ``` - - ## Notification.enableNotification enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -974,8 +930,6 @@ let bundle = { Notification.enableNotification(bundle, false, enableNotificationCallback); ``` - - ## Notification.enableNotification enableNotification(bundle: BundleOption, enable: boolean): Promise\ @@ -1006,8 +960,6 @@ Notification.enableNotification(bundle, false).then(() => { }); ``` - - ## Notification.isNotificationEnabled isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void @@ -1043,8 +995,6 @@ let bundle = { Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` - - ## Notification.isNotificationEnabled isNotificationEnabled(bundle: BundleOption): Promise\ @@ -1080,8 +1030,6 @@ Notification.isNotificationEnabled(bundle).then((data) => { }); ``` - - ## Notification.isNotificationEnabled isNotificationEnabled(callback: AsyncCallback\): void @@ -1114,8 +1062,6 @@ function isNotificationEnabledCallback(err, data) { Notification.isNotificationEnabled(isNotificationEnabledCallback); ``` - - ## Notification.isNotificationEnabled isNotificationEnabled(): Promise\ @@ -1148,8 +1094,6 @@ Notification.isNotificationEnabled().then((data) => { }); ``` - - ## Notification.displayBadge displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -1186,8 +1130,6 @@ let bundle = { Notification.displayBadge(bundle, false, displayBadgeCallback); ``` - - ## Notification.displayBadge displayBadge(bundle: BundleOption, enable: boolean): Promise\ @@ -1218,8 +1160,6 @@ Notification.displayBadge(bundle, false).then(() => { }); ``` - - ## Notification.isBadgeDisplayed isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void @@ -1255,8 +1195,6 @@ let bundle = { Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); ``` - - ## Notification.isBadgeDisplayed isBadgeDisplayed(bundle: BundleOption): Promise\ @@ -1292,8 +1230,6 @@ Notification.isBadgeDisplayed(bundle).then((data) => { }); ``` - - ## Notification.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void @@ -1333,8 +1269,6 @@ let notificationSlot = { Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); ``` - - ## Notification.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ @@ -1368,8 +1302,6 @@ Notification.setSlotByBundle(bundle, notificationSlot).then(() => { }); ``` - - ## Notification.getSlotsByBundle getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void @@ -1405,8 +1337,6 @@ let bundle = { Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); ``` - - ## Notification.getSlotsByBundle getSlotsByBundle(bundle: BundleOption): Promise> @@ -1442,8 +1372,6 @@ Notification.getSlotsByBundle(bundle).then((data) => { }); ``` - - ## Notification.getSlotNumByBundle getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void @@ -1479,8 +1407,6 @@ let bundle = { Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` - - ## Notification.getSlotNumByBundle getSlotNumByBundle(bundle: BundleOption): Promise\ @@ -1516,8 +1442,6 @@ Notification.getSlotNumByBundle(bundle).then((data) => { }); ``` - - ## Notification.remove remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason, callback: AsyncCallback\): void @@ -1560,8 +1484,6 @@ let reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(bundle, notificationKey, reason, removeCallback); ``` - - ## Notification.remove remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason): Promise\ @@ -1598,8 +1520,6 @@ Notification.remove(bundle, notificationKey, reason).then(() => { }); ``` - - ## Notification.remove remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): void @@ -1636,8 +1556,6 @@ let reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; Notification.remove(hashCode, reason, removeCallback); ``` - - ## Notification.remove remove(hashCode: string, reason: RemoveReason): Promise\ @@ -1667,8 +1585,6 @@ Notification.remove(hashCode, reason).then(() => { }); ``` - - ## Notification.removeAll removeAll(bundle: BundleOption, callback: AsyncCallback\): void @@ -1704,8 +1620,6 @@ let bundle = { Notification.removeAll(bundle, removeAllCallback); ``` - - ## Notification.removeAll removeAll(callback: AsyncCallback\): void @@ -1738,8 +1652,6 @@ function removeAllCallback(err) { Notification.removeAll(removeAllCallback); ``` - - ## Notification.removeAll removeAll(bundle?: BundleOption): Promise\ @@ -1861,8 +1773,6 @@ function getAllActiveNotificationsCallback(err, data) { Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); ``` - - ## Notification.getAllActiveNotifications getAllActiveNotifications(): Promise\\> @@ -1889,8 +1799,6 @@ Notification.getAllActiveNotifications().then((data) => { }); ``` - - ## Notification.getActiveNotificationCount getActiveNotificationCount(callback: AsyncCallback\): void @@ -1919,8 +1827,6 @@ function getActiveNotificationCountCallback(err, data) { Notification.getActiveNotificationCount(getActiveNotificationCountCallback); ``` - - ## Notification.getActiveNotificationCount getActiveNotificationCount(): Promise\ @@ -1943,8 +1849,6 @@ Notification.getActiveNotificationCount().then((data) => { }); ``` - - ## Notification.getActiveNotifications getActiveNotifications(callback: AsyncCallback>): void @@ -1973,8 +1877,6 @@ function getActiveNotificationsCallback(err, data) { Notification.getActiveNotifications(getActiveNotificationsCallback); ``` - - ## Notification.getActiveNotifications getActiveNotifications(): Promise\\> @@ -1997,8 +1899,6 @@ Notification.getActiveNotifications().then((data) => { }); ``` - - ## Notification.cancelGroup8+ cancelGroup(groupName: string, callback: AsyncCallback\): void @@ -2030,8 +1930,6 @@ let groupName = "GroupName"; Notification.cancelGroup(groupName, cancelGroupCallback); ``` - - ## Notification.cancelGroup8+ cancelGroup(groupName: string): Promise\ @@ -2055,8 +1953,6 @@ Notification.cancelGroup(groupName).then(() => { }); ``` - - ## Notification.removeGroupByBundle8+ removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void @@ -2094,8 +1990,6 @@ let groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); ``` - - ## Notification.removeGroupByBundle8+ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ @@ -2125,8 +2019,6 @@ Notification.removeGroupByBundle(bundleOption, groupName).then(() => { }); ``` - - ## Notification.setDoNotDisturbDate8+ setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): void @@ -2166,8 +2058,6 @@ let doNotDisturbDate = { Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); ``` - - ## Notification.setDoNotDisturbDate8+ setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ @@ -2241,8 +2131,6 @@ let userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` - - ## Notification.setDoNotDisturbDate8+ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ @@ -2311,8 +2199,6 @@ function getDoNotDisturbDateCallback(err, data) { Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); ``` - - ## Notification.getDoNotDisturbDate8+ getDoNotDisturbDate(): Promise\ @@ -2375,8 +2261,6 @@ let userId = 1; Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); ``` - - ## Notification.getDoNotDisturbDate8+ getDoNotDisturbDate(userId: number): Promise\ @@ -2444,8 +2328,6 @@ function supportDoNotDisturbModeCallback(err,data) { Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); ``` - - ## Notification.supportDoNotDisturbMode8+ supportDoNotDisturbMode(): Promise\ @@ -2472,8 +2354,6 @@ Notification.supportDoNotDisturbMode().then((data) => { }); ``` - - ## Notification.isSupportTemplate8+ isSupportTemplate(templateName: string, callback: AsyncCallback\): void @@ -2504,8 +2384,6 @@ function isSupportTemplateCallback(err, data) { Notification.isSupportTemplate(templateName, isSupportTemplateCallback); ``` - - ## Notification.isSupportTemplate8+ isSupportTemplate(templateName: string): Promise\ @@ -2536,8 +2414,6 @@ Notification.isSupportTemplate(templateName).then((data) => { }); ``` - - ## Notification.requestEnableNotification8+ requestEnableNotification(callback: AsyncCallback\): void @@ -2566,8 +2442,6 @@ function requestEnableNotificationCallback(err) { Notification.requestEnableNotification(requestEnableNotificationCallback); ``` - - ## Notification.requestEnableNotification8+ requestEnableNotification(): Promise\ @@ -2620,8 +2494,6 @@ let enable = true; Notification.enableDistributed(enable, enabledNotificationCallback); ``` - - ## Notification.enableDistributed8+ enableDistributed(enable: boolean): Promise\ @@ -2678,8 +2550,6 @@ function isDistributedEnabledCallback(err, data) { Notification.isDistributedEnabled(isDistributedEnabledCallback); ``` - - ## Notification.isDistributedEnabled8+ isDistributedEnabled(): Promise\ @@ -2743,8 +2613,6 @@ let enable = true; Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundleCallback); ``` - - ## Notification.enableDistributedByBundle8+ enableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise\ @@ -2814,8 +2682,6 @@ let bundle = { Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); ``` - - ## Notification.isDistributedEnabledByBundle8+ isDistributedEnabledByBundle(bundle: BundleOption): Promise\ @@ -2885,8 +2751,6 @@ function getDeviceRemindTypeCallback(err,data) { Notification.getDeviceRemindType(getDeviceRemindTypeCallback); ``` - - ## Notification.getDeviceRemindType8+ getDeviceRemindType(): Promise\ @@ -3381,8 +3245,6 @@ Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { }); ``` - - ## NotificationSubscriber Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](#notificationsubscribe). @@ -3797,8 +3659,6 @@ Notification.enableNotification(bundle, false).then(() => { | bundle | string | Yes | Yes | Bundle information of the application.| | uid | number | Yes | Yes | User ID.| - - ## NotificationKey **System capability**: SystemCapability.Notification.Notification diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md index a878376a3c035ac7ad112d95a4d8ebfa47123ee6..27962f40126ecdc7f533e17516378bb490797c4d 100644 --- a/en/application-dev/reference/apis/js-apis-notificationManager.md +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -29,6 +29,8 @@ Publishes a notification. This API uses an asynchronous callback to return the r **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------------- | | 1600001 | Internal error. | @@ -44,13 +46,13 @@ Publishes a notification. This API uses an asynchronous callback to return the r // publish callback function publishCallback(err) { if (err) { - console.info("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publish success"); } } // NotificationRequest object -let notificationRequest = { +let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -80,6 +82,8 @@ Publishes a notification. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------------- | | 1600001 | Internal error. | @@ -93,7 +97,7 @@ Publishes a notification. This API uses a promise to return the result. ```ts // NotificationRequest object -let notificationRequest = { +let notificationRequest: notificationManager.NotificationRequest = { notificationId: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -132,6 +136,8 @@ Publishes a notification to a specified user. This API uses an asynchronous call **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------------- | | 1600001 | Internal error. | @@ -148,7 +154,7 @@ Publishes a notification to a specified user. This API uses an asynchronous call // publish callback function publishCallback(err) { if (err) { - console.info("publish failed " + JSON.stringify(err)); + console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publish success"); } @@ -156,7 +162,7 @@ function publishCallback(err) { // User ID let userId = 1; // NotificationRequest object -let notificationRequest = { +let notificationRequest: notificationManager.NotificationRequest = { id: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -191,6 +197,8 @@ Publishes a notification to a specified user. This API uses a promise to return **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------------- | | 1600001 | Internal error. | @@ -204,7 +212,7 @@ Publishes a notification to a specified user. This API uses a promise to return **Example** ```ts -let notificationRequest = { +let notificationRequest: notificationManager.NotificationRequest = { notificationId: 1, content: { contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -242,6 +250,8 @@ Cancels a notification with the specified ID and label. This API uses an asynchr **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -255,7 +265,7 @@ Cancels a notification with the specified ID and label. This API uses an asynchr // cancel callback function cancelCallback(err) { if (err) { - console.info("cancel failed " + JSON.stringify(err)); + console.error(`cancel failed, code is ${err.code}, message is ${err.message}`); } else { console.info("cancel success"); } @@ -280,6 +290,8 @@ Cancels a notification with the specified ID and optional label. This API uses a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -312,6 +324,8 @@ Cancels a notification with the specified ID. This API uses an asynchronous call **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -325,7 +339,7 @@ Cancels a notification with the specified ID. This API uses an asynchronous call // cancel callback function cancelCallback(err) { if (err) { - console.info("cancel failed " + JSON.stringify(err)); + console.error(`cancel failed, code is ${err.code}, message is ${err.message}`); } else { console.info("cancel success"); } @@ -343,6 +357,8 @@ Cancels all notifications. This API uses an asynchronous callback to return the **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -361,7 +377,7 @@ Cancels all notifications. This API uses an asynchronous callback to return the // cancel callback function cancelAllCallback(err) { if (err) { - console.info("cancelAll failed " + JSON.stringify(err)); + console.error(`cancelAll failed, code is ${err.code}, message is ${err.message}`); } else { console.info("cancelAll success"); } @@ -379,6 +395,8 @@ Cancels all notifications. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -414,6 +432,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -426,7 +446,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r // addSlot callback function addSlotCallBack(err) { if (err) { - console.info("addSlot failed " + JSON.stringify(err)); + console.error(`addSlot failed, code is ${err.code}, message is ${err.message}`); } else { console.info("addSlot success"); } @@ -458,6 +478,8 @@ Adds a notification slot. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -493,6 +515,8 @@ Adds a notification slot of a specified type. This API uses an asynchronous call **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -505,7 +529,7 @@ Adds a notification slot of a specified type. This API uses an asynchronous call // addSlot callback function addSlotCallBack(err) { if (err) { - console.info("addSlot failed " + JSON.stringify(err)); + console.error(`addSlot failed, code is ${err.code}, message is ${err.message}`); } else { console.info("addSlot success"); } @@ -529,6 +553,8 @@ Adds a notification slot of a specified type. This API uses a promise to return **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -564,6 +590,8 @@ Adds an array of notification slots. This API uses an asynchronous callback to r **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -576,7 +604,7 @@ Adds an array of notification slots. This API uses an asynchronous callback to r // addSlots callback function addSlotsCallBack(err) { if (err) { - console.info("addSlots failed " + JSON.stringify(err)); + console.error(`addSlots failed, code is ${err.code}, message is ${err.message}`); } else { console.info("addSlots success"); } @@ -612,6 +640,8 @@ Adds an array of notification slots. This API uses a promise to return the resul **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -651,6 +681,8 @@ Obtains a notification slot of a specified type. This API uses an asynchronous c **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -663,7 +695,7 @@ Obtains a notification slot of a specified type. This API uses an asynchronous c // getSlot callback function getSlotCallback(err,data) { if (err) { - console.info("getSlot failed " + JSON.stringify(err)); + console.error(`getSlot failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getSlot success"); } @@ -694,6 +726,8 @@ Obtains a notification slot of a specified type. This API uses a promise to retu **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -719,6 +753,8 @@ Obtains all notification slots of this application. This API uses an asynchronou **Parameters** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | -------------------- | | callback | AsyncCallback\\> | Yes | Callback used to return all notification slots of the current application.| @@ -737,7 +773,7 @@ Obtains all notification slots of this application. This API uses an asynchronou // getSlots callback function getSlotsCallback(err,data) { if (err) { - console.info("getSlots failed " + JSON.stringify(err)); + console.error(`getSlots failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getSlots success"); } @@ -761,6 +797,8 @@ Obtains all notification slots of this application. This API uses a promise to r **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -792,6 +830,8 @@ Removes a notification slot of a specified type. This API uses an asynchronous c **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -804,7 +844,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c // removeSlot callback function removeSlotCallback(err) { if (err) { - console.info("removeSlot failed " + JSON.stringify(err)); + console.error(`removeSlot failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeSlot success"); } @@ -829,6 +869,8 @@ Removes a notification slot of a specified type. This API uses a promise to retu **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -860,6 +902,8 @@ Removes all notification slots. This API uses an asynchronous callback to return **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -871,7 +915,7 @@ Removes all notification slots. This API uses an asynchronous callback to return ```ts function removeAllCallBack(err) { if (err) { - console.info("removeAllSlots failed " + JSON.stringify(err)); + console.error(`removeAllSlots failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeAllSlots success"); } @@ -889,6 +933,8 @@ Removes all notification slots. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -925,6 +971,8 @@ Sets whether to enable notification for a specified application. This API uses a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -937,7 +985,7 @@ Sets whether to enable notification for a specified application. This API uses a ```ts function setNotificationEnablenCallback(err) { if (err) { - console.info("setNotificationEnablenCallback failed " + JSON.stringify(err)); + console.error(`setNotificationEnablenCallback failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setNotificationEnablenCallback success"); } @@ -969,6 +1017,8 @@ Sets whether to enable notification for a specified application. This API uses a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1008,6 +1058,8 @@ Checks whether notification is enabled for a specified application. This API use **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1020,7 +1072,7 @@ Checks whether notification is enabled for a specified application. This API use ```ts function isNotificationEnabledCallback(err, data) { if (err) { - console.info("isNotificationEnabled failed " + JSON.stringify(err)); + console.error(`isNotificationEnabled failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isNotificationEnabled success"); } @@ -1057,6 +1109,8 @@ Checks whether notification is enabled for a specified application. This API use **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1095,6 +1149,8 @@ Checks whether notification is enabled for this application. This API uses an as **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1106,7 +1162,7 @@ Checks whether notification is enabled for this application. This API uses an as ```ts function isNotificationEnabledCallback(err, data) { if (err) { - console.info("isNotificationEnabled failed " + JSON.stringify(err)); + console.error(`isNotificationEnabled failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isNotificationEnabled success"); } @@ -1141,6 +1197,8 @@ Checks whether notification is enabled for the current application. This API use **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1178,6 +1236,8 @@ Sets whether to enable the notification badge for a specified application. This **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1190,7 +1250,7 @@ Sets whether to enable the notification badge for a specified application. This ```ts function displayBadgeCallback(err) { if (err) { - console.info("displayBadge failed " + JSON.stringify(err)); + console.error(`displayBadge failed, code is ${err.code}, message is ${err.message}`); } else { console.info("displayBadge success"); } @@ -1222,6 +1282,8 @@ Sets whether to enable the notification badge for a specified application. This **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1261,6 +1323,8 @@ Checks whether the notification badge is enabled for a specified application. Th **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1273,7 +1337,7 @@ Checks whether the notification badge is enabled for a specified application. Th ```ts function isBadgeDisplayedCallback(err, data) { if (err) { - console.info("isBadgeDisplayed failed " + JSON.stringify(err)); + console.error(`isBadgeDisplayed failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isBadgeDisplayed success"); } @@ -1310,6 +1374,8 @@ Checks whether the notification badge is enabled for a specified application. Th **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1328,6 +1394,79 @@ notificationManager.isBadgeDisplayed(bundle).then((data) => { }); ``` +## notificationManager.setBadgeNumber10+ + +setBadgeNumber(badgeNumber: number): Promise\ + +Sets the notification badge number. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------- | +| badgeNumber | number | Yes | Notification badge number to set.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600012 | No memory space. | + +**Example** + +```ts +let badgeNumber = 10 +notificationManager.setBadgeNumber(badgeNumber).then(() => { + console.info("displayBadge success"); +}); +``` + +## notificationManager.setBadgeNumber10+ + +setBadgeNumber(badgeNumber: number, callback: AsyncCallback\): void + +Sets the notification badge number. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------- | ---- | ------------------ | +| badgeNumber | number | Yes | Notification badge number to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600012 | No memory space. | + +**Example** + +```ts +function setBadgeNumberCallback(err) { + if (err) { + console.info(`displayBadge failed code is ${err.code}, message is ${err.message}`); + } else { + console.info("displayBadge success"); + } +} + +let badgeNumber = 10 +notificationManager.setBadgeNumber(badgeNumber, setBadgeNumberCallback); +``` + ## notificationManager.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void @@ -1350,6 +1489,8 @@ Sets the notification slot for a specified application. This API uses an asynchr **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1362,7 +1503,7 @@ Sets the notification slot for a specified application. This API uses an asynchr ```ts function setSlotByBundleCallback(err) { if (err) { - console.info("setSlotByBundle failed " + JSON.stringify(err)); + console.error(`setSlotByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setSlotByBundle success"); } @@ -1397,6 +1538,8 @@ Sets the notification slot for a specified application. This API uses a promise **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1439,6 +1582,8 @@ Obtains the notification slots of a specified application. This API uses an asyn **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1451,7 +1596,7 @@ Obtains the notification slots of a specified application. This API uses an asyn ```ts function getSlotsByBundleCallback(err, data) { if (err) { - console.info("getSlotsByBundle failed " + JSON.stringify(err)); + console.error(`getSlotByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getSlotsByBundle success"); } @@ -1488,6 +1633,8 @@ Obtains the notification slots of a specified application. This API uses a promi **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1527,6 +1674,8 @@ Obtains the number of notification slots of a specified application. This API us **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1539,7 +1688,7 @@ Obtains the number of notification slots of a specified application. This API us ```ts function getSlotNumByBundleCallback(err, data) { if (err) { - console.info("getSlotNumByBundle failed " + JSON.stringify(err)); + console.error(`getSlotByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getSlotNumByBundle success"); } @@ -1576,6 +1725,8 @@ Obtains the number of notification slots of a specified application. This API us **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1626,7 +1777,7 @@ Obtains all active notifications. This API uses an asynchronous callback to retu ```ts function getAllActiveNotificationsCallback(err, data) { if (err) { - console.info("getAllActiveNotifications failed " + JSON.stringify(err)); + console.error(`getAllActiveNotifications failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getAllActiveNotifications success"); } @@ -1655,6 +1806,8 @@ Obtains all active notifications. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1685,6 +1838,8 @@ Obtains the number of active notifications of this application. This API uses an **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1696,7 +1851,7 @@ Obtains the number of active notifications of this application. This API uses an ```ts function getActiveNotificationCountCallback(err, data) { if (err) { - console.info("getActiveNotificationCount failed " + JSON.stringify(err)); + console.error(`getActiveNotificationCount failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getActiveNotificationCount success"); } @@ -1721,6 +1876,8 @@ Obtains the number of active notifications of this application. This API uses a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1751,6 +1908,8 @@ Obtains active notifications of this application. This API uses an asynchronous **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1762,7 +1921,7 @@ Obtains active notifications of this application. This API uses an asynchronous ```ts function getActiveNotificationsCallback(err, data) { if (err) { - console.info("getActiveNotifications failed " + JSON.stringify(err)); + console.error(`getActiveNotifications failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getActiveNotifications success"); } @@ -1787,6 +1946,8 @@ Obtains active notifications of this application. This API uses a promise to ret **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1818,6 +1979,8 @@ Cancels notifications under a notification group of this application. This API u **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1829,7 +1992,7 @@ Cancels notifications under a notification group of this application. This API u ```ts function cancelGroupCallback(err) { if (err) { - console.info("cancelGroup failed " + JSON.stringify(err)); + console.error(`cancelGroup failed, code is ${err.code}, message is ${err.message}`); } else { console.info("cancelGroup success"); } @@ -1856,6 +2019,8 @@ Cancels notifications under a notification group of this application. This API u **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1893,6 +2058,8 @@ Removes notifications under a notification group of a specified application. Thi **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1905,7 +2072,7 @@ Removes notifications under a notification group of a specified application. Thi ```ts function removeGroupByBundleCallback(err) { if (err) { - console.info("removeGroupByBundle failed " + JSON.stringify(err)); + console.error(`removeGroupByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeGroupByBundle success"); } @@ -1938,6 +2105,8 @@ Removes notifications under a notification group of a specified application. Thi **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -1976,6 +2145,8 @@ Sets the DND time. This API uses an asynchronous callback to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -1987,7 +2158,7 @@ Sets the DND time. This API uses an asynchronous callback to return the result. ```ts function setDoNotDisturbDateCallback(err) { if (err) { - console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + console.error(`setDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setDoNotDisturbDate success"); } @@ -2022,6 +2193,8 @@ Sets the DND time. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2064,6 +2237,8 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2076,7 +2251,7 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t ```ts function setDoNotDisturbDateCallback(err) { if (err) { - console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + console.error(`setDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setDoNotDisturbDate success"); } @@ -2114,6 +2289,8 @@ Sets the DND time for a specified user. This API uses a promise to return the re **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2158,6 +2335,8 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2169,7 +2348,7 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul ```ts function getDoNotDisturbDateCallback(err,data) { if (err) { - console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + console.error(`getDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getDoNotDisturbDate success"); } @@ -2198,6 +2377,8 @@ Obtains the DND time. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2234,6 +2415,8 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2246,7 +2429,7 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback ```ts function getDoNotDisturbDateCallback(err,data) { if (err) { - console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + console.error(`getDoNotDisturbDate failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getDoNotDisturbDate success"); } @@ -2283,6 +2466,8 @@ Obtains the DND time of a specified user. This API uses a promise to return the **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2301,9 +2486,9 @@ notificationManager.getDoNotDisturbDate(userId).then((data) => { ``` -## notificationManager.supportDoNotDisturbMode +## notificationManager.isSupportDoNotDisturbMode -supportDoNotDisturbMode(callback: AsyncCallback\): void + isSupportDoNotDisturbMode(callback: AsyncCallback\): void Checks whether DND mode is supported. This API uses an asynchronous callback to return the result. @@ -2330,20 +2515,20 @@ Checks whether DND mode is supported. This API uses an asynchronous callback to **Example** ```ts -function supportDoNotDisturbModeCallback(err,data) { +function isSupportDoNotDisturbModeCallback(err,data) { if (err) { - console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); + console.error(`isSupportDoNotDisturbMode failed, code is ${err.code}, message is ${err.message}`); } else { - console.info("supportDoNotDisturbMode success"); + console.info("isSupportDoNotDisturbMode success"); } } -notificationManager.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); +notificationManager.isSupportDoNotDisturbMode(isSupportDoNotDisturbModeCallback); ``` -## notificationManager.supportDoNotDisturbMode +## notificationManager.isSupportDoNotDisturbMode -supportDoNotDisturbMode(): Promise\ +isSupportDoNotDisturbMode(): Promise\ Checks whether DND mode is supported. This API uses a promise to return the result. @@ -2361,6 +2546,8 @@ Checks whether DND mode is supported. This API uses a promise to return the resu **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2370,7 +2557,7 @@ Checks whether DND mode is supported. This API uses a promise to return the resu **Example** ```ts -notificationManager.supportDoNotDisturbMode().then((data) => { +notificationManager.isSupportDoNotDisturbMode().then((data) => { console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); }); ``` @@ -2392,6 +2579,8 @@ Checks whether a specified template is supported. This API uses an asynchronous **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2405,7 +2594,7 @@ Checks whether a specified template is supported. This API uses an asynchronous let templateName = 'process'; function isSupportTemplateCallback(err, data) { if (err) { - console.info("isSupportTemplate failed " + JSON.stringify(err)); + console.error(`isSupportTemplate failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isSupportTemplate success"); } @@ -2436,6 +2625,8 @@ Checks whether a specified template is supported. This API uses a promise to ret **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2469,6 +2660,8 @@ Requests notification to be enabled for this application. This API uses an async **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2480,7 +2673,7 @@ Requests notification to be enabled for this application. This API uses an async ```javascript function requestEnableNotificationCallback(err) { if (err) { - console.info("requestEnableNotification failed " + JSON.stringify(err)); + console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); } else { console.info("requestEnableNotification success"); } @@ -2499,6 +2692,8 @@ Requests notification to be enabled for this application. This API uses a promis **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2536,6 +2731,8 @@ Sets whether this device supports distributed notifications. This API uses an as **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2548,7 +2745,7 @@ Sets whether this device supports distributed notifications. This API uses an as ```javascript function setDistributedEnableCallback() { if (err) { - console.info("setDistributedEnable failed " + JSON.stringify(err)); + console.error(`setDistributedEnable failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setDistributedEnable success"); } @@ -2579,6 +2776,8 @@ Sets whether this device supports distributed notifications. This API uses a pro **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2613,6 +2812,8 @@ Checks whether this device supports distributed notifications. This API uses an **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2625,7 +2826,7 @@ Checks whether this device supports distributed notifications. This API uses an ```javascript function isDistributedEnabledCallback(err, data) { if (err) { - console.info("isDistributedEnabled failed " + JSON.stringify(err)); + console.error(`isDistributedEnabled failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isDistributedEnabled success " + JSON.stringify(data)); } @@ -2652,6 +2853,8 @@ Checks whether this device supports distributed notifications. This API uses a p **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2691,6 +2894,8 @@ Sets whether a specified application supports distributed notifications. This AP **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -2704,7 +2909,7 @@ Sets whether a specified application supports distributed notifications. This AP ```javascript function setDistributedEnableByBundleCallback(err) { if (err) { - console.info("enableDistributedByBundle failed " + JSON.stringify(err)); + console.error(`setDistributedEnableByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("enableDistributedByBundle success"); } @@ -2742,6 +2947,8 @@ Sets whether a specified application supports distributed notifications. This AP **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -2785,6 +2992,8 @@ Checks whether a specified application supports distributed notifications. This **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -2798,7 +3007,7 @@ Checks whether a specified application supports distributed notifications. This ```javascript function isDistributedEnabledByBundleCallback(data) { if (err) { - console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); + console.error(`isDistributedEnabledByBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isDistributedEnabledByBundle success" + JSON.stringify(data)); } @@ -2837,6 +3046,8 @@ Checks whether a specified application supports distributed notifications. This **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -2878,6 +3089,8 @@ Obtains the notification reminder type. This API uses an asynchronous callback t **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2889,7 +3102,7 @@ Obtains the notification reminder type. This API uses an asynchronous callback t ```javascript function getDeviceRemindTypeCallback(err, data) { if (err) { - console.info("getDeviceRemindType failed " + JSON.stringify(err)); + console.error(`getDeviceRemindType failed, code is ${err.code}, message is ${err.message}`); } else { console.info("getDeviceRemindType success"); } @@ -2918,6 +3131,8 @@ Obtains the notification reminder type. This API uses a promise to return the re **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -2956,6 +3171,8 @@ Publishes a notification through the reminder agent. This API uses an asynchrono **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------------- | | 1600001 | Internal error. | @@ -2972,7 +3189,7 @@ Publishes a notification through the reminder agent. This API uses an asynchrono // publishAsBundle callback function callback(err) { if (err) { - console.info("publishAsBundle failed " + JSON.stringify(err)); + console.error(`publishAsBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publishAsBundle success"); } @@ -3020,6 +3237,8 @@ Publishes a notification through the reminder agent. This API uses a promise to **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------------- | | 1600001 | Internal error. | @@ -3080,6 +3299,8 @@ Cancels a notification published by the reminder agent. This API uses an asynchr **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -3094,7 +3315,7 @@ Cancels a notification published by the reminder agent. This API uses an asynchr // cancelAsBundle function cancelAsBundleCallback(err) { if (err) { - console.info("cancelAsBundle failed " + JSON.stringify(err)); + console.error(`cancelAsBundle failed, code is ${err.code}, message is ${err.message}`); } else { console.info("cancelAsBundle success"); } @@ -3131,6 +3352,8 @@ Cancels a notification published by the reminder agent. This API uses a promise **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -3175,6 +3398,8 @@ Sets whether to enable a specified notification slot type for a specified applic **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -3188,7 +3413,7 @@ Sets whether to enable a specified notification slot type for a specified applic // setNotificationEnableSlot function setNotificationEnableSlotCallback(err) { if (err) { - console.info("setNotificationEnableSlot failed " + JSON.stringify(err)); + console.error(`setNotificationEnableSlot failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setNotificationEnableSlot success"); } @@ -3223,6 +3448,8 @@ Sets whether to enable a specified notification slot type for a specified applic **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -3264,6 +3491,8 @@ Checks whether a specified notification slot type is enabled for a specified app **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -3277,7 +3506,7 @@ Checks whether a specified notification slot type is enabled for a specified app // isNotificationSlotEnabled function getEnableSlotCallback(err, data) { if (err) { - console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); + console.error(`isNotificationSlotEnabled failed, code is ${err.code}, message is ${err.message}`); } else { console.info("isNotificationSlotEnabled success"); } @@ -3316,6 +3545,8 @@ Checks whether a specified notification slot type is enabled for a specified app **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -3356,6 +3587,8 @@ Sets whether to enable the notification sync feature for devices where the appli **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -3371,7 +3604,7 @@ let enable = true; function callback(err) { if (err) { - console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); + console.error(`setSyncNotificationEnabledWithoutApp failed, code is ${err.code}, message is ${err.message}`); } else { console.info("setSyncNotificationEnabledWithoutApp success"); } @@ -3408,6 +3641,8 @@ Sets whether to enable the notification sync feature for devices where the appli **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -3424,7 +3659,7 @@ let enable = true; notificationManager.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { console.info('setSyncNotificationEnabledWithoutApp success'); }).catch((err) => { - console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); + console.error(`setSyncNotificationEnabledWithoutApp failed, code is ${err.code}, message is ${err.message}`); }); ``` @@ -3450,6 +3685,8 @@ Obtains whether the notification sync feature is enabled for devices where the a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -3500,6 +3737,8 @@ Obtains whether the notification sync feature is enabled for devices where the a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -3737,7 +3976,7 @@ Describes the notification request. | label | string | Yes | Yes | Notification label. | | badgeIconStyle | number | Yes | Yes | Notification badge type. | | showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | -| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to two buttons are allowed. | +| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to three buttons are allowed. | | smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| | largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| | creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index 2fc2390a979d6c1a2de7555313a496223dacc4ab..0cefd840d31e7471f1976042d8ba3f322de74882 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -36,6 +36,8 @@ Subscribes to a notification with the subscription information specified. This A **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -48,7 +50,7 @@ Subscribes to a notification with the subscription information specified. This A // subscribe callback function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribe success"); } @@ -86,6 +88,8 @@ Subscribes to notifications of all applications under this user. This API uses a **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -97,7 +101,7 @@ Subscribes to notifications of all applications under this user. This API uses a ```js function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribe success"); } @@ -134,6 +138,8 @@ Subscribes to a notification with the subscription information specified. This A **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -177,6 +183,8 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -188,7 +196,7 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu ```js function unsubscribeCallback(err) { if (err) { - console.info("unsubscribe failed " + JSON.stringify(err)); + console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("unsubscribe success"); } @@ -222,6 +230,8 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -265,6 +275,8 @@ Removes a notification for a specified application. This API uses an asynchronou **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -278,7 +290,7 @@ Removes a notification for a specified application. This API uses an asynchronou ```js function removeCallback(err) { if (err) { - console.info("remove failed " + JSON.stringify(err)); + console.error(`remove failed, code is ${err.code}, message is ${err.message}`); } else { console.info("remove success"); } @@ -318,6 +330,8 @@ Removes a notification for a specified application. This API uses a promise to r **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -364,6 +378,8 @@ Removes a specified notification. This API uses an asynchronous callback to retu **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -378,7 +394,7 @@ let hashCode = 'hashCode'; function removeCallback(err) { if (err) { - console.info("remove failed " + JSON.stringify(err)); + console.error(`remove failed, code is ${err.code}, message is ${err.message}`); } else { console.info("remove success"); } @@ -408,6 +424,8 @@ Removes a specified notification. This API uses a promise to return the result. **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -446,6 +464,8 @@ Removes all notifications for a specified application. This API uses an asynchro **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -458,7 +478,7 @@ Removes all notifications for a specified application. This API uses an asynchro ```js function removeAllCallback(err) { if (err) { - console.info("removeAll failed " + JSON.stringify(err)); + console.error(`removeAll failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeAll success"); } @@ -489,6 +509,8 @@ Removes all notifications. This API uses an asynchronous callback to return the **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -500,7 +522,7 @@ Removes all notifications. This API uses an asynchronous callback to return the ```js function removeAllCallback(err) { if (err) { - console.info("removeAll failed " + JSON.stringify(err)); + console.error(`removeAll failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeAll success"); } @@ -529,6 +551,8 @@ Removes all notifications for a specified application. This API uses a promise t **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ---------------------------------------- | | 1600001 | Internal error. | @@ -566,6 +590,8 @@ Removes all notifications for a specified user. This API uses an asynchronous ca **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -578,7 +604,7 @@ Removes all notifications for a specified user. This API uses an asynchronous ca ```js function removeAllCallback(err) { if (err) { - console.info("removeAll failed " + JSON.stringify(err)); + console.error(`removeAll failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeAll success"); } @@ -609,6 +635,8 @@ Removes all notifications for a specified user. This API uses a promise to retur **Error codes** +For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md). + | ID| Error Message | | -------- | ----------------------------------- | | 1600001 | Internal error. | @@ -621,7 +649,7 @@ Removes all notifications for a specified user. This API uses a promise to retur ```js function removeAllCallback(err) { if (err) { - console.info("removeAll failed " + JSON.stringify(err)); + console.error(`removeAll failed, code is ${err.code}, message is ${err.message}`); } else { console.info("removeAll success"); } @@ -659,7 +687,7 @@ Callback for receiving notifications. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -699,7 +727,7 @@ Callback for canceling notifications. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -739,7 +767,7 @@ Callback for notification sorting updates. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -771,7 +799,7 @@ Callback for subscription. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -803,14 +831,14 @@ Callback for unsubscription. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } }; function unsubscribeCallback(err) { if (err.code) { - console.info("unsubscribe failed " + JSON.stringify(err)); + console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("unsubscribeCallback"); } @@ -849,7 +877,7 @@ Callback for service disconnection. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -887,7 +915,7 @@ Callback for DND time setting updates. ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -926,7 +954,7 @@ Listens for the notification enabled status changes. This API uses an asynchrono ```javascript function subscribeCallback(err) { if (err) { - console.info("subscribe failed " + JSON.stringify(err)); + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); } else { console.info("subscribeCallback"); } @@ -945,6 +973,46 @@ let subscriber = { notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` +### onBadgeChanged10+ + + onBadgeChanged?:(data: [BadgeNumberCallbackData](#badgenumbercallbackdata)) => void + +Listens for the change of the notification badge number. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\<[BadgeNumberCallbackData](#badgenumbercallbackdata)\> | Yes | Callback used to return the result.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); + } else { + console.info("subscribeCallback"); + } +}; + +function onBadgeChangedCallback(data) { + console.info("bundle: ", data.bundle); + console.info("uid: ", data.uid); + console.info("badgeNumber: ", data.badgeNumber); +}; + +let subscriber = { + onBadgeChanged: onBadgeChangedCallback +}; + +notificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + ## BundleOption **System capability**: SystemCapability.Notification.Notification @@ -1054,3 +1122,15 @@ Provides the notification user input. | -------------------- | --- | -------------------- | | CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | | CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | + +## BadgeNumberCallbackData10+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | ------------ | +| bundle | string | Yes | No | Bundle name of the application.| +| uid | number | Yes | No | UID of the application. | +| badgeNumber | number | Yes | No | Notification badge number. | diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index 03e049e9a1bb1076f770bd2d89dc25455c453ee6..9901095cb2a38d06918843556da85f7b7a327da3 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -14,7 +14,7 @@ The **PermissionRequestResult** module defines the result of a permission reques | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite.| +| authResults | Array<number> | Yes| No|Resule of the permission Request.
**-1**: The permission has been set and no dialog box will be displayed. Users can modify the permission in **Settings**.
**0**: No operation is required.
**1**: Dynamic user authorization is required via a dialog window .
**2**: The request is invalid. Possible causes are as follows:
- The permission is not declared in the configuration file.
- The permission name is invalid.
- Special conditions for applying for the permission do not satisfied. See [ohos.permission.LOCATION](../../security/permission-list.md#ohospermissionlocation) and [ohos.permission.APPROXIMATELY_LOCATION](../../security/permission-list.md#ohospermissionapproximately_location).| ## Usage @@ -36,5 +36,3 @@ try { console.log(`catch err->${JSON.stringify(err)}`); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index 1e243a9881594c4acf692110cfe2a2e7a363b945..ce6daa95dc50c55f328eec71d8911f5024a2e6b7 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -35,8 +35,12 @@ isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. A third-party application can only check the idle status of itself. +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -53,8 +57,8 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | **Example** ```js @@ -77,8 +81,12 @@ isIdleState(bundleName: string): Promise<boolean> Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. A third-party application can only check the idle status of itself. +**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO + **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -100,8 +108,8 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | **Example** @@ -140,10 +148,10 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000004 | IPC failed. | +| 10000005 | Application is not installed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **Example** @@ -182,10 +190,10 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000004 | IPC failed. | +| 10000005 | Application is not installed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **Example** @@ -232,9 +240,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -292,9 +300,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -346,9 +354,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -405,9 +413,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -456,9 +464,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -514,9 +522,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -561,9 +569,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -615,9 +623,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -664,9 +672,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -714,9 +722,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -771,9 +779,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -821,9 +829,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -878,10 +886,10 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | +| 10000004 | IPC failed. | | 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **Example** @@ -927,10 +935,10 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | +| 10000004 | IPC failed. | | 10000005 | Application is not installed. | -| 10000006 | Get application info failed. | -| 10100002 | Get Application group info failed. | +| 10000006 | Failed to get the application information. | +| 10100002 | Failed to get the application group information. | **Example** @@ -977,9 +985,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10100001 | Repeated operation on the application group. | **Return value** @@ -1033,9 +1041,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10100001 | Repeated operation on the application group. | **Example** @@ -1083,8 +1091,8 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **Return value** @@ -1142,13 +1150,14 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **Example** ```javascript + // @ts-nocheck let onBundleGroupChanged = (err, res) =>{ console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appOldGroup is : ' + res.appOldGroup); @@ -1197,8 +1206,8 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **Example** @@ -1241,8 +1250,8 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10100001 | Application group operation repeated. | +| 10000004 | IPC failed. | +| 10100001 | Repeated operation on the application group. | **Example** @@ -1294,9 +1303,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -1342,9 +1351,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -1397,9 +1406,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** @@ -1445,9 +1454,9 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000001 | Memory operation failed. | | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | -| 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed. | -| 10000007 | Get system or actual time failed. | +| 10000004 | IPC failed. | +| 10000006 | Failed to get the application information. | +| 10000007 | Failed to get the system time. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 1234e81445de56ead44aaf2f118c53f0e12e7dbc..b5cbbd52e0c0bc4cc2f9cd364b679bc02f989f85 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -100,13 +100,13 @@ router.pushUrl({ data3: [123, 456, 789] } } -}) - .then(() => { - // success - }) - .catch(err => { +}, (err) => { + if (err) { console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); - }) + return; + } + console.info('pushUrl success'); +}) ``` ## router.pushUrl9+ @@ -473,9 +473,9 @@ Describes the page routing state. | name | string | No | Name of the current page, that is, the file name. | | path | string | Yes | Path of the current page. | -## router.enableBackPageAlert9+ +## router.showAlertBeforeBackPage9+ -enableBackPageAlert(options: EnableAlertOptions): void +showAlertBeforeBackPage(options: EnableAlertOptions): void Enables the display of a confirm dialog box before returning to the previous page. @@ -499,11 +499,11 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ```js try { - router.enableBackPageAlert({ + router.showAlertBeforeBackPage({ message: 'Message Info' }); } catch(error) { - console.error(`enableBackPageAlert failed, code is ${error.code}, message is ${error.message}`); + console.error(`showAlertBeforeBackPage failed, code is ${error.code}, message is ${error.message}`); } ``` ## EnableAlertOptions @@ -516,9 +516,9 @@ Describes the confirm dialog box. | ------- | ------ | ---- | -------- | | message | string | Yes | Content displayed in the confirm dialog box.| -## router.disableAlertBeforeBackPage +## router.hideAlertBeforeBackPage9+ -disableAlertBeforeBackPage(): void +hideAlertBeforeBackPage(): void Disables the display of a confirm dialog box before returning to the previous page. @@ -527,7 +527,7 @@ Disables the display of a confirm dialog box before returning to the previous pa **Example** ```js -router.disableAlertBeforeBackPage(); +router.hideAlertBeforeBackPage(); ``` ## router.getParams @@ -574,7 +574,7 @@ Enumerates the routing modes. | Name | Description | | -------- | ------------------------------------------------------------ | -| Standard | Standard mode.
The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.| +| Standard | Standard mode.
The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.
**NOTE**
If the routing mode is not used, the page is redirected to in standard mode.| | Single | Singleton mode.
If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.
If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.| ## Examples @@ -749,7 +749,7 @@ enableAlertBeforeBackPage(options: EnableAlertOptions): void Enables the display of a confirm dialog box before returning to the previous page. -This API is deprecated since API version 9. You are advised to use [enableBackPageAlert9+](#routerenablebackpagealert9) instead. +This API is deprecated since API version 9. You are advised to use [showAlertBeforeBackPage9+](#routershowalertbeforebackpage9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -766,3 +766,19 @@ This API is deprecated since API version 9. You are advised to use [enableBackPa message: 'Message Info' }); ``` + +## router.disableAlertBeforeBackPage(deprecated) + +disableAlertBeforeBackPage(): void + +Disables the display of a confirm dialog box before returning to the previous page. + +This API is deprecated since API version 9. You are advised to use [hideAlertBeforeBackPage9+](#routerhidealertbeforebackpage9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + +```js +router.disableAlertBeforeBackPage(); +``` diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index af2635b955827a772846784a127a6819ff037a37..c806d10c6963add3231f68a1a790d68c31d4b3a5 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -20,27 +20,29 @@ The APIs of this module return exceptions since API version 9. The following tab **System capability**: SystemCapability.Communication.IPC.Core - | Name | Value | Description | - | ------------------------------------- | ------- | --------------------------------------------- | - | CHECK_PARAM_ERROR | 401 | Parameter check failed. | - | OS_MMAP_ERROR | 1900001 | Failed to call mmap. | - | OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.| - | WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | - | READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | - | ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | - | ONLY_REMOTE_OBJECT_PERMITTED_ERROR | 1900006 | This operation is allowed only on the remote object. | - | COMMUNICATION_ERROR | 1900007 | Failed to communicate with the remote object over IPC. | - | PROXY_OR_REMOTE_OBJECT_INVALID_ERROR | 1900008 | Invalid proxy or remote object. | - | WRITE_DATA_TO_MESSAGE_SEQUENCE_ERROR | 1900009 | Failed to write data to MessageSequence. | - | READ_DATA_FROM_MESSAGE_SEQUENCE_ERROR | 1900010 | Failed to read data from MessageSequence. | - | PARCEL_MEMORY_ALLOC_ERROR | 1900011 | Failed to allocate memory during serialization. | - | CALL_JS_METHOD_ERROR | 1900012 | Failed to invoke the JS callback. | - | OS_DUP_ERROR | 1900013 | Failed to call dup. | +| Name | Value | Description | +| ------------------------------------- | ------- | --------------------------------------------- | +| CHECK_PARAM_ERROR | 401 | Parameter check failed. | +| OS_MMAP_ERROR | 1900001 | Failed to call mmap. | +| OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.| +| WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | +| READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | +| ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | +| ONLY_REMOTE_OBJECT_PERMITTED_ERROR | 1900006 | This operation is allowed only on the remote object. | +| COMMUNICATION_ERROR | 1900007 | Failed to communicate with the remote object over IPC. | +| PROXY_OR_REMOTE_OBJECT_INVALID_ERROR | 1900008 | Invalid proxy or remote object. | +| WRITE_DATA_TO_MESSAGE_SEQUENCE_ERROR | 1900009 | Failed to write data to MessageSequence. | +| READ_DATA_FROM_MESSAGE_SEQUENCE_ERROR | 1900010 | Failed to read data from MessageSequence. | +| PARCEL_MEMORY_ALLOC_ERROR | 1900011 | Failed to allocate memory during serialization. | +| CALL_JS_METHOD_ERROR | 1900012 | Failed to invoke the JS callback. | +| OS_DUP_ERROR | 1900013 | Failed to call dup. | ## MessageSequence9+ - Provides APIs for reading and writing data in specific format. During RPC or IPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. +Provides APIs for reading and writing data in specific format. + +During RPC or IPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. ### create @@ -52,9 +54,9 @@ The APIs of this module return exceptions since API version 9. The following tab **Return value** - | Type | Description | - | --------------- | ------------------------------- | - | MessageSequence | **MessageSequence** object created.| +| Type | Description | +| --------------- | ------------------------------- | +| MessageSequence | **MessageSequence** object created.| **Example** @@ -88,18 +90,18 @@ Serializes a remote object and writes it to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | ----------------------------------------- | - | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageSequence** object.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | ----------------------------------------- | +| object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageSequence** object.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900008 | proxy or remote object is invalid | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| -------- | ------- | +| 1900008 | proxy or remote object is invalid | +| 1900009 | write data to message sequence failed | **Example** @@ -129,18 +131,18 @@ Reads the remote object from **MessageSequence**. You can use this API to deseri **Return value** - | Type | Description | - | ------------------------------- | ------------------ | - | [IRemoteObject](#iremoteobject) | Remote object obtained.| +| Type | Description | +| ------------------------------- | ------------------ | +| [IRemoteObject](#iremoteobject) | Remote object obtained.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | +| 1900010 | read data from message sequence failed | **Example** @@ -171,17 +173,17 @@ Writes an interface token to this **MessageSequence** object. The remote object **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | token | string | Yes | Interface token to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| token | string | Yes | Interface token to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -205,17 +207,17 @@ Reads the interface token from this **MessageSequence** object. The interface to **Return value** - | Type | Description | - | ------ | ------------------------ | - | string | Interface token obtained.| +| Type | Description | +| ------ | ------------------------ | +| string | Interface token obtained.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ----- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | ----- | +| 1900010 | read data from message sequence failed | **Example** @@ -244,9 +246,9 @@ Obtains the data size of this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | ----------------------------------------------- | - | number | Size of the **MessageSequence** object obtained, in bytes.| +| Type | Description | +| ------ | ----------------------------------------------- | +| number | Size of the **MessageSequence** object obtained, in bytes.| **Example** @@ -266,9 +268,9 @@ Obtains the capacity of this **MessageSequence** object. **Return value** - | Type | Description| - | ------ | ----- | - | number | **MessageSequence** capacity obtained, in bytes.| +| Type | Description| +| ------ | ----- | +| number | **MessageSequence** capacity obtained, in bytes.| **Example** @@ -288,9 +290,9 @@ Sets the size of the data contained in this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description| - | ------ | ------ | ---- | ------ | - | size | number | Yes | Data size to set, in bytes.| +| Name| Type | Mandatory| Description| +| ------ | ------ | ---- | ------ | +| size | number | Yes | Data size to set, in bytes.| **Example** @@ -315,17 +317,17 @@ Sets the storage capacity of this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | --------------------------------------------- | - | size | number | Yes | Storage capacity of the **MessageSequence** object to set, in bytes.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------------------------------- | +| size | number | Yes | Storage capacity of the **MessageSequence** object to set, in bytes.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------ | - | 1900011 | parcel memory alloc failed | +| ID| Error Message| +| -------- | ------ | +| 1900011 | parcel memory alloc failed | **Example** @@ -350,9 +352,9 @@ Obtains the writable capacity (in bytes) of this **MessageSequence** object. **Return value** - | Type| Description| - | ------ | ------ | - | number | Writable capacity of the **MessageSequence** instance, in bytes.| +| Type| Description| +| ------ | ------ | +| number | Writable capacity of the **MessageSequence** instance, in bytes.| **Example** @@ -376,9 +378,9 @@ Obtains the readable capacity of this **MessageSequence** object. **Return value** - | Type| Description| - | ------ | ------- | - | number | Readable capacity of the **MessageSequence** instance, in bytes.| +| Type| Description| +| ------ | ------- | +| number | Readable capacity of the **MessageSequence** instance, in bytes.| **Example** @@ -402,9 +404,9 @@ Obtains the read position of this **MessageSequence** object. **Return value** - | Type| Description| - | ------ | ------ | - | number | Read position obtained.| +| Type| Description| +| ------ | ------ | +| number | Read position obtained.| **Example** @@ -424,9 +426,9 @@ Obtains the write position of this **MessageSequence** object. **Return value** - | Type| Description| - | ------ | ----- | - | number | Write position obtained.| +| Type| Description| +| ------ | ----- | +| number | Write position obtained.| **Example** @@ -447,9 +449,9 @@ Moves the read pointer to the specified position. **Parameters** - | Name| Type| Mandatory| Description| - | ------ | ------ | ---- | ------- | - | pos | number | Yes | Position from which data is to read.| +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ------- | +| pos | number | Yes | Position from which data is to read.| **Example** @@ -479,9 +481,9 @@ Moves the write pointer to the specified position. **Parameters** - | Name| Type| Mandatory| Description| - | ------ | ------ | ---- | ----- | - | pos | number | Yes | Position from which data is to write.| +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ----- | +| pos | number | Yes | Position from which data is to write.| **Example** @@ -509,17 +511,17 @@ Writes a byte value to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description| - | ----- | ------ | ---- | ----- | - | val | number | Yes| Byte value to write.| +| Name| Type | Mandatory| Description| +| ----- | ------ | ---- | ----- | +| val | number | Yes| Byte value to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| -------- | ------- | +| 1900009 | write data to message sequence failed | **Example** @@ -543,17 +545,17 @@ Reads the byte value from this **MessageSequence** object. **Return value** - | Type | Description| - | ------ | ----- | - | number | Byte value read.| +| Type | Description| +| ------ | ----- | +| number | Byte value read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -584,17 +586,17 @@ Writes a short integer to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description| - | ------ | ------ | --- | --- | - | val | number | Yes| Short integer to write.| +| Name| Type | Mandatory| Description| +| ------ | ------ | --- | --- | +| val | number | Yes| Short integer to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------ | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ------ | +| 1900009 | write data to message sequence failed | **Example** @@ -618,17 +620,17 @@ Reads the short integer from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | -------------- | - | number | Short integer read.| +| Type | Description | +| ------ | -------------- | +| number | Short integer read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -641,12 +643,12 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode console.info("rpc write short fail, errorMessage" + error.message); } try { - let ret = data.readShort(8); + let ret = data.readShort(); + console.log("RpcClient: readByte is: " + ret); } catch(error) { console.info("rpc read short fail, errorCode " + error.code); console.info("rpc read short fail, errorMessage" + error.message); } - console.log("RpcClient: readByte is: " + ret); ``` ### writeInt @@ -659,17 +661,17 @@ Writes an integer to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------- | - | val | number | Yes | Integer to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| val | number | Yes | Integer to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| -------- | ------- | +| 1900009 | write data to message sequence failed | **Example** @@ -693,17 +695,17 @@ Reads the integer from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | ------------ | - | number | Integer read.| +| Type | Description | +| ------ | ------------ | +| number | Integer read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | ------- | +| 1900010 | read data from message sequence failed | **Example** @@ -734,17 +736,17 @@ Writes a long integer to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------- | - | val | number | Yes | Long integer to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| val | number | Yes | Long integer to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ------- | +| 1900009 | write data to message sequence failed | **Example** @@ -768,17 +770,17 @@ Reads the long integer from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | -------------- | - | number | Long integer read.| +| Type | Description | +| ------ | -------------- | +| number | Long integer read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -809,17 +811,17 @@ Writes a floating-point number to this **MessageSequence** object. **Parameters** - | Name| Type| Mandatory| Description| - | ----- | ---- | ---- | ----- | - | val | number | Yes| Floating-point number to write.| +| Name| Type| Mandatory| Description| +| ----- | ---- | ---- | ----- | +| val | number | Yes| Floating-point number to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ------- | +| 1900009 | write data to message sequence failed | **Example** @@ -843,17 +845,17 @@ Reads the floating-pointer number from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | ------------ | - | number | Floating-point number read.| +| Type | Description | +| ------ | ------------ | +| number | Floating-point number read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -884,17 +886,17 @@ Writes a double-precision floating-point number to this **MessageSequence** obje **Parameters** - | Name| Type| Mandatory| Description| - | ------ | ------ | ---- | ------ | - | val number | Yes| Double-precision floating-point number to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| val | number | Yes | Double-precision floating-point number to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -918,17 +920,17 @@ Reads the double-precision floating-point number from this **MessageSequence** o **Return value** - | Type | Description | - | ------ | ------------------ | - | number | Double-precision floating-point number read.| +| Type | Description | +| ------ | ------------------ | +| number | Double-precision floating-point number read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -959,17 +961,17 @@ Writes a Boolean value to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------- | ---- | ---------------- | - | val | boolean | Yes | Boolean value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ---------------- | +| val | boolean | Yes | Boolean value to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ------- | +| 1900009 | write data to message sequence failed | **Example** @@ -993,17 +995,17 @@ Reads the Boolean value from this **MessageSequence** object. **Return value** - | Type | Description | - | ------- | -------------------- | - | boolean | Boolean value read.| +| Type | Description | +| ------- | -------------------- | +| boolean | Boolean value read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| -------- | ------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1034,17 +1036,17 @@ Writes a character to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------- | - | val | number | Yes | Single character to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| val | number | Yes | Single character to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1068,17 +1070,17 @@ Reads the character from this **MessageSequence** object. **Return value** - | Type | Description| - | ------ | ---- | - | number | Character read.| +| Type | Description| +| ------ | ---- | +| number | Character read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------ | --------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------ | --------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1109,17 +1111,17 @@ Writes a string to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ----------------------------------------- | - | val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------- | +| val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1143,17 +1145,17 @@ Reads the string from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | -------------- | - | string | String read.| +| Type | Description | +| ------ | -------------- | +| string | String read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1184,17 +1186,17 @@ Writes a **Parcelable** object to this **MessageSequence** object. **Parameters** - | Name| Type| Mandatory| Description| - | ------ | --------- | ---- | ------ | - | val | Parcelable | Yes | **Parcelable** object to write.| +| Name| Type| Mandatory| Description| +| ------ | --------- | ---- | ------ | +| val | Parcelable | Yes | **Parcelable** object to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1237,18 +1239,18 @@ Reads a **Parcelable** object from this **MessageSequence** object to the specif **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------- | ---- | ----------------------------------------- | - | dataIn | Parcelable | Yes | **Parcelable** object to read.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ----------------------------------------- | +| dataIn | Parcelable | Yes | **Parcelable** object to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900010 | read data from message sequence failed | - | 1900012 | call js callback function failed | +| ID| Error Message| +| -------- | ------- | +| 1900010 | read data from message sequence failed | +| 1900012 | call js callback function failed | **Example** @@ -1293,17 +1295,17 @@ Writes a byte array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | -------- | ---- | ------------------ | - | byteArray | number[] | Yes | Byte array to write.| +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | ------------------ | +| byteArray | number[] | Yes | Byte array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1328,17 +1330,17 @@ Reads a byte array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ------------------ | - | dataIn | number[] | Yes | Byte array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| dataIn | number[] | Yes | Byte array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1370,17 +1372,17 @@ Reads the byte array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | -------------- | - | number[] | Byte array read.| +| Type | Description | +| -------- | -------------- | +| number[] | Byte array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| -------- | ------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1412,17 +1414,17 @@ Writes a short array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | -------- | ---- | -------------------- | - | shortArray | number[] | Yes | Short array to write.| +| Name | Type | Mandatory| Description | +| ---------- | -------- | ---- | -------------------- | +| shortArray | number[] | Yes | Short array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ----- | ----- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ----- | ----- | +| 1900009 | write data to message sequence failed | **Example** @@ -1446,17 +1448,17 @@ Reads a short array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------- | - | dataIn | number[] | Yes | Short array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| dataIn | number[] | Yes | Short array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------ | ------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------ | ------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1487,17 +1489,17 @@ Reads the short array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | ---------------- | - | number[] | Short array read.| +| Type | Description | +| -------- | ---------------- | +| number[] | Short array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| -------- | ------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1528,17 +1530,17 @@ Writes an integer array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | -------- | ---- | ------------------ | - | intArray | number[] | Yes | Integer array to write.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------ | +| intArray | number[] | Yes | Integer array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ----- | --------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ----- | --------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1562,17 +1564,17 @@ Reads an integer array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ------------------ | - | dataIn | number[] | Yes | Integer array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| dataIn | number[] | Yes | Integer array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1603,17 +1605,17 @@ Reads the integer array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | -------------- | - | number[] | Integer array read.| +| Type | Description | +| -------- | -------------- | +| number[] | Integer array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ----- | ------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ----- | ------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1644,17 +1646,17 @@ Writes a long array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | -------- | ---- | -------------------- | - | longArray | number[] | Yes | Long array to write.| +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| longArray | number[] | Yes | Long array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ----- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ----- | +| 1900009 | write data to message sequence failed | **Example** @@ -1678,17 +1680,17 @@ Reads a long array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------- | - | dataIn | number[] | Yes | Long array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| dataIn | number[] | Yes | Long array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------ | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | ------ | +| 1900010 | read data from message sequence failed | **Example** @@ -1719,17 +1721,17 @@ Reads the long array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | ---------------- | - | number[] | Long array read.| +| Type | Description | +| -------- | ---------------- | +| number[] | Long array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1760,17 +1762,17 @@ Writes a floating-point array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | - | floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| +| Name | Type | Mandatory| Description | +| ---------- | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | +| floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1794,17 +1796,17 @@ Reads a floating-point array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | - | dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | +| dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1835,17 +1837,17 @@ Reads the floating-point array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | -------------- | - | number[] | Floating-point array read.| +| Type | Description | +| -------- | -------------- | +| number[] | Floating-point array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1876,17 +1878,17 @@ Writes a double-precision floating-point array to this **MessageSequence** objec **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | -------- | ---- | ------------------------ | - | doubleArray | number[] | Yes | Double-precision floating-point array to write.| +| Name | Type | Mandatory| Description | +| ----------- | -------- | ---- | ------------------------ | +| doubleArray | number[] | Yes | Double-precision floating-point array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -1910,17 +1912,17 @@ Reads a double-precision floating-point array from this **MessageSequence** obje **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ------------------------ | - | dataIn | number[] | Yes | Double-precision floating-point array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------------------ | +| dataIn | number[] | Yes | Double-precision floating-point array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1951,17 +1953,17 @@ Reads the double-precision floating-point array from this **MessageSequence** ob **Return value** - | Type | Description | - | -------- | -------------------- | - | number[] | Double-precision floating-point array read.| +| Type | Description | +| -------- | -------------------- | +| number[] | Double-precision floating-point array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -1992,17 +1994,17 @@ Writes a Boolean array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ------------ | --------- | ---- | ------------------ | - | booleanArray | boolean[] | Yes | Boolean array to write.| +| Name | Type | Mandatory| Description | +| ------------ | --------- | ---- | ------------------ | +| booleanArray | boolean[] | Yes | Boolean array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -2026,17 +2028,17 @@ Reads a Boolean array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | --------- | ---- | ------------------ | - | dataIn | boolean[] | Yes | Boolean array to read.| +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ------------------ | +| dataIn | boolean[] | Yes | Boolean array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2067,17 +2069,17 @@ Reads the Boolean array from this **MessageSequence** object. **Return value** - | Type | Description | - | --------- | -------------- | - | boolean[] | Boolean array read.| +| Type | Description | +| --------- | -------------- | +| boolean[] | Boolean array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2108,17 +2110,17 @@ Writes a character array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | -------- | ---- | ---------------------- | - | charArray | number[] | Yes | Character array to write.| +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | ---------------------- | +| charArray | number[] | Yes | Character array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------ | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| -------- | ------ | +| 1900009 | write data to message sequence failed | **Example** @@ -2142,17 +2144,17 @@ Reads a character array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ---------------------- | - | dataIn | number[] | Yes | Character array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| dataIn | number[] | Yes | Character array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2183,17 +2185,17 @@ Reads the character array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | ------------------ | - | number[] | Character array read.| +| Type | Description | +| -------- | ------------------ | +| number[] | Character array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2225,17 +2227,17 @@ Writes a string array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | -------- | ---- | ------------------------------------------------------- | - | stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| +| Name | Type | Mandatory| Description | +| ----------- | -------- | ---- | ------------------------------------------------------- | +| stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -2259,17 +2261,17 @@ Reads a string array from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------- | - | dataIn | string[] | Yes | String array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| dataIn | string[] | Yes | String array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2300,17 +2302,17 @@ Reads the string array from this **MessageSequence** object. **Return value** - | Type | Description | - | -------- | ---------------- | - | string[] | String array read.| +| Type | Description | +| -------- | ---------------- | +| string[] | String array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2343,9 +2345,9 @@ Writes information to this **MessageSequence** object indicating that no excepti For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -2385,12 +2387,14 @@ Reads the exception information from this **MessageSequence** object. For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -2411,6 +2415,11 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageSequence.create(); let reply = rpc.MessageSequence.create(); @@ -2450,17 +2459,17 @@ Writes a **Parcelable** array to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------------- | ------------ | ---- | -------------------------- | - | parcelableArray | Parcelable[] | Yes | **Parcelable** array to write.| +| Name | Type | Mandatory| Description | +| --------------- | ------------ | ---- | -------------------------- | +| parcelableArray | Parcelable[] | Yes | **Parcelable** array to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900009 | write data to message sequence failed | **Example** @@ -2506,18 +2515,18 @@ Reads a **Parcelable** array from this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------------- | ------------ | ---- | -------------------------- | - | parcelableArray | Parcelable[] | Yes | **Parcelable** array to read.| +| Name | Type | Mandatory| Description | +| --------------- | ------------ | ---- | -------------------------- | +| parcelableArray | Parcelable[] | Yes | **Parcelable** array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | - | 1900012 | call js callback function failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | +| 1900012 | call js callback function failed | **Example** @@ -2567,17 +2576,17 @@ Writes an array of **IRemoteObject** objects to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | --------------- | ---- | ---------------------------------------------- | - | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| +| Name | Type | Mandatory| Description | +| ----------- | --------------- | ---- | ---------------------------------------------- | +| objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ------- | +| 1900009 | write data to message sequence failed | **Example** @@ -2614,17 +2623,17 @@ Reads an array of **IRemoteObject** objects from this **MessageSequence** object **Parameters** - | Name | Type | Mandatory| Description | - | ------- | --------------- | ---- | ---------------------------------------------- | - | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| +| Name | Type | Mandatory| Description | +| ------- | --------------- | ---- | ---------------------------------------------- | +| objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2667,17 +2676,17 @@ Reads the **IRemoteObject** object array from this **MessageSequence** object. **Return value** - | Type | Description | - | --------------- | --------------------------- | - | IRemoteObject[] | **IRemoteObject** object array read.| +| Type | Description | +| --------------- | --------------------------- | +| IRemoteObject[] | **IRemoteObject** object array read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2715,9 +2724,9 @@ Closes a file descriptor. This API is a static method. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------- | - | fd | number | Yes | File descriptor to close.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| fd | number | Yes | File descriptor to close.| **Example** @@ -2743,23 +2752,23 @@ Duplicates a file descriptor. This API is a static method. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | fd | number | Yes | File descriptor to duplicate.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| fd | number | Yes | File descriptor to duplicate.| **Return value** - | Type | Description | - | ------ | -------------------- | - | number | New file descriptor.| +| Type | Description | +| ------ | -------------------- | +| number | New file descriptor.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900013 | call os dup function failed | +| ID| Error Message| +| ------- | ------- | +| 1900013 | call os dup function failed | **Example** @@ -2785,9 +2794,9 @@ Checks whether this **MessageSequence** object contains file descriptors. **Return value** - | Type | Description | - | ------- | -------------------------------------------------------------------- | - | boolean | Returns **true** if the **MessageSequence** object contains file descriptors; returns **false** otherwise.| +| Type | Description | +| ------- | -------------------------------------------------------------------- | +| boolean | Returns **true** if the **MessageSequence** object contains file descriptors; returns **false** otherwise.| **Example** @@ -2823,17 +2832,17 @@ Writes a file descriptor to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| fd | number | Yes | File descriptor to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------ | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| -------- | ------ | +| 1900009 | write data to message sequence failed | **Example** @@ -2860,17 +2869,17 @@ Reads the file descriptor from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | ---------------- | - | number | File descriptor read.| +| Type | Description | +| ------ | ---------------- | +| number | File descriptor read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -2903,17 +2912,17 @@ Writes an anonymous shared object to this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------------------- | - | ashmem | Ashmem | Yes | Anonymous shared object to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| ashmem | Ashmem | Yes | Anonymous shared object to write.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------- | - | 1900003 | write to ashmem failed | +| ID| Error Message| +| ------- | ------- | +| 1900003 | write to ashmem failed | **Example** @@ -2945,17 +2954,17 @@ Reads the anonymous shared object from this **MessageSequence** object. **Return value** - | Type | Description | - | ------ | ------------------ | - | Ashmem | Anonymous share object read.| +| Type | Description | +| ------ | ------------------ | +| Ashmem | Anonymous share object read.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900004 | read from ashmem failed | +| ID| Error Message| +| ------- | -------- | +| 1900004 | read from ashmem failed | **Example** @@ -2993,9 +3002,9 @@ Obtains the maximum amount of raw data that can be held by this **MessageSequenc **Return value** - | Type | Description | - | ------ | ------------------------------------------------------------ | - | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageSequence** object.| +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageSequence** object.| **Example** @@ -3015,18 +3024,18 @@ Writes raw data to this **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ------- | -------- | ---- | ---------------------------------- | - | rawData | number[] | Yes | Raw data to write. | - | size | number | Yes | Size of the raw data, in bytes.| +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ---------------------------------- | +| rawData | number[] | Yes | Raw data to write. | +| size | number | Yes | Size of the raw data, in bytes.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------ | - | 1900009 | write data to message sequence failed | +| ID| Error Message| +| ------- | ------ | +| 1900009 | write data to message sequence failed | **Example** @@ -3051,23 +3060,23 @@ Reads raw data from this **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | size | number | Yes | Size of the raw data to read.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| size | number | Yes | Size of the raw data to read.| **Return value** - | Type | Description | - | -------- | ------------------------------ | - | number[] | Raw data read, in bytes.| +| Type | Description | +| -------- | ------------------------------ | +| number[] | Raw data read, in bytes.| **Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900010 | read data from message sequence failed | +| ID| Error Message| +| ------- | -------- | +| 1900010 | read data from message sequence failed | **Example** @@ -3093,7 +3102,9 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode >This class is no longer maintained since API version 9. You are advised to use [MessageSequence](#messagesequence9). -Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageParcel** to write data in specific format to a **MessageParcel** object. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. +Provides APIs for reading and writing data in specific format. + +During RPC, the sender can use the **write()** method provided by **MessageParcel** to write data in specific format to a **MessageParcel** object. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. ### create @@ -3105,9 +3116,9 @@ Creates a **MessageParcel** object. This method is a static method. **Return value** - | Type | Description | - | ------------- | ----------------------------- | - | MessageParcel | **MessageParcel** object created.| +| Type | Description | +| ------------- | ----------------------------- | +| MessageParcel | **MessageParcel** object created.| **Example** @@ -3141,15 +3152,15 @@ Serializes a remote object and writes it to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | --------------------------------------- | - | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageParcel** object.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | --------------------------------------- | +| object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageParcel** object.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -3188,9 +3199,9 @@ Reads the remote object from this **MessageParcel** object. You can use this met **Return value** - | Type | Description | - | ------------------------------- | ------------------ | - | [IRemoteObject](#iremoteobject) | Remote object obtained.| +| Type | Description | +| ------------------------------- | ------------------ | +| [IRemoteObject](#iremoteobject) | Remote object obtained.| **Example** @@ -3230,15 +3241,15 @@ Writes an interface token to this **MessageParcel** object. The remote object ca **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | token | string | Yes | Interface token to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| token | string | Yes | Interface token to write.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -3259,9 +3270,9 @@ Reads the interface token from this **MessageParcel** object. The interface toke **Return value** - | Type | Description | - | ------ | ------------------------ | - | string | Interface token obtained.| +| Type | Description | +| ------ | ------------------------ | +| string | Interface token obtained.| **Example** @@ -3285,9 +3296,9 @@ Obtains the data size of this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | --------------------------------------------- | - | number | Size of the **MessageParcel** object obtained, in bytes.| +| Type | Description | +| ------ | --------------------------------------------- | +| number | Size of the **MessageParcel** object obtained, in bytes.| **Example** @@ -3307,9 +3318,9 @@ Obtains the capacity of this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | --------------------------------------------- | - | number | **MessageParcel** capacity obtained, in bytes.| +| Type | Description | +| ------ | --------------------------------------------- | +| number | **MessageParcel** capacity obtained, in bytes.| **Example** @@ -3329,15 +3340,15 @@ Sets the size of data contained in this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------------------------- | - | size | number | Yes | Data size to set, in bytes.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------- | +| size | number | Yes | Data size to set, in bytes.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -3357,15 +3368,15 @@ Sets the storage capacity of this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------------------------- | - | size | number | Yes | Storage capacity to set, in bytes.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------- | +| size | number | Yes | Storage capacity to set, in bytes.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -3385,9 +3396,9 @@ Obtains the writable capacity of this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | --------------------------------------------------- | - | number | **MessageParcel** writable capacity obtained, in bytes.| +| Type | Description | +| ------ | --------------------------------------------------- | +| number | **MessageParcel** writable capacity obtained, in bytes.| **Example** @@ -3411,9 +3422,9 @@ Obtains the readable capacity of this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | --------------------------------------------------- | - | number | **MessageParcel** object readable capacity, in bytes.| +| Type | Description | +| ------ | --------------------------------------------------- | +| number | **MessageParcel** object readable capacity, in bytes.| **Example** @@ -3437,9 +3448,9 @@ Obtains the read position of this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | --------------------------------------- | - | number | Current read position of the **MessageParcel** object.| +| Type | Description | +| ------ | --------------------------------------- | +| number | Current read position of the **MessageParcel** object.| **Example** @@ -3459,9 +3470,9 @@ Obtains the write position of this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | --------------------------------------- | - | number | Current write position of the **MessageParcel** object.| +| Type | Description | +| ------ | --------------------------------------- | +| number | Current write position of the **MessageParcel** object.| **Example** @@ -3482,15 +3493,15 @@ Moves the read pointer to the specified position. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | pos | number | Yes | Position from which data is to read.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| pos | number | Yes | Position from which data is to read.| **Return value** - | Type | Description | - | ------- | ------------------------------------------------- | - | boolean | Returns **true** if the read position changes; returns **false** otherwise.| +| Type | Description | +| ------- | ------------------------------------------------- | +| boolean | Returns **true** if the read position changes; returns **false** otherwise.| **Example** @@ -3515,15 +3526,15 @@ Moves the write pointer to the specified position. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | pos | number | Yes | Position from which data is to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| pos | number | Yes | Position from which data is to write.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the write position changes; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the write position changes; returns **false** otherwise.| **Example** @@ -3546,15 +3557,15 @@ Writes a Byte value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------- | - | val | number | Yes | Byte value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| val | number | Yes | Byte value to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -3574,9 +3585,9 @@ Reads the Byte value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ------------ | - | number | Byte value read.| +| Type | Description | +| ------ | ------------ | +| number | Byte value read.| **Example** @@ -3598,15 +3609,15 @@ Writes a Short int value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | val | number | Yes | Short int value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| val | number | Yes | Short int value to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3626,9 +3637,9 @@ Reads the Short int value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | -------------- | - | number | Short int value read.| +| Type | Description | +| ------ | -------------- | +| number | Short int value read.| **Example** @@ -3650,15 +3661,15 @@ Writes an Int value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------- | - | val | number | Yes | Int value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| val | number | Yes | Int value to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -3678,9 +3689,9 @@ Reads the Int value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ------------ | - | number | Int value read.| +| Type | Description | +| ------ | ------------ | +| number | Int value read.| **Example** @@ -3702,15 +3713,15 @@ Writes a Long int value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------- | - | val | number | Yes | Long int value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| val | number | Yes | Long int value to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3730,9 +3741,9 @@ Reads the Long int value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | -------------- | - | number | Long int value read.| +| Type | Description | +| ------ | -------------- | +| number | Long int value read.| **Example** @@ -3754,15 +3765,15 @@ Writes a Float value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------- | - | val | number | Yes | Float value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| val | number | Yes | Float value to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3782,9 +3793,9 @@ Reads the Float value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ------------ | - | number | Float value read.| +| Type | Description | +| ------ | ------------ | +| number | Float value read.| **Example** @@ -3806,15 +3817,15 @@ Writes a Double value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------- | - | val | number | Yes | Double value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| val | number | Yes | Double value to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3834,9 +3845,9 @@ Reads the Double value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ------------------ | - | number | Double value read.| +| Type | Description | +| ------ | ------------------ | +| number | Double value read.| **Example** @@ -3858,15 +3869,15 @@ Writes a Boolean value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------- | ---- | ---------------- | - | val | boolean | Yes | Boolean value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ---------------- | +| val | boolean | Yes | Boolean value to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3886,9 +3897,9 @@ Reads the Boolean value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------- | -------------------- | - | boolean | Boolean value read.| +| Type | Description | +| ------- | -------------------- | +| boolean | Boolean value read.| **Example** @@ -3910,15 +3921,15 @@ Writes a Char value to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------- | - | val | number | Yes | Char value to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| val | number | Yes | Char value to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3938,9 +3949,9 @@ Reads the Char value from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ---------------- | - | number | Char value read.| +| Type | Description | +| ------ | ---------------- | +| number | Char value read.| **Example** @@ -3962,15 +3973,15 @@ Writes a string to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ----------------------------------------- | - | val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------- | +| val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -3990,9 +4001,9 @@ Reads the string from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | -------------- | - | string | String read.| +| Type | Description | +| ------ | -------------- | +| string | String read.| **Example** @@ -4014,15 +4025,15 @@ Writes a sequenceable object to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ----------------------------- | ---- | -------------------- | - | val | [Sequenceable](#sequenceable) | Yes | Sequenceable object to write.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------- | +| val | [Sequenceable](#sequenceable) | Yes | Sequenceable object to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4061,15 +4072,15 @@ Reads member variables from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ----------------------------- | ---- | --------------------------------------- | - | dataIn | [Sequenceable](#sequenceabledeprecated) | Yes | Object that reads member variables from the **MessageParcel** object.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | --------------------------------------- | +| dataIn | [Sequenceable](#sequenceabledeprecated) | Yes | Object that reads member variables from the **MessageParcel** object.| **Return value** - | Type | Description | - | ------- | ------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4111,15 +4122,15 @@ Writes a byte array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | -------- | ---- | ------------------ | - | byteArray | number[] | Yes | Byte array to write.| +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | ------------------ | +| byteArray | number[] | Yes | Byte array to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4140,9 +4151,9 @@ Reads a byte array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ------------------ | - | dataIn | number[] | Yes | Byte array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| dataIn | number[] | Yes | Byte array to read.| **Example** @@ -4165,9 +4176,9 @@ Reads the byte array from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | -------------- | - | number[] | Byte array read.| +| Type | Description | +| -------- | -------------- | +| number[] | Byte array read.| **Example** @@ -4190,15 +4201,15 @@ Writes a short array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | -------- | ---- | -------------------- | - | shortArray | number[] | Yes | Short array to write.| +| Name | Type | Mandatory| Description | +| ---------- | -------- | ---- | -------------------- | +| shortArray | number[] | Yes | Short array to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4218,9 +4229,9 @@ Reads a short array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------- | - | dataIn | number[] | Yes | Short array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| dataIn | number[] | Yes | Short array to read.| **Example** @@ -4242,9 +4253,9 @@ Reads the short array from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | ---------------- | - | number[] | Short array read.| +| Type | Description | +| -------- | ---------------- | +| number[] | Short array read.| **Example** @@ -4266,15 +4277,15 @@ Writes an integer array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | -------- | ---- | ------------------ | - | intArray | number[] | Yes | Integer array to write.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------ | +| intArray | number[] | Yes | Integer array to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4294,9 +4305,9 @@ Reads an integer array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ------------------ | - | dataIn | number[] | Yes | Integer array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| dataIn | number[] | Yes | Integer array to read.| **Example** @@ -4318,9 +4329,9 @@ Reads the integer array from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | -------------- | - | number[] | Integer array read.| +| Type | Description | +| -------- | -------------- | +| number[] | Integer array read.| **Example** @@ -4342,15 +4353,15 @@ Writes a long array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | -------- | ---- | -------------------- | - | longArray | number[] | Yes | Long array to write.| +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| longArray | number[] | Yes | Long array to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4370,9 +4381,9 @@ Reads a long array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------- | - | dataIn | number[] | Yes | Long array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| dataIn | number[] | Yes | Long array to read.| **Example** @@ -4394,9 +4405,9 @@ Reads the long array from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | ---------------- | - | number[] | Long array read.| +| Type | Description | +| -------- | ---------------- | +| number[] | Long array read.| **Example** @@ -4418,15 +4429,15 @@ Writes a FloatArray to this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | ---------- | -------- | ---- | --- | - | floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| +| Name| Type| Mandatory| Description| +| ---------- | -------- | ---- | --- | +| floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4446,9 +4457,9 @@ Reads a FloatArray from this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | ------ | -------- | ---- | ------ | - | dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| +| Name| Type| Mandatory| Description| +| ------ | -------- | ---- | ------ | +| dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| **Example** @@ -4470,9 +4481,9 @@ Reads the FloatArray from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | -------------- | - | number[] | FloatArray read.| +| Type | Description | +| -------- | -------------- | +| number[] | FloatArray read.| **Example** @@ -4494,15 +4505,15 @@ Writes a DoubleArray to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ----------- | -------- | ---- | ------------------------ | - | doubleArray | number[] | Yes | DoubleArray to write.| +| Name | Type | Mandatory| Description | +| ----------- | -------- | ---- | ------------------------ | +| doubleArray | number[] | Yes | DoubleArray to write.| **Return value** - | Type | Description | - | ------- | ----------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4522,9 +4533,9 @@ Reads a DoubleArray from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ------------------------ | - | dataIn | number[] | Yes | DoubleArray to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------------------ | +| dataIn | number[] | Yes | DoubleArray to read.| **Example** @@ -4546,9 +4557,9 @@ Reads the DoubleArray from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | -------------------- | - | number[] | DoubleArray read.| +| Type | Description | +| -------- | -------------------- | +| number[] | DoubleArray read.| **Example** @@ -4570,15 +4581,15 @@ Writes a Boolean array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ------------ | --------- | ---- | ------------------ | - | booleanArray | boolean[] | Yes | Boolean array to write.| +| Name | Type | Mandatory| Description | +| ------------ | --------- | ---- | ------------------ | +| booleanArray | boolean[] | Yes | Boolean array to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4598,9 +4609,9 @@ Reads a Boolean array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | --------- | ---- | ------------------ | - | dataIn | boolean[] | Yes | Boolean array to read.| +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ------------------ | +| dataIn | boolean[] | Yes | Boolean array to read.| **Example** @@ -4622,9 +4633,9 @@ Reads the Boolean array from this **MessageParcel** object. **Return value** - | Type | Description | - | --------- | -------------- | - | boolean[] | Boolean array read.| +| Type | Description | +| --------- | -------------- | +| boolean[] | Boolean array read.| **Example** @@ -4646,15 +4657,15 @@ Writes a character array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | -------- | ---- | ---------------------- | - | charArray | number[] | Yes | Character array to write.| +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | ---------------------- | +| charArray | number[] | Yes | Character array to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4674,9 +4685,9 @@ Reads a character array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | ---------------------- | - | dataIn | number[] | Yes | Character array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| dataIn | number[] | Yes | Character array to read.| **Example** @@ -4698,9 +4709,9 @@ Reads the character array from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | ------------------ | - | number[] | Character array read.| +| Type | Description | +| -------- | ------------------ | +| number[] | Character array read.| **Example** @@ -4722,15 +4733,15 @@ Writes a string array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description| - | ----------- | -------- | ---- | ---------------- | - | stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| +| Name | Type | Mandatory| Description| +| ----------- | -------- | ---- | ---------------- | +| stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| **Return value** - | Type | Description| - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description| +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4750,9 +4761,9 @@ Reads a string array from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------- | - | dataIn | string[] | Yes | String array to read.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| dataIn | string[] | Yes | String array to read.| **Example** @@ -4774,9 +4785,9 @@ Reads the string array from this **MessageParcel** object. **Return value** - | Type | Description | - | -------- | ---------------- | - | string[] | String array read.| +| Type | Description | +| -------- | ---------------- | +| string[] | String array read.| **Example** @@ -4840,6 +4851,8 @@ Reads the exception information from this **MessageParcel** object. **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -4860,6 +4873,11 @@ Reads the exception information from this **MessageParcel** object. "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageParcel.create(); let reply = rpc.MessageParcel.create(); @@ -4894,15 +4912,15 @@ Writes a sequenceable array to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ----------------- | -------------- | ---- | -------------------------- | - | sequenceableArray | Sequenceable[] | Yes | Sequenceable array to write.| +| Name | Type | Mandatory| Description | +| ----------------- | -------------- | ---- | -------------------------- | +| sequenceableArray | Sequenceable[] | Yes | Sequenceable array to write.| **Return value** - | Type | Description | - | ------- | --------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -4944,9 +4962,9 @@ Reads a sequenceable array from this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ----------------- | -------------- | ---- | -------------------------- | - | sequenceableArray | Sequenceable[] | Yes | Sequenceable array to read.| +| Name | Type | Mandatory| Description | +| ----------------- | -------------- | ---- | -------------------------- | +| sequenceableArray | Sequenceable[] | Yes | Sequenceable array to read.| **Example** @@ -4990,15 +5008,15 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description| - | ----------- | --------------- | ---- | ----- | - | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| +| Name | Type | Mandatory| Description| +| ----------- | --------------- | ---- | ----- | +| objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| **Return value** - | Type | Description | - | ------- | -------------------------------------------------------------------------------------------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | -------------------------------------------------------------------------------------------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -5042,9 +5060,9 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description| - | ------- | --------------- | ---- | --------- | - | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| +| Name | Type | Mandatory| Description| +| ------- | --------------- | ---- | --------- | +| objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| **Example** @@ -5089,9 +5107,9 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. **Return value** - | Type| Description| - | --------------- | -------- | - | IRemoteObject[] | **IRemoteObject** object array obtained.| +| Type| Description| +| --------------- | -------- | +| IRemoteObject[] | **IRemoteObject** object array obtained.| **Example** @@ -5137,9 +5155,9 @@ Closes a file descriptor. This API is a static method. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------- | - | fd | number | Yes | File descriptor to close.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| fd | number | Yes | File descriptor to close.| **Example** @@ -5160,15 +5178,15 @@ Duplicates a file descriptor. This API is a static method. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | fd | number | Yes | File descriptor to duplicate.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| fd | number | Yes | File descriptor to duplicate.| **Return value** - | Type | Description | - | ------ | -------------------- | - | number | New file descriptor.| +| Type | Description | +| ------ | -------------------- | +| number | New file descriptor.| **Example** @@ -5183,15 +5201,15 @@ Duplicates a file descriptor. This API is a static method. containFileDescriptors(): boolean -Checks whether this **MessageParcel** object contains a file descriptor. +Checks whether this **MessageParcel** object contains file descriptors. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type | Description | - | ------- | ------------------------------------------------------------------ | - | boolean |Returns **true** if the **MessageSequence** object contains a file descriptor; returns **false** otherwise.| +| Type | Description | +| ------- | ------------------------------------------------------------------ | +| boolean |Returns **true** if the **MessageParcel** object contains file descriptors; returns **false** otherwise.| **Example** @@ -5217,15 +5235,15 @@ Writes a file descriptor to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| fd | number | Yes | File descriptor to write.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -5248,9 +5266,9 @@ Reads the file descriptor from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ---------------- | - | number | File descriptor read.| +| Type | Description | +| ------ | ---------------- | +| number | File descriptor read.| **Example** @@ -5274,15 +5292,15 @@ Writes an anonymous shared object to this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ----------------------------------- | - | ashmem | Ashmem | Yes | Anonymous shared object to write.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------- | +| ashmem | Ashmem | Yes | Anonymous shared object to write.| **Return value** - | Type | Description | - | ------- | -------------------------------------------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | -------------------------------------------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -5303,9 +5321,9 @@ Reads the anonymous shared object from this **MessageParcel** object. **Return value** - | Type | Description | - | ------ | ------------------ | - | Ashmem | Anonymous share object obtained.| +| Type | Description | +| ------ | ------------------ | +| Ashmem | Anonymous share object obtained.| **Example** @@ -5328,9 +5346,9 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel* **Return value** - | Type | Description | - | ------ | ---------------------------------------------------------- | - | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object.| +| Type | Description | +| ------ | ---------------------------------------------------------- | +| number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object.| **Example** @@ -5350,16 +5368,16 @@ Writes raw data to this **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ------- | -------- | ---- | ---------------------------------- | - | rawData | number[] | Yes | Raw data to write. | - | size | number | Yes | Size of the raw data, in bytes.| +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ---------------------------------- | +| rawData | number[] | Yes | Raw data to write. | +| size | number | Yes | Size of the raw data, in bytes.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -5380,15 +5398,15 @@ Reads raw data from this **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | size | number | Yes | Size of the raw data to read.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| size | number | Yes | Size of the raw data to read.| **Return value** - | Type | Description | - | -------- | ------------------------------ | - | number[] | Raw data obtained, in bytes.| +| Type | Description | +| -------- | ------------------------------ | +| number[] | Raw data obtained, in bytes.| **Example** @@ -5415,15 +5433,15 @@ Marshals this **Parcelable** object into a **MessageSequence** object. **Parameters** - | Name | Type | Mandatory| Description | - | ------- | --------------- | ---- | ------------------------------------------- | - | dataOut | MessageSequence | Yes | **MessageSequence** object to which the **Parcelable** object is to be marshaled.| +| Name | Type | Mandatory| Description | +| ------- | --------------- | ---- | ------------------------------------------- | +| dataOut | MessageSequence | Yes | **MessageSequence** object to which the **Parcelable** object is to be marshaled.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```ts @@ -5464,15 +5482,15 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | --------------- | ---- | ----------------------------------------------- | - | dataIn | MessageSequence | Yes | **MessageSequence** object from which the **Parcelable** object is to be unmarshaled.| +| Name| Type | Mandatory| Description | +| ------ | --------------- | ---- | ----------------------------------------------- | +| dataIn | MessageSequence | Yes | **MessageSequence** object from which the **Parcelable** object is to be unmarshaled.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -5520,15 +5538,15 @@ Marshals the sequenceable object into a **MessageParcel** object. **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | ----------------------------------------- | - | dataOut | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object to which the sequenceable object is to be marshaled.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ----------------------------------------- | +| dataOut | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object to which the sequenceable object is to be marshaled.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ```ts @@ -5569,15 +5587,15 @@ Unmarshals this sequenceable object from a **MessageParcel** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | --------------------------------------------- | - | dataIn | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object in which the sequenceable object is to be unmarshaled.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | --------------------------------------------- | +| dataIn | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object in which the sequenceable object is to be unmarshaled.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -5623,9 +5641,9 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl **Return value** - | Type | Description| - | ---- | ----- | - | [IRemoteObject](#iremoteobject) | Returns the **RemoteObject** if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| +| Type | Description| +| ---- | ----- | +| [IRemoteObject](#iremoteobject) | Returns the **RemoteObject** if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| **Example** @@ -5640,6 +5658,8 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -5660,7 +5680,11 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **asObject()** of the proxy object is called to obtain the proxy or remote object. + ```ts class TestProxy { remote: rpc.RemoteObject; constructor(remote) { @@ -5702,12 +5726,12 @@ Defines the response to the request. **System capability**: SystemCapability.Communication.IPC.Core - | Name | Type | Readable| Writable| Description | - | ------- | --------------- | ---- | ---- |-------------------------------------- | - | errCode | number | Yes | No | Error Code | - | code | number | Yes | No | Message code. | - | data | MessageSequence | Yes | No | **MessageSequence** object sent to the remote process.| - | reply | MessageSequence | Yes | No | **MessageSequence** object returned by the remote process. | +| Name | Type | Readable| Writable| Description | +| ------- | --------------- | ---- | ---- |-------------------------------------- | +| errCode | number | Yes | No | Error Code | +| code | number | Yes | No | Message code. | +| data | MessageSequence | Yes | No | **MessageSequence** object sent to the remote process.| +| reply | MessageSequence | Yes | No | **MessageSequence** object returned by the remote process. | ## SendRequestResult8+(deprecated) @@ -5717,12 +5741,12 @@ Defines the response to the request. **System capability**: SystemCapability.Communication.IPC.Core - | Name | Type | Readable| Writable| Description | - | ------- | ------------- | ---- | ---- | ----------------------------------- | - | errCode | number | Yes | No | Error Code | - | code | number | Yes | No | Message code. | - | data | MessageParcel | Yes | No | **MessageParcel** object sent to the remote process.| - | reply | MessageParcel | Yes | No | **MessageParcel** object returned by the remote process. | +| Name | Type | Readable| Writable| Description | +| ------- | ------------- | ---- | ---- | ----------------------------------- | +| errCode | number | Yes | No | Error Code | +| code | number | Yes | No | Message code. | +| data | MessageParcel | Yes | No | **MessageParcel** object sent to the remote process.| +| reply | MessageParcel | Yes | No | **MessageParcel** object returned by the remote process. | ## IRemoteObject @@ -5738,15 +5762,15 @@ Obtains the interface descriptor. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------ | ---- | -------------------- | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------- | +| descriptor | string | Yes | Interface descriptor.| **Return value** - | Type | Description | - | ------------- | --------------------------------------------- | - | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| +| Type | Description | +| ------------- | --------------------------------------------- | +| IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| ### queryLocalInterface(deprecated) @@ -5760,15 +5784,15 @@ Queries the interface descriptor. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------ | ---- | -------------------- | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------- | +| descriptor | string | Yes | Interface descriptor.| **Return value** - | Type | Description | - | ------------- | --------------------------------------------- | - | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| +| Type | Description | +| ------------- | --------------------------------------------- | +| IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| ### sendRequest(deprecated) @@ -5776,24 +5800,24 @@ Queries the interface descriptor. sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message does not contain any content. If synchronous mode is set in **options** , a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type| Mandatory| Description | - | ------- | ------------------------------- | ---- | ---- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type| Mandatory| Description | +| ------- | ------------------------------- | ---- | ---- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| ### sendRequest8+(deprecated) @@ -5802,67 +5826,67 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | -------------------------------- | --------------------------------------------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| +| Type | Description | +| -------------------------------- | --------------------------------------------- | +| Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| ### sendMessageRequest9+ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> -Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | ---------------------------- | ----------------------------------------- | - | Promise<RequestResult> | Promise used to return the **requestResult** object.| +| Type | Description | +| ---------------------------- | ----------------------------------------- | +| Promise<RequestResult> | Promise used to return the **requestResult** object.| ### sendMessageRequest9+ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void -Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a callback will be called immediately, and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | ### sendRequest8+(deprecated) @@ -5870,42 +5894,42 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a callback will be called immediately, and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | ### registerDeathRecipient9+ registerDeathRecipient(recipient: DeathRecipient, flags: number): void -Registers a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. +Registers a callback for receiving death notifications of the remote object. The callback will be called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.| - | flags | number | Yes | Flag of the death notification.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | -------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.| +| flags | number | Yes | Flag of the death notification.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | ### addDeathrecipient(deprecated) @@ -5919,16 +5943,16 @@ Adds a callback for receiving death notifications of the remote object. This met **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| - | flags | number | Yes | Flag of the death notification.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | -------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| +| flags | number | Yes | Flag of the death notification.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is added successfully; return **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| ### unregisterDeathRecipient9+ @@ -5941,18 +5965,18 @@ Unregisters the callback used to receive death notifications of the remote objec **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.| - | flags | number | Yes | Flag of the death notification.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | -------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.| +| flags | number | Yes | Flag of the death notification.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | ### removeDeathRecipient(deprecated) @@ -5966,38 +5990,38 @@ Removes the callback used to receive death notifications of the remote object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| - | flags | number | Yes | Flag of the death notification.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | -------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| +| flags | number | Yes | Flag of the death notification.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is removed; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the callback is removed; returns **false** otherwise.| ### getDescriptor9+ getDescriptor(): string -Obtains the interface descriptor of this object. The interface descriptor is a string. +Obtains the interface descriptor (which is a string) of this object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type | Description | - | ------ | ---------------- | - | string | Interface descriptor obtained.| +| Type | Description | +| ------ | ---------------- | +| string | Interface descriptor obtained.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | ### getInterfaceDescriptor(deprecated) @@ -6006,15 +6030,15 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode getInterfaceDescriptor(): string -Obtains the interface descriptor of this object. The interface descriptor is a string. +Obtains the interface descriptor (which is a string) of this object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type | Description | - | ------ | ---------------- | - | string | Interface descriptor obtained.| +| Type | Description | +| ------ | ---------------- | +| string | Interface descriptor obtained.| ### isObjectDead @@ -6027,9 +6051,9 @@ Checks whether this object is dead. **Return value** - | Type | Description | - | ------- | ------------------------------------------- | - | boolean | Returns **true** if the object is dead; returns **false** otherwise.| +| Type | Description | +| ------- | ------------------------------------------- | +| boolean | Returns **true** if the object is dead; returns **false** otherwise.| ## RemoteProxy @@ -6052,27 +6076,29 @@ Provides APIs to implement **IRemoteObject**. sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6093,6 +6119,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageParcel.create(); let reply = rpc.MessageParcel.create(); @@ -6115,27 +6146,29 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> -Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | ---------------------------- | ----------------------------------------- | - | Promise<RequestResult> | Promise used to return the **requestResult** object.| +| Type | Description | +| ---------------------------- | ----------------------------------------- | +| Promise<RequestResult> | Promise used to return the **requestResult** object.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6156,6 +6189,11 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageSequence.create(); let reply = rpc.MessageSequence.create(); @@ -6186,27 +6224,29 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | -------------------------------- | --------------------------------------------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| +| Type | Description | +| -------------------------------- | --------------------------------------------- | +| Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6227,6 +6267,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageParcel.create(); let reply = rpc.MessageParcel.create(); @@ -6255,22 +6300,24 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void -Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked at certain time after the response to **sendMessageRequest** is returned, and the reply contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a callback will be called immediately, and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If **options** is the synchronous mode, a callback will be invoked at certain time after the response to **sendMessageRequest** is returned, and the reply contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6304,6 +6351,11 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn result.reply.reclaim(); } FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageSequence.create(); let reply = rpc.MessageSequence.create(); @@ -6323,22 +6375,24 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a callback will be called immediately, and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6372,6 +6426,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch result.reply.reclaim(); } FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message. + + ```ts let option = new rpc.MessageOption(); let data = rpc.MessageParcel.create(); let reply = rpc.MessageParcel.create(); @@ -6390,26 +6449,28 @@ Obtains the **LocalInterface** object of an interface token. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | ------ | ---- | ---------------------- | - | interface | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------- | +| interface | string | Yes | Interface descriptor.| **Return value** - | Type | Description | - | ------------- | ------------------------------------------ | - | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| +| Type | Description | +| ------------- | ------------------------------------------ | +| IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900006 | only remote object permitted | +| ID| Error Message| +| ------- | -------- | +| 1900006 | only remote object permitted | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6430,6 +6491,11 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode "abilityName":"com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getLocalInterface()** of the proxy object is called to obtain the interface descriptor. + + ```ts try { let broker = proxy.getLocalInterface("testObject"); console.log("RpcClient: getLocalInterface is " + broker); @@ -6451,18 +6517,20 @@ Obtains the **LocalInterface** object of an interface token. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | ------ | ---- | ---------------------- | - | interface | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------- | +| interface | string | Yes | Interface descriptor.| **Return value** - | Type | Description | - | ------------- | ------------------------------------------ | - | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| +| Type | Description | +| ------------- | ------------------------------------------ | +| IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6483,6 +6551,11 @@ Obtains the **LocalInterface** object of an interface token. "abilityName":"com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **queryLocalInterface()** of the proxy object is called to obtain the interface descriptor. + + ```ts let broker = proxy.queryLocalInterface("testObject"); console.log("RpcClient: queryLocalInterface is " + broker); ``` @@ -6491,27 +6564,29 @@ Obtains the **LocalInterface** object of an interface token. registerDeathRecipient(recipient: DeathRecipient, flags: number): void -Registers a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. +Registers a callback for receiving death notifications of the remote object. The callback will be invoked when the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.| - | flags | number | Yes | Flag of the death notification.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | -------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.| +| flags | number | Yes | Flag of the death notification.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6532,6 +6607,11 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **registerDeathRecipient()** of the proxy object is called to register a callback for receiving the death notification of the remote object. + + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -6539,7 +6619,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } let deathRecipient = new MyDeathRecipient(); try { - proxy.registerDeathRecippient(deathRecipient, 0); + proxy.registerDeathRecipient(deathRecipient, 0); } catch(error) { console.info("proxy register deathRecipient fail, errorCode " + error.code); console.info("proxy register deathRecipient fail, errorMessage " + error.message); @@ -6558,19 +6638,21 @@ Adds a callback for receiving the death notifications of the remote object, incl **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | --------------------------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add. | - | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | --------------------------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add. | +| flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is added successfully; return **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6591,18 +6673,23 @@ Adds a callback for receiving the death notifications of the remote object, incl "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **addDeathRecippient()** of the proxy object is called to add a callback for receiving the death notification of the remove object. + + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); } } let deathRecipient = new MyDeathRecipient(); - proxy.addDeathRecippient(deathRecipient, 0); + proxy.addDeathRecipient(deathRecipient, 0); ``` ### unregisterDeathRecipient9+ -unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean +unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void Unregisters the callback used to receive death notifications of the remote object. @@ -6610,21 +6697,23 @@ Unregisters the callback used to receive death notifications of the remote objec **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.| - | flags | number | Yes | Flag of the death notification.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | -------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.| +| flags | number | Yes | Flag of the death notification.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6645,6 +6734,11 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **unregisterDeathRecipient()** of the proxy object is called to unregister the callback for receiving the death notification of the remote object. + + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -6672,19 +6766,21 @@ Removes the callback used to receive death notifications of the remote object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | --------------------------------- | ---- | --------------------------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove. | - | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------- | ---- | --------------------------------- | +| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove. | +| flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is removed; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the callback is removed; returns **false** otherwise.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6705,6 +6801,11 @@ Removes the callback used to receive death notifications of the remote object. "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **removeDeathRecipient()** of the proxy object is called to remove the callback used to receive the death notification of the remote object. + + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -6719,27 +6820,29 @@ Removes the callback used to receive death notifications of the remote object. getDescriptor(): string -Obtains the interface descriptor of this object. The interface descriptor is a string. +Obtains the interface descriptor (which is a string) of this proxy object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type | Description | - | ------ | ---------------- | - | string | Interface descriptor obtained.| +| Type | Description | +| ------ | ---------------- | +| string | Interface descriptor obtained.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900008 | proxy or remote object is invalid | - | 1900007 | communication failed | +| ID| Error Message| +| -------- | ------- | +| 1900008 | proxy or remote object is invalid | +| 1900007 | communication failed | **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6760,6 +6863,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getDescriptor()** of the proxy object is called to obtain the interface descriptor of the object. + + ```ts try { let descriptor = proxy.getDescriptor(); console.log("RpcClient: descriptor is " + descriptor); @@ -6781,12 +6888,14 @@ Obtains the interface descriptor of this proxy object. **Return value** - | Type | Description | - | ------ | ------------------ | - | string | Interface descriptor obtained.| +| Type | Description | +| ------ | ------------------ | +| string | Interface descriptor obtained.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6807,6 +6916,11 @@ Obtains the interface descriptor of this proxy object. "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getInterfaceDescriptor()** of the proxy object is called to obtain the interface descriptor of the current proxy object. + + ```ts let descriptor = proxy.getInterfaceDescriptor(); console.log("RpcClient: descriptor is " + descriptor); ``` @@ -6821,12 +6935,14 @@ Checks whether the **RemoteObject** is dead. **Return value** - | Type | Description | - | ------- | --------------------------------------------------------- | - | boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------------------- | +| boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.| **Example** + Obtain the service. + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; @@ -6847,6 +6963,11 @@ Checks whether the **RemoteObject** is dead. "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); + ``` + +The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **isObjectDead()** of the proxy object is called to check whether this object is dead. + + ```ts let isDead = proxy.isObjectDead(); console.log("RpcClient: isObjectDead is " + isDead); ``` @@ -6857,12 +6978,12 @@ Provides common message options (flag and wait time). Use the specified flag to **System capability**: SystemCapability.Communication.IPC.Core - | Name | Value | Description | - | ------------- | ---- | ----------------------------------------------------------- | - | TF_SYNC | 0 | Synchronous call. | - | TF_ASYNC | 1 | Asynchronous call. | - | TF_ACCEPT_FDS | 0x10 | Indication to **sendMessageRequest9+** for returning the file descriptor.| - | TF_WAIT_TIME | 8 | Default waiting time, in seconds. | +| Name | Value | Description | +| ------------- | ---- | ----------------------------------------------------------- | +| TF_SYNC | 0 | Synchronous call. | +| TF_ASYNC | 1 | Asynchronous call. | +| TF_ACCEPT_FDS | 0x10 | Indication to **sendMessageRequest9+** for returning the file descriptor.| +| TF_WAIT_TIME | 8 | Default waiting time, in seconds. | ### constructor9+ @@ -6875,9 +6996,9 @@ A constructor used to create a **MessageOption** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | ------ | ---- | -------------------------------------- | - | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------- | +| syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| **Example** @@ -6900,10 +7021,10 @@ A constructor used to create a **MessageOption** object. **Parameters** - | Name | Type | Mandatory| Description | - | --------- | ------ | ---- | --------------------------------------------- | - | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. | - | waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------------------------------- | +| syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. | +| waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| **Example** @@ -6924,9 +7045,9 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously. **Return value** - | Type | Description | - | ------- | ------------------------------------ | - | boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.| +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.| **Example** @@ -6961,9 +7082,9 @@ Obtains the call flag, which can be synchronous or asynchronous. **Return value** - | Type | Description | - | ------ | ------------------------------------ | - | number | Call mode obtained.| +| Type | Description | +| ------ | ------------------------------------ | +| number | Call mode obtained.| **Example** @@ -6992,9 +7113,9 @@ Sets the call flag, which can be synchronous or asynchronous. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | flags | number | Yes | Call flag to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| flags | number | Yes | Call flag to set.| **Example** @@ -7020,9 +7141,9 @@ Obtains the maximum wait time for this RPC call. **Return value** - | Type | Description | - | ------ | ----------------- | - | number | Maximum wait time obtained.| +| Type | Description | +| ------ | ----------------- | +| number | Maximum wait time obtained.| **Example** @@ -7049,9 +7170,9 @@ Sets the maximum wait time for this RPC call. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------ | ---- | --------------------- | - | waitTime | number | Yes | Maximum wait time to set.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | --------------------- | +| waitTime | number | Yes | Maximum wait time to set.| **Example** @@ -7080,9 +7201,9 @@ Obtains the system capability manager. This API is a static method. **Return value** - | Type | Description | - | ------------------------------- | -------------------- | - | [IRemoteObject](#iremoteobject) | System capability manager obtained.| +| Type | Description | +| ------------------------------- | -------------------- | +| [IRemoteObject](#iremoteobject) | System capability manager obtained.| **Example** @@ -7101,9 +7222,9 @@ Obtains the PID of the caller. This API is a static method, which is invoked by **Return value** - | Type | Description | - | ------ | ----------------- | - | number | PID of the caller.| +| Type | Description | +| ------ | ----------------- | +| number | PID of the caller.| **Example** @@ -7127,9 +7248,9 @@ Obtains the UID of the caller. This API is a static method, which is invoked by **Return value** - | Type | Description | - | ------ | ----------------- | - | number | UID of the caller.| +| Type | Description | +| ------ | ----------------- | +| number | UID of the caller.| **Example** @@ -7153,9 +7274,9 @@ Obtains the caller's token ID, which is used to verify the caller identity. **Return value** - | Type | Description | - | ------ | --------------------- | - | number | Token ID of the caller obtained.| +| Type | Description | +| ------ | --------------------- | +| number | Token ID of the caller obtained.| **Example** @@ -7174,15 +7295,15 @@ Obtains the caller's token ID, which is used to verify the caller identity. static getCallingDeviceID(): string -Obtains the ID of the device hosting the caller's process. +Obtains the ID of the device hosting the caller's process. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type | Description | - | ------ | ---------------------------- | - | string | Device ID obtained.| +| Type | Description | +| ------ | ---------------------------- | +| string | Device ID obtained.| **Example** @@ -7206,9 +7327,9 @@ Obtains the local device ID. This API is a static method. **Return value** - | Type | Description | - | ------ | ------------------ | - | string | Local device ID obtained.| +| Type | Description | +| ------ | ------------------ | +| string | Local device ID obtained.| **Example** @@ -7232,9 +7353,9 @@ Checks whether the remote process is a process of the local device. This API is **Return value** - | Type | Description | - | ------- | --------------------------------------------------------- | - | boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------------------- | +| boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.| **Example** @@ -7258,9 +7379,9 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | ------------------- | - | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | ------------------- | +| object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | **Example** @@ -7292,15 +7413,15 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | ------------------- | - | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | ------------------- | +| object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | **Return value** - | Type | Description | - | ------ | --------------------------------------------------------------------------------- | - | number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or if the operation fails.| +| Type | Description | +| ------ | --------------------------------------------------------------------------------- | +| number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or if the operation fails.| **Example** @@ -7339,9 +7460,9 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. **Return value** - | Type | Description | - | ------ | ------------------------------------ | - | string | String containing the UID and PID of the remote user.| +| Type | Description | +| ------ | ------------------------------------ | +| string | String containing the UID and PID of the remote user.| **Example** @@ -7366,9 +7487,9 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------ | ---- | ------------------------------------------------------------------ | - | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------------ | +| identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| **Example** @@ -7393,21 +7514,21 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. static setCallingIdentity(identity: string): boolean -Restores the UID and PID of the remote user. This API is a static method. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. +Sets the UID and PID of the remote user. This API is a static method. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------ | ---- | ------------------------------------------------------------------ | - | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------------ | +| identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -7441,9 +7562,9 @@ A constructor used to create a **RemoteObject** object. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------ | ---- | ------------ | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------ | +| descriptor | string | Yes | Interface descriptor.| ### sendRequest(deprecated) @@ -7452,24 +7573,24 @@ A constructor used to create a **RemoteObject** object. sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | ------- | --------------------------------------------- | - | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| **Example** @@ -7518,24 +7639,24 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | -------------------------------- | --------------------------------------------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| +| Type | Description | +| -------------------------------- | --------------------------------------------- | +| Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| **Example** @@ -7588,24 +7709,24 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> -Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a promise will be fulfilled immediately and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type | Description | - | ---------------------------- | --------------------------------------------- | - | Promise<RequestResult> | Promise used to return the **sendRequestResult** object.| +| Type | Description | +| ---------------------------- | --------------------------------------------- | +| Promise<RequestResult> | Promise used to return the **sendRequestResult** object.| **Example** @@ -7644,19 +7765,19 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void -Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a callback will be called immediately, and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a callback will be invoked when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | AsyncCallback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| AsyncCallback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | **Example** @@ -7694,19 +7815,19 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If asynchronous mode is set in **options**, a callback will be called immediately, and the reply message is empty. The specific reply needs to be obtained from the callback on the service side. If synchronous mode is set in **options**, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name | Type | Mandatory| Description | - | ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | - | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | - | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | - | AsyncCallback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | +| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | +| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | +| AsyncCallback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | **Example** @@ -7764,18 +7885,18 @@ Provides a response to **sendMessageRequest()**. The server processes the reques **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | --------------------------------------- | - | code | number | Yes | Service request code sent by the remote end. | - | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that holds the parameters called by the client.| - | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object carrying the result. | - | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | --------------------------------------- | +| code | number | Yes | Service request code sent by the remote end. | +| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that holds the parameters called by the client.| +| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object carrying the result. | +| option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -7825,19 +7946,19 @@ Provides a response to **sendMessageRequest()**. The server processes the reques **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------------------------------- | ---- | ----------------------------------------- | - | code | number | Yes | Service request code sent by the remote end. | - | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that holds the parameters called by the client.| - | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object to which the result is written. | - | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | ----------------------------------------- | +| code | number | Yes | Service request code sent by the remote end. | +| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that holds the parameters called by the client.| +| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object to which the result is written. | +| option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | **Return value** - | Type | Description | - | ----------------- | ---------------------------------------------------------------------------------------------- | - | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. The value **true** means the operation is successful; the value **false** means the opposite.| - | Promise\ | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. | +| Type | Description | +| ----------------- | ---------------------------------------------------------------------------------------------- | +| boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. The value **true** means the operation is successful; the value **false** means the opposite.| +| Promise\ | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. | **Example**: Overload **onRemoteMessageRequest** to process requests synchronously. @@ -7955,9 +8076,9 @@ Obtains the UID of the remote process. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type | Description | - | ------ | ----------------------- | - | number | UID of the remote process obtained.| +| Type | Description | +| ------ | ----------------------- | +| number | UID of the remote process obtained.| **Example** @@ -7981,9 +8102,9 @@ Obtains the PID of the remote process. **Return value** - | Type | Description | - | ------ | ----------------------- | - | number | PID of the remote process obtained.| +| Type | Description | +| ------ | ----------------------- | +| number | PID of the remote process obtained.| **Example** @@ -8007,15 +8128,15 @@ Obtains the interface descriptor. **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------ | ---- | -------------------- | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------- | +| descriptor | string | Yes | Interface descriptor.| **Return value** - | Type | Description | - | ------------- | --------------------------------------------- | - | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| +| Type | Description | +| ------------- | --------------------------------------------- | +| IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| **Example** @@ -8030,8 +8151,12 @@ Obtains the interface descriptor. constructor(descriptor) { super(descriptor); } - registerDeathRecipient(recipient: MyDeathRecipient, flags: number); - unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); + registerDeathRecipient(recipient: MyDeathRecipient, flags: number) { + // Implement the method logic based on service requirements. + } + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number) { + // Implement the method logic based on service requirements. + } isObjectDead(): boolean { return false; } @@ -8040,8 +8165,8 @@ Obtains the interface descriptor. try { let broker = testRemoteObject.getLocalInterface("testObject"); } catch(error) { - console.info(rpc get local interface fail, errorCode " + error.code); - console.info(rpc get local interface fail, errorMessage " + error.message); + console.info("rpc get local interface fail, errorCode " + error.code); + console.info("rpc get local interface fail, errorMessage " + error.message); } ``` @@ -8057,15 +8182,15 @@ Checks whether the remote object corresponding to the specified interface token **Parameters** - | Name | Type | Mandatory| Description | - | ---------- | ------ | ---- | ---------------------- | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------------------- | +| descriptor | string | Yes | Interface descriptor.| **Return value** - | Type | Description | - | ------------- | ------------------------------------------------------------------ | - | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| +| Type | Description | +| ------------- | ------------------------------------------------------------------ | +| IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| **Example** @@ -8103,17 +8228,17 @@ Obtains the interface descriptor of this object. The interface descriptor is a s **Return value** - | Type | Description | - | ------ | ---------------- | - | string | Interface descriptor obtained.| +| Type | Description | +| ------ | ---------------- | +| string | Interface descriptor obtained.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900008 | proxy or remote object is invalid | +| ID| Error Message| +| ------- | -------- | +| 1900008 | proxy or remote object is invalid | **Example** @@ -8127,8 +8252,12 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number); - unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); + registerDeathRecipient(recipient: MyDeathRecipient, flags: number) { + // Implement the method logic based on service requirements. + } + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number) { + // Implement the method logic based on service requirements. + } isObjectDead(): boolean { return false; } @@ -8137,8 +8266,8 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode try { let descriptor = testRemoteObject.getDescriptor(); } catch(error) { - console.info(rpc get local interface fail, errorCode " + error.code); - console.info(rpc get local interface fail, errorMessage " + error.message); + console.info("rpc get local interface fail, errorCode " + error.code); + console.info("rpc get local interface fail, errorMessage " + error.message); } console.log("RpcServer: descriptor is: " + descriptor); ``` @@ -8155,9 +8284,9 @@ Obtains the interface descriptor. **Return value** - | Type | Description | - | ------ | ---------------- | - | string | Interface descriptor obtained.| +| Type | Description | +| ------ | ---------------- | +| string | Interface descriptor obtained.| **Example** @@ -8196,10 +8325,10 @@ Binds an interface descriptor to an **IRemoteBroker** object. **Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------- | ---- | ------------------------------------- | - | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| -------------- | ------------- | ---- | ------------------------------------- | +| localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | +| descriptor | string | Yes | Interface descriptor.| **Example** @@ -8219,8 +8348,12 @@ Binds an interface descriptor to an **IRemoteBroker** object. console.info(rpc attach local interface fail, errorMessage " + error.message); } } - registerDeathRecipient(recipient: MyDeathRecipient, flags: number); - unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); + registerDeathRecipient(recipient: MyDeathRecipient, flags: number) { + // Implement the method logic based on service requirements. + } + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number) { + // Implement the method logic based on service requirements. + } isObjectDead(): boolean { return false; } @@ -8243,10 +8376,10 @@ Binds an interface descriptor to an **IRemoteBroker** object. **Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------- | ---- | ------------------------------------- | - | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | - | descriptor | string | Yes | Interface descriptor.| +| Name | Type | Mandatory| Description | +| -------------- | ------------- | ---- | ------------------------------------- | +| localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | +| descriptor | string | Yes | Interface descriptor.| **Example** @@ -8285,12 +8418,12 @@ Provides methods related to anonymous shared memory objects, including creating, The table below describes the protection types of the mapped memory. - | Name | Value | Description | - | ---------- | --- | ------------------ | - | PROT_EXEC | 4 | The mapped memory is executable. | - | PROT_NONE | 0 | The mapped memory is inaccessible.| - | PROT_READ | 1 | The mapped memory is readable. | - | PROT_WRITE | 2 | The mapped memory is writeable. | +| Name | Value | Description | +| ---------- | --- | ------------------ | +| PROT_EXEC | 4 | The mapped memory is executable. | +| PROT_NONE | 0 | The mapped memory is inaccessible.| +| PROT_READ | 1 | The mapped memory is readable. | +| PROT_WRITE | 2 | The mapped memory is writeable. | ### create9+ @@ -8302,16 +8435,16 @@ Creates an **Ashmem** object with the specified name and size. This API is a sta **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------------- | - | name | string | Yes | Name of the **Ashmem** object to create. | - | size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| name | string | Yes | Name of the **Ashmem** object to create. | +| size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| **Return value** - | Type | Description | - | ------ | ---------------------------------------------- | - | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| +| Type | Description | +| ------ | ---------------------------------------------- | +| Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| **Example** @@ -8339,16 +8472,16 @@ Creates an **Ashmem** object with the specified name and size. This API is a sta **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------------- | - | name | string | Yes | Name of the **Ashmem** object to create. | - | size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| name | string | Yes | Name of the **Ashmem** object to create. | +| size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| **Return value** - | Type | Description | - | ------ | ---------------------------------------------- | - | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| +| Type | Description | +| ------ | ---------------------------------------------- | +| Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| **Example** @@ -8368,15 +8501,15 @@ Creates an **Ashmem** object by copying the file descriptor of an existing **Ash **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------- | - | ashmem | Ashmem | Yes | Existing **Ashmem** object.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| ashmem | Ashmem | Yes | Existing **Ashmem** object.| **Return value** - | Type | Description | - | ------ | ---------------------- | - | Ashmem | **Ashmem** object created.| +| Type | Description | +| ------ | ---------------------- | +| Ashmem | **Ashmem** object created.| **Example** @@ -8406,15 +8539,15 @@ Creates an **Ashmem** object by copying the file descriptor of an existing **Ash **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------- | - | ashmem | Ashmem | Yes | Existing **Ashmem** object.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| ashmem | Ashmem | Yes | Existing **Ashmem** object.| **Return value** - | Type | Description | - | ------ | ---------------------- | - | Ashmem | **Ashmem** object created.| +| Type | Description | +| ------ | ---------------------- | +| Ashmem | **Ashmem** object created.| **Example** @@ -8465,9 +8598,9 @@ Obtains the memory size of this **Ashmem** object. **Return value** - | Type | Description | - | ------ | -------------------------- | - | number | **Ashmem** size obtained.| +| Type | Description | +| ------ | -------------------------- | +| number | **Ashmem** size obtained.| **Example** @@ -8487,17 +8620,17 @@ Creates the shared file mapping on the virtual address space of this process. Th **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ------------------------------ | - | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------ | +| mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | ------ | - | 1900001 | call mmap function failed | +| ID| Error Message| +| ------- | ------ | +| 1900001 | call mmap function failed | **Example** @@ -8523,15 +8656,15 @@ Creates the shared file mapping on the virtual address space of this process. Th **Parameters** - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ------------------------------ | - | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------ | +| mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the mapping is created; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the mapping is created; returns **false** otherwise.| **Example** @@ -8549,13 +8682,13 @@ Maps the shared file to the readable and writable virtual address space of the p **System capability**: SystemCapability.Communication.IPC.Core -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900001 | call mmap function failed | +| ID| Error Message| +| ------- | -------- | +| 1900001 | call mmap function failed | **Example** @@ -8581,9 +8714,9 @@ Maps the shared file to the readable and writable virtual address space of the p **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the mapping is created; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the mapping is created; returns **false** otherwise.| **Example** @@ -8601,13 +8734,13 @@ Maps the shared file to the read-only virtual address space of the process. **System capability**: SystemCapability.Communication.IPC.Core -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900001 | call mmap function failed | +| ID| Error Message| +| ------- | -------- | +| 1900001 | call mmap function failed | **Example** @@ -8633,9 +8766,9 @@ Maps the shared file to the read-only virtual address space of the process. **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the mapping is created; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the mapping is created; returns **false** otherwise.| **Example** @@ -8655,17 +8788,17 @@ Sets the protection level of the memory region to which the shared file is mappe **Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------ | ---- | ------------------ | - | protectionType | number | Yes | Protection type to set.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------ | +| protectionType | number | Yes | Protection type to set.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | -------- | ------- | - | 1900002 | call os ioctl function failed | +| ID| Error Message| +| -------- | ------- | +| 1900002 | call os ioctl function failed | **Example** @@ -8691,15 +8824,15 @@ Sets the protection level of the memory region to which the shared file is mappe **Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------ | ---- | ------------------ | - | protectionType | number | Yes | Protection type to set.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------ | +| protectionType | number | Yes | Protection type to set.| **Return value** - | Type | Description | - | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -8719,19 +8852,19 @@ Writes data to the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------------------------------------- | - | buf | number[] | Yes | Data to write. | - | size | number | Yes | Size of the data to write. | - | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------------------------------------- | +| buf | number[] | Yes | Data to write. | +| size | number | Yes | Size of the data to write. | +| offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID| Error Message| - | ------- | -------- | - | 1900003 | write to ashmem failed | +| ID| Error Message| +| ------- | -------- | +| 1900003 | write to ashmem failed | **Example** @@ -8759,17 +8892,17 @@ Writes data to the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | -------- | ---- | -------------------------------------------------- | - | buf | number[] | Yes | Data to write. | - | size | number | Yes | Size of the data to write. | - | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------------------------------------- | +| buf | number[] | Yes | Data to write. | +| size | number | Yes | Size of the data to write. | +| offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| **Return value** - | Type | Description | - | ------- | ----------------------------------------------------------------------------------------- | - | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| +| Type | Description | +| ------- | ----------------------------------------------------------------------------------------- | +| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** @@ -8792,24 +8925,24 @@ Reads data from the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------------------------------------- | - | size | number | Yes | Size of the data to read. | - | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------------------- | +| size | number | Yes | Size of the data to read. | +| offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| **Return value** - | Type | Description | - | -------- | ---------------- | - | number[] | Data read.| +| Type | Description | +| -------- | ---------------- | +| number[] | Data read.| -**Error Code** +**Error codes** For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). - | ID | Error Message| - | -------- | -------- | - | 1900004 | read from ashmem failed | +| ID | Error Message| +| -------- | -------- | +| 1900004 | read from ashmem failed | **Example** @@ -8839,16 +8972,16 @@ Reads data from the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------------------------------------------------- | - | size | number | Yes | Size of the data to read. | - | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------------------- | +| size | number | Yes | Size of the data to read. | +| offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| **Return value** - | Type | Description | - | -------- | ---------------- | - | number[] | Data read.| +| Type | Description | +| -------- | ---------------- | +| number[] | Data read.| **Example** @@ -8862,4 +8995,3 @@ Reads data from the shared file associated with this **Ashmem** object. let readResult = ashmem.readFromAshmem(5, 0); console.log("RpcTest: read to Ashmem result is : " + readResult); ``` - diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 22f25f8f0185b954270c2169fc657f0676244623..cc887122bc052addffca28197c745e52a6555807 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -724,8 +724,8 @@ Defines virtual screen parameters. | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------------------- | | name | string | Yes | Yes | Name of a virtual screen. | -| width | number | Yes | Yes | Width of the virtual screen. | -| height | number | Yes | Yes | Height of the virtual screen. | +| width | number | Yes | Yes | Width of the virtual screen, in pixels.| +| height | number | Yes | Yes | Height of the virtual screen, in pixels.| | density | number | Yes | Yes | Density of the virtual screen. | | surfaceId | string | Yes | Yes | Surface ID of the virtual screen.| @@ -735,6 +735,8 @@ Implements a **Screen** instance. Before calling any API in **Screen**, you must use **[getAllScreens()](#screengetallscreens)** or **[createVirtualScreen()](#screencreatevirtualscreen)** to obtain a **Screen** instance. +### Attributes + **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name | Type | Readable| Writable| Description | @@ -744,6 +746,7 @@ Before calling any API in **Screen**, you must use **[getAllScreens()](#screenge | supportedModeInfo | Array<[ScreenModeInfo](#screenmodeinfo)> | Yes | No | Mode set supported by the screen. | | activeModeIndex | number | Yes | No | Index of the active screen mode.| | orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | +| sourceMode10+ | [ScreenSourceMode](#screensourcemode10) | Yes | No | Source mode of the screen. | ### setOrientation @@ -997,6 +1000,19 @@ Enumerates the screen orientations. | REVERSE_VERTICAL | 3 | Reverse vertical. | | REVERSE_HORIZONTAL | 4 | Reverse horizontal. | +## ScreenSourceMode10+ + +Enumerates the display content source modes of the screen. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value | Description | +| ------------------ | ---- | -------------------------------- | +| SCREEN_MAIN | 0 | The primary screen is displayed (default).| +| SCREEN_MIRROR | 1 | The mirror is displayed. | +| SCREEN_EXTEND | 2 | The extended screen is displayed. | +| SCREEN_ALONE | 3 | The source is unspecified. | + ## ScreenModeInfo Defines the screen mode information. @@ -1006,6 +1022,6 @@ Defines the screen mode information. | Name | Type| Readable| Writable| Description | | ----------- | -------- | ---- | ---- | -------------------------------------------------- | | id | number | Yes | Yes | Mode ID. The supported mode is determined by the device resolution and refresh rate.| -| width | number | Yes | Yes | Screen width. | -| height | number | Yes | Yes | Screen height. | +| width | number | Yes | Yes | Width of the screen, in pixels. | +| height | number | Yes | Yes | Height of the screen, in pixels. | | refreshRate | number | Yes | Yes | Screen refresh rate. | diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md deleted file mode 100644 index 65a4ac2a29a971ba15f88ea4597189024c2877fd..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-securityLabel.md +++ /dev/null @@ -1,179 +0,0 @@ -# @ohos.securityLabel (Data Label) - -The **secuityLabel** module provides APIs to manage file data security levels, including obtaining and setting file data security levels. - -> **NOTE** -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -```js -import securityLabel from '@ohos.securityLabel'; -``` - -## Usage - -Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox as follows: - -```js -import featureAbility from '@ohos.ability.featureAbility'; -let context = featureAbility.getContext(); -let path = ''; -context.getFilesDir().then((data) => { - path = data; -}) -``` - -## securityLabel.setSecurityLabel - -setSecurityLabel(path:string, type:dataLevel):Promise<void> - -Sets the security label for a file in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | -------------------------------------------- | -| path | string | Yes | File path. | -| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| - -**Return value** - - | Type | Description | - | ------------------- | ---------------- | - | Promise<void> | Promise used to return the result. An empty value will be returned.| - -**Example** - - ```js - securityLabel.setSecurityLabel(path, "s0").then(function(){ - console.info("setSecurityLabel successfully"); - }).catch(function(error){ - console.info("setSecurityLabel failed with error:" + error); - }); - ``` - -## securityLabel.setSecurityLabel - -setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void - -Sets the security label for a file in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | -------------------------------------------- | -| path | string | Yes | File path. | -| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | - -**Example** - - ```js - securityLabel.setSecurityLabel(path, "s0", function(error){ - console.info("setSecurityLabel:" + JSON.stringify(error)); - }); - ``` -## securityLabel.setSecurityLabelSync - -setSecurityLabelSync(path:string, type:dataLevel):void - -Sets the security label for a file in synchronous mode. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | -------------------------------------------- | -| path | string | Yes | File path. | -| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| - -**Example** - -```js -securityLabel.setSecurityLabelSync(path, "s0"); -``` - -## securityLabel.getSecurityLabel - -getSecurityLabel(path:string):Promise<string> - -Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | -------- | - | path | string | Yes | File path.| - -**Return value** - - | Type | Description | - | --------------------- | ------------ | - | Promise<string> | Promise used to return the security label obtained.| - -**Example** - - ```js - securityLabel.getSecurityLabel(path).then(function(type){ - console.log("getSecurityLabel successfully:" + type); - }).catch(function(err){ - console.log("getSecurityLabel failed with error:" + err); - }); - ``` - -## securityLabel.getSecurityLabel - -getSecurityLabel(path:string, callback:AsyncCallback<string>): void - -Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | -------------------------- | - | path | string | Yes | File path. | - | callback | AsyncCallback<string> | Yes | Callback used to return the security label obtained.| - -**Example** - - ```js - securityLabel.getSecurityLabel(path, function(err, type){ - console.log("getSecurityLabel successfully:" + type); - }); - ``` -## securityLabel.getSecurityLabelSync - -getSecurityLabelSync(path:string):string - -Obtains the security label of a file in synchronous mode. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------- | -| path | string | Yes | File path.| - -**Return value** - -| Type | Description | -| ------ | ------------ | -| string | Security label obtained.| - -**Example** - -```js -let result = securityLabel.getSecurityLabelSync(path); -console.log("getSecurityLabel successfully:" + result); -``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 69845e5552e2c21cb49852513e837c7976dcb8b3..987da3a5c044ee43e963df6a1ef731d8a0d07915 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -2876,7 +2876,7 @@ Transforms a rotation vector based on the coordinate system. This API uses an as | Name | Type | Mandatory| Description | | ---------------- | ----------------------------------------- | ---- | ---------------------- | -| inRotationVector | Array<number> | Yes | Rotation matrix. | +| inRotationVector | Array<number> | Yes | Rotation vector. | | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Rotation vector to transform. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being transformed.| @@ -2923,7 +2923,7 @@ Transforms a rotation vector based on the coordinate system. This API uses a pro | Name | Type | Mandatory| Description | | ---------------- | ----------------------------------------- | ---- | ---------------- | -| inRotationVector | Array<number> | Yes | Rotation matrix. | +| inRotationVector | Array<number> | Yes | Rotation vector. | | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Rotation vector to transform.| **Return value** @@ -3179,7 +3179,7 @@ For details about the following error codes, see [Error Codes of sensor.getRotat try { let gravity = [-0.27775216, 0.5351276, 9.788099]; let geomagnetic = [210.87253, -78.6096, -111.44444]; - sensor.getRotationMatrix(gravity, geomagnetic, function (err, data) => { + sensor.getRotationMatrix(gravity, geomagnetic, function (err, data) { if (err) { console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); return; @@ -3477,7 +3477,7 @@ Describes the sensor information. | Name | Type| Readable| Writable| Description | | --------------- | -------- | ---------------------- | ---------------------- | ---------------------- | | sensorName | string | Yes | Yes | Sensor name. | -| venderName | string | Yes | Yes | Vendor of the sensor. | +| vendorName | string | Yes | Yes | Vendor of the sensor. | | firmwareVersion | string | Yes | Yes | Firmware version of the sensor. | | hardwareVersion | string | Yes | Yes | Hardware version of the sensor. | | sensorId | number | Yes | Yes | Sensor type ID. | @@ -3496,9 +3496,9 @@ Describes the acceleration sensor data. It extends from [Response](#response). | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ------------------------------------ | -| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s². | -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s². | -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s². | +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s².| +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s².| +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s².| ## LinearAccelerometerResponse @@ -3510,9 +3510,9 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | -| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s². | -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s². | -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s². | +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s².| +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s².| +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s².| ## AccelerometerUncalibratedResponse @@ -3524,12 +3524,12 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( | Name | Type | Readable| Writable| Description | | ----- | ------ | ---- | ---- | ------------------------------------------------ | -| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s². | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s². | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s². | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s². | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s². | -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s². | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s². | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s². | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s².| +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s². | ## GravityResponse @@ -3541,9 +3541,9 @@ Describes the gravity sensor data. It extends from [Response](#response). | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | -| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s². | -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s². | -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s². | +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s².| +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s².| +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s².| ## OrientationResponse @@ -3831,6 +3831,18 @@ Describes the geographical location. | longitude | number | Yes | Yes | Longitude. | | altitude | number | Yes | Yes | Altitude.| +## LocationOptions + +Describes the geographical location. + +**System capability**: SystemCapability.Sensors.Sensor + +| Name | Type | Readable | Writable | Description | +| --------- | ------ | -------- | -------- | ----------- | +| latitude | number | Yes | Yes | Latitude. | +| longitude | number | Yes | Yes | Longitude. | +| altitude | number | Yes | Yes | Altitude. | + ## sensor.on(deprecated) ### ACCELEROMETER(deprecated) @@ -6231,7 +6243,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo } console.info(JSON.stringify(data)); }) - ``` diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md index 3dec0fa1e2fd325479ac688443e67500d60f570b..5c562892d8f5d5a99423cb79a19478609612aed6 100644 --- a/en/application-dev/reference/apis/js-apis-system-package.md +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -19,11 +19,11 @@ import package from '@system.package'; ## package.hasInstalled(deprecated) > This API is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. -hasInstalled(Object): void +hasInstalled(options: CheckPackageHasInstalledOptions): void Checks whether an application exists, or whether a native application has been installed. -**Required permissions**: ohos.permission.GET_BUNDLE_INFO +**Required permissions**: none **System capability**: SystemCapability.BundleManager.BundleFramework @@ -65,9 +65,9 @@ Checks whether a bundle has been installed. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name| Type| Description| -| --- | --- | ---- | -| result | boolean | The value **true** means that the bundle has been installed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|result | boolean | Yes| The value **true** means that the bundle has been installed, and **false** means the opposite.| ## CheckPackageHasInstalledOptions @@ -75,6 +75,8 @@ Checks whether a bundle has been installed. Defines the options used for checking whether a bundle has been installed. +**System capability**: SystemCapability.BundleManager.BundleFramework + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | bundleName | string | Yes| Bundle name.| diff --git a/en/application-dev/reference/apis/js-apis-system-parameterV9.md b/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md similarity index 98% rename from en/application-dev/reference/apis/js-apis-system-parameterV9.md rename to en/application-dev/reference/apis/js-apis-system-parameterEnhance.md index 97e9b165f31c640c52593ae8d1c8d8969862b8e8..8b4be482d1e6b6b1bae52827c0104387ed16601d 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameterV9.md +++ b/en/application-dev/reference/apis/js-apis-system-parameterEnhance.md @@ -1,10 +1,11 @@ -# SystemParameter (System Parameter) +# @ohos.systemParameterEnhance (System Parameter) The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs provided by this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getters and modify the values through setters. For details about the system parameter design principles and definitions, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). > **NOTE** +> > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs provided by this module are system APIs. > - Third-party applications cannot use the APIs provided by this module, because system parameters each require specific discretionary access control (DAC) and mandatory access control (MAC) permissions. @@ -12,7 +13,7 @@ For details about the system parameter design principles and definitions, see ## Modules to Import ```ts -import systemparameter from '@ohos.systemParameterV9' +import systemparameter from '@ohos.systemParameterEnhance' ``` ## systemparameter.getSync diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index c8e93e0f8b84dafe4e52ce939d2cad5012762f36..ebeafe6fb89160110767d14fe06ef6ccf2365550 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -4,7 +4,8 @@ The **systemTime** module provides system time and time zone features. You can u > **NOTE** > -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module are deprecated since API version 9. You are advised to use the APIs of the [@ohos.systemDateTime (System Time and Time Zone)](js-apis-system-date-time.md) module. +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -107,10 +108,6 @@ getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -150,10 +147,6 @@ getCurrentTime(callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime-1). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -192,10 +185,6 @@ getCurrentTime(isNano?: boolean): Promise<number> Obtains the time elapsed since the Unix epoch. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime-2). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -238,10 +227,6 @@ getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -281,10 +266,6 @@ getRealActiveTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime-1). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -323,10 +304,6 @@ getRealActiveTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime-2). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -369,10 +346,6 @@ getRealTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, including the deep sleep time. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -412,10 +385,6 @@ getRealTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, including the deep sleep time. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime-1). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -454,10 +423,6 @@ getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system startup, including the deep sleep time. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime-2). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -587,10 +552,6 @@ getDate(callback: AsyncCallback<Date>): void Obtains the current system date. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getDate](./js-apis-system-date-time.md#systemdatetimegetdate). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -629,10 +590,6 @@ getDate(): Promise<Date> Obtains the current system date. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getDate](./js-apis-system-date-time.md#systemdatetimegetdate-1). - **System capability**: SystemCapability.MiscServices.Time **Return value** @@ -754,10 +711,6 @@ getTimezone(callback: AsyncCallback<string>): void Obtains the system time zone. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getTimezone](./js-apis-system-date-time.md#systemdatetimegettimezone). - **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -796,10 +749,6 @@ getTimezone(): Promise<string> Obtains the system time zone. This API uses a promise to return the result. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getTimezone](./js-apis-system-date-time.md#systemdatetimegettimezone-1). - **System capability**: SystemCapability.MiscServices.Time **Return value** diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 6657eb3e558732fa50af4c7bb82f7b26e3457433..dca4d71f55fded097f6d9521b97540bf5eefd433 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,4 +1,4 @@ -# @ohos.wantAgent (wantAgent) +# @ohos.wantAgent (WantAgent) The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. @@ -16,7 +16,7 @@ import WantAgent from '@ohos.wantAgent'; getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void -Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. +Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. If the creation fails, a null **WantAgent** object is returned. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -75,7 +75,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); getWantAgent(info: WantAgentInfo): Promise\ -Obtains a **WantAgent** object. This API uses a promise to return the result. +Obtains a **WantAgent** object. This API uses a promise to return the result. If the creation fails, a null **WantAgent** object is returned. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -160,8 +160,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + // getBundleName callback + function getBundleNameCallback(err, data) { + console.info('==========================>getBundleNameCallback=======================>'); + } + WantAgent.getBundleName(wantAgent, getBundleNameCallback); } // WantAgentInfo object let wantAgentInfo = { @@ -192,12 +199,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getBundleName callback -function getBundleNameCallback(err, data) { - console.info('==========================>getBundleNameCallback=======================>'); -} -WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -261,10 +262,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.getBundleName(wantAgent).then((data) => { - console.info('==========================>getBundleNameCallback=======================>'); + if (wantAgent) { + WantAgent.getBundleName(wantAgent).then((data) => { + console.info('==========================>getBundleNameCallback=======================>'); + }); + } }); ``` @@ -300,8 +302,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + // getUid callback + function getUidCallback(err, data) { + console.info('==========================>getUidCallback=======================>'); + } + WantAgent.getUid(wantAgent, getUidCallback); } // WantAgentInfo object let wantAgentInfo = { @@ -332,12 +341,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getUid callback -function getUidCallback(err, data) { - console.info('==========================>getUidCallback=======================>'); -} -WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -402,10 +405,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.getUid(wantAgent).then((data) => { - console.info('==========================>getUidCallback=======================>'); + if (wantAgent) { + WantAgent.getUid(wantAgent).then((data) => { + console.info('==========================>getUidCallback=======================>'); + }); + } }); ``` @@ -440,8 +444,15 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + // cancel callback + function cancelCallback(err, data) { + console.info('==========================>cancelCallback=======================>'); + } + WantAgent.cancel(wantAgent, cancelCallback); } // WantAgentInfo object let wantAgentInfo = { @@ -472,12 +483,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// cancel callback -function cancelCallback(err, data) { - console.info('==========================>cancelCallback=======================>'); -} -WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -542,10 +547,11 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; -}); - -WantAgent.cancel(wantAgent).then((data) => { - console.info('==========================>cancelCallback=======================>'); + if (wantAgent) { + WantAgent.cancel(wantAgent).then((data) => { + console.info('==========================>cancelCallback=======================>'); + }); + } }); ``` @@ -582,8 +588,19 @@ function getWantAgentCallback(err, data) { if (err.code == 0) { wantAgent = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; + } + + // trigger callback + function triggerCallback(data) { + console.info('==========================>triggerCallback=======================>'); + } + + var triggerInfo = { + code:0 } + WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) } // WantAgentInfo object let wantAgentInfo = { @@ -614,16 +631,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// trigger callback -function triggerCallback(data) { - console.info('==========================>triggerCallback=======================>'); -} - -var triggerInfo = { - code:0 -} -WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) ``` @@ -661,8 +668,15 @@ function getWantAgentCallback(err, data) { wantAgent1 = data; wantAgent2 = data; } else { - console.info('----getWantAgent failed!----'); + console.error('getWantAgent failed, error: ' + JSON.stringify(err)); + return; } + + // equal callback + function equalCallback(err, data) { + console.info('==========================>equalCallback=======================>'); + } + WantAgent.equal(wantAgent1, wantAgent2, equalCallback) } // WantAgentInfo object let wantAgentInfo = { @@ -693,12 +707,6 @@ let wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// equal callback -function equalCallback(err, data) { - console.info('==========================>equalCallback=======================>'); -} -WantAgent.equal(wantAgent1, wantAgent2, equalCallback) ``` @@ -766,6 +774,11 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; + if (data) { + WantAgent.equal(wantAgent1, wantAgent2).then((data) => { + console.info('==========================>equalCallback=======================>'); + }); + } }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { @@ -827,11 +840,12 @@ let wantAgentInfo = { WantAgent.getWantAgent(wantAgentInfo).then((data) => { console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + if (data) { + WantAgent.getOperationType(wantAgent, (OperationType) => { + console.log('----------- getOperationType ----------, OperationType: ' + OperationType); + }) + } }); - -WantAgent.getOperationType(wantAgent, (OperationType) => { - console.log('----------- getOperationType ----------, OperationType: ' + OperationType); -}) ``` ## WantAgent.getOperationType9+ @@ -901,7 +915,6 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { }); ``` - ## WantAgentFlags **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -940,5 +953,5 @@ WantAgent.getWantAgent(wantAgentInfo).then((data) => { | info | WantAgent | Yes | A triggered **WantAgent** object. | | want | Want | Yes | An existing triggered **want**. | | finalCode | number | Yes | Request code that triggers the **WantAgent** object.| -| finalData | string | No | Final data collected by the common event. | +| finalData | string | Yes | Final data collected by the common event. | | extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index 455416ed7c1290971e5a797766d35c52ed08b537..6b45cedd701e6e2a287cc8cdc80055e3f95e0caf 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -9,11 +9,13 @@ This module provides WebGL APIs that correspond to the OpenGL ES 2.0 feature set > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > WebGL complies with the OpenGL protocol and does not support multi-thread calling. +> +> This module can be used only in the JavaScript-compatible web-like development paradigm. ## Invoking Method -Create a **** component in the HML file. The following is an example: +Create a **\** component in the HML file. The following is an example: ```html @@ -24,7 +26,7 @@ Create a **** component in the HML file. The following is an example: ``` -Obtain the **** component instance in the JS file. The following is an example: +Obtain the **\** component instance in the JS file. The following is an example: ```js diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index dc19039007c1f8207e2dd3ac026c67bdac169d9f..7a55f214f16fad1cf35faebd459e8bac7dfd1e25 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -9,11 +9,13 @@ This module provides WebGL APIs that correspond to the OpenGL ES 3.0 feature set > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > WebGL2 complies with the OpenGL protocol and does not support multi-thread calling. +> +> This module can be used only in the JavaScript-compatible web-like development paradigm. ## Invoking Method -Create a **** component in the HML file. The following is an example: +Create a **\** component in the HML file. The following is an example: ```html @@ -24,7 +26,7 @@ Create a **** component in the HML file. The following is an example: ``` -Obtain the **** component instance in the JS file. The following is an example: +Obtain the **\** component instance in the JS file. The following is an example: ```js diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md index 46c43be00e3df1ec2f9cc56ea2f0f834a0c6cc12..c4b50a6993017a534e846fc2edb761ae0f74e12d 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManager.md +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -1,4 +1,4 @@ -# WLAN +# @ohos.wifiManager (WLAN) The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. > **NOTE** @@ -30,6 +30,14 @@ Enables WLAN. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| + ## wifi.disableWifi9+ @@ -49,6 +57,13 @@ Disables WLAN. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.isWifiActive9+ @@ -66,6 +81,13 @@ Checks whether WLAN is enabled. | -------- | -------- | | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.scan9+ @@ -83,6 +105,13 @@ Starts a scan for WLAN. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getScanResults9+ @@ -100,6 +129,13 @@ Obtains the scan result. This API uses a promise to return the result. | -------- | -------- | | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getScanResults9+ @@ -117,6 +153,14 @@ Obtains the scan result. This API uses an asynchronous callback to return the re | -------- | -------- | -------- | -------- | | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| + **Example** ```js import wifi from '@ohos.wifi'; @@ -250,6 +294,13 @@ Obtains the scan result. This API returns the result synchronously. | -------- | -------- | |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.addDeviceConfig9+ @@ -275,6 +326,14 @@ Adds network configuration. This API uses a promise to return the result. | -------- | -------- | | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| + ## WifiDeviceConfig9+ Represents the WLAN configuration. @@ -417,6 +476,13 @@ Adds network configuration. This API uses an asynchronous callback to return the | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.addCandidateConfig9+ @@ -440,6 +506,13 @@ Adds the configuration of a candidate network. This API uses a promise to return | -------- | -------- | | Promise<number> | Promise used to return the network configuration ID.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.addCandidateConfig9+ @@ -458,6 +531,13 @@ Adds the configuration of a candidate network. This API uses an asynchronous cal | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeCandidateConfig9+ @@ -481,6 +561,13 @@ Removes the configuration of a candidate network. This API uses a promise to ret | -------- | -------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeCandidateConfig9+ @@ -499,6 +586,13 @@ Removes the configuration of a candidate network. This API uses an asynchronous | networkId | number | Yes| ID of the network configuration to remove.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getCandidateConfigs9+ @@ -516,6 +610,13 @@ Obtains candidate network configuration. | -------- | -------- | |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.connectToCandidateConfig9+ @@ -533,6 +634,14 @@ Connects to a candidate network. | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the candidate network configuration.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.connectToNetwork9+ @@ -552,12 +661,14 @@ Connects to the specified network. | -------- | -------- | -------- | -------- | | networkId | number | Yes| Network configuration ID.| -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.connectToDevice9+ @@ -578,12 +689,14 @@ Connects to the specified network. | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.disconnect9+ @@ -598,12 +711,13 @@ Disconnects the network. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getSignalLevel9+ @@ -628,6 +742,13 @@ Obtains the WLAN signal level. | -------- | -------- | | number | Signal level obtained. The value range is [0, 4].| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getLinkedInfo9+ @@ -645,6 +766,14 @@ Obtains WLAN connection information. This API uses a promise to return the resul | -------- | -------- | | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.getLinkedInfo9+ @@ -662,6 +791,15 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| + **Example** ```js import wifi from '@ohos.wifi'; @@ -766,6 +904,13 @@ Checks whether the WLAN is connected. | -------- | -------- | | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getSupportedFeatures9+ @@ -794,12 +939,19 @@ Obtains the features supported by this device. | 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| | 0x0008 | Wi-Fi Direct| | 0x0010 | SoftAP| -| 0x0040 | Wi-Fi AWare| +| 0x0040 | Wi-Fi Aware| | 0x8000 | WLAN AP/STA concurrency| | 0x8000000 | WPA3 Personal (WPA-3 SAE)| | 0x10000000 | WPA3-Enterprise Suite B | | 0x20000000 | Enhanced open feature| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2401000 | Operation failed.| ## wifi.isFeatureSupported9+ @@ -824,6 +976,13 @@ Checks whether the device supports the specified WLAN feature. | -------- | -------- | | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2401000 | Operation failed.| ## wifi.getDeviceMacAddress9+ @@ -843,6 +1002,13 @@ Obtains the device MAC address. | -------- | -------- | | string[] | MAC address obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.getIpInfo9+ @@ -860,6 +1026,13 @@ Obtains IP information. | -------- | -------- | | [IpInfo](#ipinfo9) | IP information obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## IpInfo9+ @@ -894,6 +1067,13 @@ Obtains the country code. | -------- | -------- | | string | Country code obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2401000 | Operation failed.| ## wifi.reassociate9+ @@ -907,12 +1087,14 @@ Re-associates with the network. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.reconnect9+ @@ -926,12 +1108,14 @@ Reconnects to the network. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| +| 2501001 | Wifi is closed.| ## wifi.getDeviceConfigs9+ @@ -951,6 +1135,13 @@ Obtains network configuration. | -------- | -------- | |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.updateNetwork9+ @@ -968,7 +1159,7 @@ Updates network configuration. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| **Return value** @@ -976,6 +1167,13 @@ Updates network configuration. | -------- | -------- | | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.disableNetwork9+ @@ -995,12 +1193,13 @@ Disables network configuration. | -------- | -------- | -------- | -------- | | netId | number | Yes| ID of the network configuration to disable.| -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeAllNetwork9+ @@ -1014,12 +1213,13 @@ Removes the configuration of all networks. **System capability**: SystemCapability.Communication.WiFi.STA -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.removeDevice9+ @@ -1039,12 +1239,13 @@ Removes the specified network configuration. | -------- | -------- | -------- | -------- | | id | number | Yes| ID of the network configuration to remove.| -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.enableHotspot9+ @@ -1058,12 +1259,13 @@ Enables this hotspot. **System capability**: SystemCapability.Communication.WiFi.AP.Core -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.disableHotspot9+ @@ -1077,12 +1279,13 @@ Disables this hotspot. **System capability**: SystemCapability.Communication.WiFi.AP.Core -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.isHotspotDualBandSupported9+ @@ -1100,8 +1303,15 @@ Checks whether the hotspot supports dual band. | **Type**| **Description**| | -------- | -------- | - | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + | boolean | Returns **true** if the hotspot supports dual band; returns **false** otherwise.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.isHotspotActive9+ @@ -1121,6 +1331,13 @@ Checks whether this hotspot is active. | -------- | -------- | | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.setHotspotConfig9+ @@ -1140,12 +1357,13 @@ Sets hotspot configuration. | -------- | -------- | -------- | -------- | | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## HotspotConfig9+ @@ -1168,7 +1386,7 @@ Represents the hotspot configuration. getHotspotConfig(): HotspotConfig -obtains hotspot configuration. +Obtains hotspot configuration. **System API**: This is a system API. @@ -1182,6 +1400,13 @@ obtains hotspot configuration. | -------- | -------- | | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.getStations9+ @@ -1201,6 +1426,13 @@ Obtains information about the connected stations. | -------- | -------- | |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## StationInfo9+ @@ -1233,7 +1465,13 @@ Obtains P2P link information. This API uses a promise to return the result. | -------- | -------- | | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2pLinkedInfo9+ @@ -1293,6 +1531,13 @@ Obtains the current P2P group information. This API uses a promise to return the | -------- | -------- | | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getCurrentGroup9+ @@ -1310,6 +1555,13 @@ Obtains the current P2P group information. This API uses an asynchronous callbac | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pPeerDevices9+ @@ -1327,6 +1579,13 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r | -------- | -------- | | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pPeerDevices9+ @@ -1344,6 +1603,13 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2pDevice9+ @@ -1391,6 +1657,13 @@ Obtains the local device information in the P2P connection. This API uses a prom | -------- | -------- | | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pLocalDevice9+ @@ -1425,12 +1698,13 @@ Creates a P2P group. | -------- | -------- | -------- | -------- | | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2PConfig9+ @@ -1470,12 +1744,13 @@ Removes this P2P group. **System capability**: SystemCapability.Communication.WiFi.P2P -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.p2pConnect9+ @@ -1494,12 +1769,13 @@ Sets up a P2P connection. | -------- | -------- | -------- | -------- | | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| **Example** ```js @@ -1578,12 +1854,13 @@ Cancels this P2P connection. **System capability**: SystemCapability.Communication.WiFi.P2P -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.startDiscoverDevices9+ @@ -1595,12 +1872,13 @@ Starts to discover devices. **System capability**: SystemCapability.Communication.WiFi.P2P -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.stopDiscoverDevices9+ @@ -1612,12 +1890,13 @@ Stops discovering devices. **System capability**: SystemCapability.Communication.WiFi.P2P -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.deletePersistentGroup9+ @@ -1638,12 +1917,13 @@ Deletes a persistent group. | -------- | -------- | -------- | -------- | | netId | number | Yes| ID of the group to delete.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.getP2pGroups9+ @@ -1663,6 +1943,13 @@ Obtains information about all P2P groups. This API uses a promise to return the | -------- | -------- | | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## WifiP2pGroupInfo9+ @@ -1701,6 +1988,13 @@ Obtains information about all P2P groups. This API uses an asynchronous callback | -------- | -------- | -------- | -------- | | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.setDeviceName9+ @@ -1720,12 +2014,13 @@ Sets the device name. | -------- | -------- | -------- | -------- | | devName | string | Yes| Device name to set.| -**Return value** +**Error codes** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('wifiStateChange')9+ @@ -1744,6 +2039,14 @@ Registers the WLAN state change events. | type | string | Yes| Event type. The value is **wifiStateChange**.| | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| + **WLAN states** | **Value**| **Description**| @@ -1769,7 +2072,15 @@ Unregisters the WLAN state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| - | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| **Example** ```js @@ -1811,6 +2122,13 @@ Registers the WLAN connection state change events. | 0 | Disconnected.| | 1 | Connected.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.off('wifiConnectionChange')9+ @@ -1827,8 +2145,15 @@ Unregisters the WLAN connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the WLAN connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.on('wifiScanStateChange')9+ @@ -1854,6 +2179,13 @@ Registers the WLAN scan state change events. | 0 | Scan failed.| | 1 | Scan successful.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.off('wifiScanStateChange')9+ @@ -1870,8 +2202,15 @@ Unregisters the WLAN scan state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<number> | No| Callback for the WLAN scan state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.on('wifiRssiChange')9+ @@ -1890,6 +2229,13 @@ Registers the RSSI change events. | type | string | Yes| Event type. The value is **wifiRssiChange**.| | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.off('wifiRssiChange')9+ @@ -1906,8 +2252,15 @@ Unregisters the RSSI change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the RSSI change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2501000 | Operation failed.| ## wifi.on('hotspotStateChange')9+ @@ -1935,6 +2288,13 @@ Registers the hotspot state change events. | 2 | Activating| | 3 | Deactivating| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.off('hotspotStateChange')9+ @@ -1951,8 +2311,15 @@ Unregisters the hotspot state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the hotspot state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2601000 | Operation failed.| ## wifi.on('p2pStateChange')9+ @@ -1981,6 +2348,14 @@ Registers the P2P state change events. | 4 | Closing| | 5 | Closed| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| + ## wifi.off('p2pStateChange')9+ off(type: "p2pStateChange", callback?: Callback<number>): void @@ -1996,8 +2371,15 @@ Unregisters the P2P state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the P2P state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pConnectionChange')9+ @@ -2016,6 +2398,13 @@ Registers the P2P connection state change events. | type | string | Yes| Event type. The value is **p2pConnectionChange**.| | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pConnectionChange')9+ @@ -2032,8 +2421,15 @@ Unregisters the P2P connection state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| - | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pDeviceChange')9+ @@ -2052,6 +2448,13 @@ Registers the P2P device state change events. | type | string | Yes| Event type. The value is **p2pDeviceChange**.| | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pDeviceChange')9+ @@ -2068,8 +2471,15 @@ Unregisters the P2P device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pPeerDeviceChange')9+ @@ -2088,6 +2498,13 @@ Registers the P2P peer device state change events. | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pPeerDeviceChange')9+ @@ -2104,8 +2521,15 @@ Unregisters the P2P peer device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the P2P peer device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pPersistentGroupChange')9+ @@ -2124,6 +2548,13 @@ Registers the P2P persistent group state change events. | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pPersistentGroupChange')9+ @@ -2140,8 +2571,15 @@ Unregisters the P2P persistent group state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| - | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<void> | No| Callback for the P2P persistent group state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.on('p2pDiscoveryChange')9+ @@ -2167,6 +2605,13 @@ Registers the P2P device discovery state change events. | 0 | Initial state.| | 1 | Discovered.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| ## wifi.off('p2pDiscoveryChange')9+ @@ -2183,4 +2628,12 @@ Unregisters the P2P device discovery state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback for the P2P device discovery state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2801000 | Operation failed.| diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md index 656fa873965ceceb94e2e675380ad72577017a33..852b58547ddaf7b5c6eac648016d400ed13f35f9 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -1,8 +1,7 @@ -# WLAN Extension Interface +# @ohos.wifiManagerExt (WLAN Extension Interface) This **wifiext** module provides WLAN extension interfaces for non-universal products. > **NOTE** -> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -23,12 +22,13 @@ Enables the WLAN hotspot. **System capability**: SystemCapability.Communication.WiFi.AP.Extension -**Return value** +**Error codes** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.disableHotspot @@ -40,12 +40,13 @@ Disables the WLAN hotspot. **System capability**: SystemCapability.Communication.WiFi.AP.Extension -**Return value** +**Error codes** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). +| **Type**| **Description**| + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.getSupportedPowerModel @@ -59,10 +60,17 @@ Obtains the supported power models. This API uses a promise to return the result **Return value** -| Type| Description| -| -------- | -------- | -| Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2701000 | Operation failed.| ## PowerModel @@ -89,10 +97,17 @@ Obtains the supported power models. This API uses an asynchronous callback to re **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.getPowerModel @@ -106,10 +121,17 @@ Obtains the power model. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#powermodel)> | Promise used to return the power models obtained.| + +**Error codes** +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.getPowerModel @@ -123,16 +145,23 @@ Obtains the power model. This API uses an asynchronous callback to return the re **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). + +| **Type**| **Description**| + | -------- | -------- | +| 2701000 | Operation failed.| ## wifiext.setPowerModel setPowerModel(model: PowerModel) : boolean; -Sets the power model. + Sets the power model. **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT @@ -140,12 +169,14 @@ Sets the power model. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| model | [PowerModel](#powermodel) | Yes| Power model to set.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | [PowerModel](#powermodel) | Yes| Power model to set.| -**Return value** +**Error codes** + +For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). | **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | -------- | -------- | +| 2701000 | Operation failed.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 9f3a86e1a616d1fce7d3a2f732351b90f3eb2785..f8a8d90d0e6eea8ad7a95cb49fe873c7a82d41a5 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -188,10 +188,10 @@ Describes the rectangular area of the window. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | ------------------ | -| left | number | Yes | Yes | Left boundary of the rectangle.| -| top | number | Yes | Yes | Top boundary of the rectangle.| -| width | number | Yes | Yes | Width of the rectangle. | -| height | number | Yes | Yes | Height of the rectangle. | +| left | number | Yes | Yes | Left boundary of the rectangle, in pixels.| +| top | number | Yes | Yes | Top boundary of the rectangle, in pixels.| +| width | number | Yes | Yes | Width of the rectangle, in pixels.| +| height | number | Yes | Yes | Height of the rectangle, in pixels.| ## AvoidArea7+ @@ -215,8 +215,8 @@ Describes the window size. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | ---------- | -| width | number | Yes | Yes | Window width.| -| height | number | Yes | Yes | Window height.| +| width | number | Yes | Yes | Window width, in pixels.| +| height | number | Yes | Yes | Window height, in pixels.| ## WindowProperties @@ -296,6 +296,21 @@ Describes the translation parameters. | y | number | No | Yes | Distance to translate along the y-axis. The default value is **0.0**.| | z | number | No | Yes | Distance to translate along the z-axis. The default value is **0.0**.| +## WindowEventType10+ + +Enumerates the window lifecycle states. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value| Description | +| ---------- | ------ | ---------- | +| WINDOW_SHOWN | 1 | The window is running in the foreground.| +| WINDOW_ACTIVE | 2 | The window gains focus.| +| WINDOW_INACTIVE | 3 | The window loses focus.| +| WINDOW_HIDDEN | 4 | The window is running in the background.| + ## window.createWindow9+ createWindow(config: Configuration, callback: AsyncCallback<Window>): void @@ -824,7 +839,7 @@ create(id: string, type: WindowType, callback: AsyncCallback<Window>): voi Creates a subwindow. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9) instead. **Model restriction**: This API can be used only in the FA model. @@ -860,7 +875,7 @@ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9-1) instead. **Model restriction**: This API can be used only in the FA model. @@ -900,7 +915,7 @@ create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback&l Creates a system window. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -936,7 +951,7 @@ create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> Creates a system window. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -975,7 +990,7 @@ find(id: string, callback: AsyncCallback<Window>): void Finds a window based on the ID. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1008,7 +1023,7 @@ find(id: string): Promise<Window> Finds a window based on the ID. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1045,7 +1060,7 @@ getTopWindow(callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. **Model restriction**: This API can be used only in the FA model. @@ -1079,7 +1094,7 @@ getTopWindow(): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. **Model restriction**: This API can be used only in the FA model. @@ -1112,7 +1127,7 @@ getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. > **NOTE** -> +> > This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1145,7 +1160,7 @@ getTopWindow(ctx: BaseContext): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. > **NOTE** -> +> > This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2735,7 +2750,7 @@ try { } ``` -### on('dialogTargetTouch')9+ +### on('dialogTargetTouch')10+ on(type: 'dialogTargetTouch', callback: Callback<void>): void @@ -2762,7 +2777,7 @@ try { } ``` -### off('dialogTargetTouch')9+ +### off('dialogTargetTouch')10+ off(type: 'dialogTargetTouch', callback?: Callback<void>): void @@ -2787,6 +2802,62 @@ try { } ``` +### on('windowEvent')10+ + +on(type: 'windowEvent', callback: Callback<WindowEventType>): void + +Enables listening for window lifecycle changes. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowEvent'**, indicating the window lifecycle change event.| +| callback | Callback<[WindowEventType](#windoweventtype10)> | Yes | Callback used to return the window lifecycle state. | + +**Example** + +```js +try { + windowClass.on('windowEvent', (data) => { + console.info('Window event happened. Event:' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +} +``` + +### off('windowEvent')10+ + +off(type: 'windowEvent', callback?: Callback<WindowEventType >): void + +Disables listening for window lifecycle changes. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowEvent'**, indicating the window lifecycle change event.| +| callback | Callback<[WindowEventType](#windoweventtype10)> | No | Callback used to return the window lifecycle state. | + +**Example** + +```js +try { + windowClass.off('windowEvent'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +} +``` + ### bindDialogTarget9+ bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>, callback: AsyncCallback<void>): void @@ -2927,6 +2998,154 @@ try { } ``` +### bindDialogTarget9+ + +bindDialogTarget(requestInfo: dialogRequest.RequestInfo, deathCallback: Callback<void>, callback: AsyncCallback<void>): void + +Binds the modal window to the target window, and adds a callback to listen for modal window destruction events. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| requestInfo | [dialogRequest.RequestInfo](js-apis-app-ability-dialogRequest.md#requestinfo) | Yes | **RequestInfo** of the target window.| +| deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; +import rpc from '@ohos.rpc'; +import dialogRequest from '@ohos.app.ability.dialogRequest'; +import window from '@ohos.window'; + +export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info('onCreate'); + } + + onRequest(want, startId) { + console.info('onRequest'); + try { + let requestInfo = dialogRequest.getRequestInfo(want) + windowClass.bindDialogTarget(requestInfo, () => { + console.info('Dialog Window Need Destroy.'); + }, (err) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target.'); + }); + } catch(err) { + console.error('getRequestInfo err = ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info('onConnect'); + } + + onDisconnect(want) { + console.info('onDisconnect'); + } + + onDestroy() { + console.info('onDestroy'); + } +} +``` + +### bindDialogTarget9+ + +bindDialogTarget(requestInfo: dialogRequest.RequestInfo, deathCallback: Callback<void>): Promise<void> + +Binds the modal window to the target window, and adds a callback to listen for modal window destruction events. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| requestInfo | [dialogRequest.RequestInfo](js-apis-app-ability-dialogRequest.md#requestinfo) | Yes | **RequestInfo** of the target window.| +| deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; +import rpc from '@ohos.rpc'; +import dialogRequest from '@ohos.app.ability.dialogRequest'; +import window from '@ohos.window'; + +export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info('onCreate'); + } + + onRequest(want, startId) { + console.info('onRequest'); + try { + let requestInfo = dialogRequest.getRequestInfo(want) + let promise = windowClass.bindDialogTarget(requestInfo, () => { + console.info('Dialog Window Need Destroy.'); + }); + promise.then(()=> { + console.info('Succeeded in binding dialog target.'); + }).catch((err)=>{ + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + }); + } catch(err) { + console.error('getRequestInfo err = ' + JSON.stringify(err)) + } + } + + onConnect(want) { + console.info('onConnect'); + } + + onDisconnect(want) { + console.info('onDisconnect'); + } + + onDestroy() { + console.info('onDestroy'); + } +} +``` + ### isWindowSupportWideGamut9+ isWindowSupportWideGamut(callback: AsyncCallback<boolean>): void @@ -3116,7 +3335,7 @@ Sets the background color for this window. In the stage model, this API must be | Name| Type| Mandatory| Description| | ----- | ------ | -- | ----------------------------------------------------------------------- | -| color | string | Yes| Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| +| color | string | Yes| Background color to set. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| **Error codes** @@ -3994,7 +4213,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { playMode: PlayMode.Normal // Animation playback mode. onFinish: ()=> { context.completeTransition(true) - } + } }, () => { let obj : window.TranslateOptions = { x : 100.0, @@ -4138,7 +4357,7 @@ Sets the shadow for the window borders. | Name | Type | Mandatory | Description | | ------- | ------ | --------- | ------------------------------------------------------------ | | radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value **0** means that the shadow is disabled for the window borders. | -| color | string | No | Color of the shadow. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| color | string | No | Color of the shadow. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | | offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | | offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | @@ -4198,6 +4417,260 @@ try { ``` +### raiseToAppTop10+ + +raiseToAppTop(callback: AsyncCallback<void>): void + +Raises the application subwindow to the top layer of the application. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | --------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | +| 1300009 | The parent window is invalid. | + +**Example** + +```js +windowClass.raiseToAppTop((err) => { + if (err.code) { + console.error('Failed to raise the window to app top. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in raising the window to app top.'); +}); + +``` + +### raiseToAppTop10+ + +raiseToAppTop(): Promise<void> + +Raises the application subwindow to the top layer of the application. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | --------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | +| 1300009 | The parent window is invalid. | + +**Example** + +```js +let promise = windowClass.raiseToAppTop(); +promise.then(()=> { + console.info('Succeeded in raising the window to app top.'); +}).catch((err)=>{ + console.error('Failed to raise the window to app top. Cause: ' + JSON.stringify(err)); +}); + +``` + +### setAspectRatio10+ + +setAspectRatio(ratio: number): Promise<void> + +Sets the aspect ratio of the window content layout. This API uses a promise to return the result. + +This API is available only for the main window of the application. The aspect ratio will be saved permanently and takes effect even after the application is closed or the device is restarted. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | --------- | ------------------------------------------------------------ | +| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value must be greater than 0. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + let ratio = 1.0; + let promise = windowClass.setAspectRatio(ratio); + promise.then(()=> { + console.info('Succeeded in setting aspect ratio of window.'); + }).catch((err)=>{ + console.error('Failed to set the aspect ratio of window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} + +``` + +### setAspectRatio10+ + +setAspectRatio(ratio: number, callback: AsyncCallback<void>): void + +Sets the aspect ratio of the window content layout. This API uses an asynchronous callback to return the result. + +This API is available only for the main window of the application. The aspect ratio will be saved permanently and takes effect even after the application is closed or the device is restarted. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| ratio | number | Yes | Aspect ratio of the window content layout except border decoration. The value must be greater than 0. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + let ratio = 1.0; + windowClass.setAspectRatio(ratio, (err) => { + if (err.code) { + console.error('Failed to set the aspect ratio of window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the aspect ratio of window.'); + }); +} catch (exception) { + console.error('Failed to set the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} + +``` + +### resetAspectRatio10+ + +resetAspectRatio(): Promise<void> + +Resets the aspect ratio of the window content layout. This API uses a promise to return the result. + +This API is available only for the main window of the application. After this API is called, the persistently stored aspect ratio is cleared. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + let promise = windowClass.resetAspectRatio(); + promise.then(()=> { + console.info('Succeeded in resetting aspect ratio of window.'); + }).catch((err)=>{ + console.error('Failed to reset the aspect ratio of window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to reset the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} + +``` + +### resetAspectRatio10+ + +resetAspectRatio(callback: AsyncCallback<void>): void + +Resets the aspect ratio of the window content layout. This API uses an asynchronous callback to return the result. + +This API is available only for the main window of the application. After this API is called, the persistently stored aspect ratio is cleared. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.resetAspectRatio((err) => { + if (err.code) { + console.error('Failed to reset the aspect ratio of window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in resetting aspect ratio of window.'); + }); +} catch (exception) { + console.error('Failed to reset the aspect ratio of window. Cause: ' + JSON.stringify(exception)); +} + +``` + ### show(deprecated) show(callback: AsyncCallback<void>): void @@ -5368,7 +5841,7 @@ Sets the background color for this window. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| color | string | Yes | Background color to set. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5401,7 +5874,7 @@ Sets the background color for this window. This API uses a promise to return the | Name | Type | Mandatory | Description | | ----- | ------ | --------- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| color | string | Yes | Background color to set. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | **Return value** @@ -5927,7 +6400,7 @@ Describes the lifecycle of a window stage. Implements a window manager, which manages each basic window unit, that is, [Window](#window) instance. -Before calling any of the following APIs, you must use [onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate) to create a **WindowStage** instance. +Before calling any of the following APIs, you must use [onWindowStageCreate()](js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) to create a **WindowStage** instance. ### getMainWindow9+ @@ -6726,7 +7199,7 @@ controller.animationForShown = (context : window.TransitionContext) => { playMode: PlayMode.Normal // Animation playback mode. onFinish: ()=> { context.completeTransition(true) - } + } }, () => { let obj : window.TranslateOptions = { x : 100.0, @@ -6739,7 +7212,6 @@ controller.animationForShown = (context : window.TransitionContext) => { ); console.info('complete transition end'); }; - ``` ### animationForHidden9+ @@ -6773,7 +7245,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { playMode: PlayMode.Normal // Animation playback mode. onFinish: ()=> { context.completeTransition(true) - } + } }, () => { let obj : window.TranslateOptions = { x : 100.0, diff --git a/en/application-dev/reference/arkui-js/js-components-common-events.md b/en/application-dev/reference/arkui-js/js-components-common-events.md index 8461a469536052368d330ad2ad5574be941f34b5..3dd49f1812d39348f14e5e332cfba1f29fe26973 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-events.md +++ b/en/application-dev/reference/arkui-js/js-components-common-events.md @@ -99,6 +99,8 @@ Different from private events, universal events can be bound to most components. When a component triggers an event, the event callback receives an event object by default. You can obtain the corresponding information through the event object. + + | Attribute | Type | Description | | -------------------- | ------ | ---------------------------------------- | | dataSet6+ | Object | Custom attribute set defined through [data-*](../arkui-js/js-components-common-attributes.md).| @@ -241,32 +243,38 @@ Sets a custom drag image. **Example** ```js -createPixelMap() { - let color = new ArrayBuffer(4*96*96); - var buffer = new Uint8Array(color); - for (var i = 0; i < buffer.length; i++) { - buffer[i] = (i + 1) % 255; - } - let opts = { - alphaType:0, - editable:true, - pixelFormat:4, - scaleMode:1, - size:{height:96,width:96} - } - const promise = image.createPixelMap(color,opts); - promise.then((data)=> { - console.error('-create pixmap has info message:' + JSON.stringify(data)); - this.pixelMap = data; - this.pixelMapReader = data; - }) -}, +import image from '@ohos.multimedia.image'; -onInit() { - this.createPixelMap -}, - -dragStart(e) { - e.dataTransfer.setDragImage(this.pixelMapReader, 50, 50); +export default { + createPixelMap() { + let color = new ArrayBuffer(4 * 96 * 96); + var buffer = new Uint8Array(color); + for (var i = 0; i < buffer.length; i++) { + buffer[i] = (i + 1) % 255; + } + let opts = { + alphaType: 0, + editable: true, + pixelFormat: 4, + scaleMode: 1, + size: { + height: 96, width: 96 + } + } + const promise = image.createPixelMap(color, opts); + promise.then((data) => { + console.error('-create pixmap has info message:' + JSON.stringify(data)); + this.pixelMap = data; + this.pixelMapReader = data; + }) + }, + + onInit() { + this.createPixelMap + }, + + dragStart(e) { + e.dataTransfer.setDragImage(this.pixelMapReader, 50, 50); + } } ``` diff --git a/en/application-dev/reference/arkui-ts/figures/TabBarStyle.jpeg b/en/application-dev/reference/arkui-ts/figures/TabBarStyle.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..cc2131f3d6b7f264f3a091e7788f7208232863cf Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/TabBarStyle.jpeg differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000111864201.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000111864201.gif deleted file mode 100644 index 24702d37d233b9f10a83e4e36b8c8ff23393014f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000111864201.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264366.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264366.png new file mode 100644 index 0000000000000000000000000000000000000000..212290aaf09896bef738026b0c519eb9b5d21de2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264366.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422906.PNG b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422906.PNG new file mode 100644 index 0000000000000000000000000000000000000000..854d21cc4692e51e8eac70f5644f4362a58ee640 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422906.PNG differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582854.PNG b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582854.PNG new file mode 100644 index 0000000000000000000000000000000000000000..0a8168a0a1041188a2a090bd380c2a9f5f6306a7 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582854.PNG differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001211898500.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001211898500.png deleted file mode 100644 index f27757afb281875f5cd4fca0e4b86684cdf0f1a8..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001211898500.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218462.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218462.gif deleted file mode 100644 index 1be92ae9b4a61f304b91c5b03f7b0e799ac679fa..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218462.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744189.PNG b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744189.PNG new file mode 100644 index 0000000000000000000000000000000000000000..3bcd5aa32b3ae31928a9691864fa792a9733b162 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744189.PNG differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png index 5855095851b92058f270d69a46546db43ec974b8..17a7767c1f69c12ccfb0c1436110a9e22b848c26 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744193.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858413.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858413.gif deleted file mode 100644 index 791930fb1f2f681dac85167f646dbcf88d121882..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858413.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978365.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978365.gif deleted file mode 100644 index 8da8a4adcc50c16eafb2378f0bbab0706471ae8b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978365.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/form.png b/en/application-dev/reference/arkui-ts/figures/form.png new file mode 100644 index 0000000000000000000000000000000000000000..4586dc5b6e03f856e7c0e7c7a3158d12a574a1bf Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/form.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/imageAnimator.gif b/en/application-dev/reference/arkui-ts/figures/imageAnimator.gif index 9686185c04ef6c0a764fa7fcb91b8270d503f79d..aa023c33fc6335b746d1e36eee2d9b55dc48cc1a 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/imageAnimator.gif and b/en/application-dev/reference/arkui-ts/figures/imageAnimator.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/loadProgress.jpeg b/en/application-dev/reference/arkui-ts/figures/loadProgress.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..141bc03c7528681e90fc3ed91b4c05611355e092 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/loadProgress.jpeg differ diff --git a/en/application-dev/reference/arkui-ts/figures/rating1.gif b/en/application-dev/reference/arkui-ts/figures/rating1.gif new file mode 100644 index 0000000000000000000000000000000000000000..1d7a087484ec152e0be0cecdc1b571d5a6a8f076 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/rating1.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/textstyle.png b/en/application-dev/reference/arkui-ts/figures/textstyle.png index 38128cb5f1a6aa7a36a3b4e483bf2815c7170117..babd8a3e221a628927e8f760126d625e9f395066 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/textstyle.png and b/en/application-dev/reference/arkui-ts/figures/textstyle.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/transform.PNG b/en/application-dev/reference/arkui-ts/figures/transform.PNG index a840e7050d1ae79179722dd9f23e4f383d1db2ec..9dff892b65a37c26514e9ebe925d200a75d7eee7 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/transform.PNG and b/en/application-dev/reference/arkui-ts/figures/transform.PNG differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index 21d4f71e0c0c71ccbd5b571380f20552f7abcd48..5ba70754a095b5cc00d3f317e62b9a9b7cb6471d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -19,6 +19,7 @@ DatePicker(options?: {start?: Date, end?: Date, selected?: Date}) Creates a date picker in the given date range. **Parameters** + | Name| Type| Mandatory | Description| | -------- | -------- | ------------- | -------- | | start | Date | No | Start date of the picker.
Default value: **Date('1970-1-1')**| 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 new file mode 100644 index 0000000000000000000000000000000000000000..e641340a69dad32e2db89c55ba2d44911d3258b7 --- /dev/null +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-formcomponent.md @@ -0,0 +1,124 @@ +# FormComponent + +The **FormComponent** is used to display widgets. + +> **NOTE** +> +> - This component is supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This component is intended for the widget host. For details about the widget provider, see [JS Service Widget UI Components](../js-service-widget-ui/Readme-EN.md). +> +> - To use this component, you must have the system signature. + +## Required Permissions + +ohos.permission.GET_BUNDLE_INFO + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +ohos.permission.REQUIRE_FORM + + +## Child Components + +Not supported + + +## APIs + +FormComponent(value: { + id: number; + name: string; + bundle: string; + ability: string; + module: string; + dimension?: FormDimension; + temporary?: boolean + }) + +Creates a **FormComponent** instance to display the provided widget. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ----------------------------------------------------------------------- | +| id | number | Yes | Widget ID. Set this parameter to **0** for a new widget. | +| name | string | Yes | Widget name. | +| bundle | string | Yes | Bundle name of the widget. | +| ability | string | Yes | Ability name of the widget. | +| module | string | Yes | Module name of the widget. | +| dimension | [FormDimension](#formdimension) | No | Dimensions of the widget. The widgets in the 2 x 2, 4 x 4, and 4 x 2 dimensions are supported.
Default value: **Dimension_2_2**| +| temporary | boolean | No | Whether the widget is a temporary one. | + +## FormDimension + +| Name | Description | +| -------------------------- | -------- | +| Dimension_1_2 | 1 x 2 widget.| +| Dimension_2_2 | 2 x 2 widget.| +| Dimension_2_4 | 2 x 4 widget.| +| Dimension_4_4 | 4 x 4 widget.| +| Dimension_2_19+ | 2 x 1 widget.| + +## Attributes +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------------------------------------------------------------------------------- | ---- | ----------------------------------------------------------------------- | +| size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Yes | Size of the widget. | +| moduleName | string | Yes | Module name of the widget. | +| dimension | [FormDimension](#formdimension) | No | Dimensions of the widget. The widgets in the 2 x 2, 4 x 4, and 4 x 2 dimensions are supported.
Default value: **Dimension_2_2**| +| allowUpdate | boolean | No | Whether to allow the widget to update.
Default value: **true** | +| visibility | [Visibility](ts-appendix-enums.md#visibility) | No | Whether the widget is visible.
Default value: **Visible** | + + + +## Events + +| 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. | +| 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. | + + +## Example + +```ts +//card.ets +@Entry +@Component +struct CardExample { + @State formId:number = 0; + build() { + Column() { + Text('this is a card') + .fontSize(50) + .fontWeight(FontWeight.Bold) + FormComponent({ + id:this.formId, + name:"Form1", + bundle:"com.example.cardexample", + ability:"FormAbility", + module:"entry", + dimension:FormDimension.Dimension_2_2, + temporary:false + }) + .allowUpdate(true) + .size({width:360,height:360}) + .visibility(Visibility.Visible) + .onAcquired((form)=>{ + console.log(`form info : ${JSON.stringify(form)}`); + this.fomId = form.id; + }) + .onError((err)=>{ + console.log(`fail to add form, err: ${JSON.stringify(err)}`); + }) + + } + .width('100%') + .height('100%') + } +} +``` + +![Form](figures/form.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index 25743606575892d60be19fa31fd0e60055d01fb9..09b45c7abe0e652ec4d287d8f665444aafed9c25 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -70,39 +70,20 @@ struct ImageAnimatorExample { ImageAnimator() .images([ { - src: $r('app.media.img1'), - duration: 500, - width: 170, - height: 120, - top: 0, - left: 0 + src: $r('app.media.img1') }, { - src: $r('app.media.img2'), - duration: 500, - width: 170, - height: 120, - top: 0, - left: 170 + src: $r('app.media.img2') }, { - src: $r('app.media.img3'), - duration: 500, - width: 170, - height: 120, - top: 120, - left: 170 + src: $r('app.media.img3') }, { - src: $r('app.media.img4'), - duration: 500, - width: 170, - height: 120, - top: 120, - left: 0 + src: $r('app.media.img4') } ]) - .state(this.state).reverse(this.reverse).fixedSize(false) + .duration(2000) + .state(this.state).reverse(this.reverse) .fillMode(FillMode.None).iterations(this.iterations).width(340).height(240) .margin({ top: 100 }) .onStart(() => { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md index 9dbeb85f9b9e13c4c5f346ad999d900b9ad1511a..6a39e1c9f17f7a7150728509cdc5fdc32658189a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-loadingprogress.md @@ -41,4 +41,4 @@ struct LoadingProgressExample { } ``` -![en-us_image_000000111864201](figures/en-us_image_000000111864201.gif) +![loadProgress](figures/loadProgress.jpeg) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md index ddce11da511ebe1cc573290ffd40807d31ec5ac4..8d35b928f71ec67a97fa45c7815cdd0387f3b0dd 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md @@ -17,6 +17,63 @@ NavRouter() ## Events -| Name | Description | -| ------------------------------------------------------- | ------------------------------------------------------------ | -| onStateChange(callback: (isActivated: boolean) => void) | Invoked when the component activation status changes. The value **true** means that component is activated, and **false** means the opposite.
**NOTE**
After the user clicks **NavRouter**, if the **\** component is activated and the corresponding **\** child component loaded, **onStateChange(true)** is called. If the corresponding **\** child component is no longer displayed, **onStateChange(false)** is called. | +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | +| onStateChange(callback: (isActivated: boolean) => void) | Invoked when the component activation status changes. The value **true** means that component is activated, and **false** means the opposite.
**NOTE**
After the user clicks **NavRouter**, if the **\** component is activated and the corresponding **\** child component loaded, **onStateChange(true)** is called. If the corresponding **\** child component is no longer displayed, **onStateChange(false)** is called. | + +## Example + +```ts +// xxx.ets +@Entry +@Component +struct NavRouterExample { + private arr: number[] = [0, 1, 2, 3] + @State isActive: boolean = false + @State dex: number = 0 + + build() { + Column() { + Navigation() { + List({ space: 12, initialIndex: 0 }) { + ForEach(this.arr, (item: number, index: number) => { + ListItem() { + NavRouter() { + Row() { + Image($r('app.media.icon')).width(30).height(30).borderRadius(30).margin({ left: 3, right: 10 }) + Text(`NavRouter${item + 1}`) + .fontSize(22) + .fontWeight(500) + .textAlign(TextAlign.Center) + } + .width(180) + .height(72) + .backgroundColor(this.dex === index ? '#ccc' : '#fff') + .borderRadius(24) + + NavDestination() { + Text (`I am NavDestination page ${item + 1}`).fontSize (50) + Flex({ direction: FlexDirection.Row }) { + Row() { + Image($r('app.media.icon')).width(40).height(40).borderRadius(40).margin({ right: 15 }) + Text('7 classes today').fontSize(30) + }.padding({ left: 15 }) + } + }.backgroundColor('#ccc') + .title(`NavDestination${item + 1}`) + }.onStateChange((isActivated: boolean) => { + this.dex = index + }) + } + }, item => item) + } + .height('100%') + .margin({ top: 12, left: 12 }) + } + .mode(NavigationMode.Split) + .hideTitleBar(true) + .hideToolBar(true) + }.height('100%') + } +} +``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md b/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md index 6eba8d6890c9a809c9017942b91a8f62d878e381..560a20be960ff723ccd1a633272df3cb58024e54 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-rating.md @@ -39,9 +39,10 @@ Rating(options?: { rating: number, indicator?: boolean }) | -------- | -------- | | onChange(callback:(value: number) => void) | Triggered when the rating value changes.| - ## Example +### Example 1 + ```ts // xxx.ets @Entry @@ -95,3 +96,37 @@ struct RatingExample { ``` ![rating](figures/rating.gif) + +### Example 2 + +```ts +// xxx.ets +@Entry +@Component +struct RatingExample { + @State rating: number = 3.5 + + build() { + Column() { + Rating({ rating: this.rating, indicator: false }) + .stars(5) + .stepSize(0.5) + .starStyle({ + backgroundUri: '/common/imag1.png', // The common folder is at the same level as pages. + foregroundUri: '/common/imag2.png', + secondaryUri: '/common/imag3.png' + }) + .margin({ top: 24 }) + .onChange((value: number) => { + this.rating = value + }) + Text('current score is ' + this.rating) + .fontSize(16) + .fontColor('rgba(24,36,49,0.60)') + .margin({ top: 16 }) + }.width('100%').height('100%').backgroundColor('#F1F3F5') + } +} +``` + +![rating1](figures/rating1.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md b/en/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md index 66e15d7285648a52f5c558d1f204674975804b76..b0d69a921883805f7a4686af464214869ff46578 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-remotewindow.md @@ -18,12 +18,14 @@ RemoteWindow(target: WindowAnimationTarget) Creates a **\** through a window animation object. -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | target | [WindowAnimationTarget](#windowanimationtarget) | Yes| - | Description of the animation window to control.| +**Parameters** + +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| target | [WindowAnimationTarget](#windowanimationtarget) | Yes| - | Description of the animation window to control.| ## WindowAnimationTarget + Implements a target window, which is used to remotely control the animation. | Name | Type | Description| @@ -34,6 +36,7 @@ Implements a target window, which is used to remotely control the animation. | missionId | number | Mission ID.| ## RRect + Implements a rounded rectangle. | Name | Type | Description| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 513ce4a3c0a067574521f44d994188a9e53f711d..39321308ca3063bc5da81e5ec94d353b02684cd1 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -38,14 +38,15 @@ RichText(content:string) | \

--\

| Defines six levels of headings in the HTML document. \

defines the most important heading, and \

defines the least important heading.| \

This is an H1 heading\

\

This is an H2 heading\

| | \

\

| Defines a paragraph.| \

This is a paragraph\

| | \
| Inserts a newline character.| \

This is a paragraph\
This is a new paragraph\

| +| \ | Defines the font style for the text contained within it, including the font face, size, and color.| \This is in red\ | | \
| Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \

This is a paragraph\

\
\

This is a paragraph\

| -| \\ | Defines an image.| \\ | +| \\ | Defines an image.| \\ | | \
\
| Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \
\

This is the heading in a div element\

\
| | \\ | Displays text in italic style.| \This is in italic style\| | \\ | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \ tag where it could be confused with a hyperlink.| \

\This is an underlined paragraph\\

| | \ | Used to embed CSS within an HTML document.| \ | | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \

This is a heading\

\

This is a paragraph\

| -| \ | Embeds or references a client-side script, such as JavaScript. | \ | +| \ | Embeds or references a client-side script, such as JavaScript.| \ | ## Example @@ -82,4 +83,8 @@ struct RichTextExample { } ``` - ![richText](figures/richText.png) + ![richText](figures/richText.png) + +## Precautions + +The underlying layer of the **\** component reuses the **\** component to provide basic capabilities, including but not limited to HTML page parsing and rendering. However, the **\** component is resources consuming. In scenarios where the **\** component is repeatedly used, for example, when it is repeatedly used in a list, frame freezing or slow response may occur. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md index 9d96cce6609b6619abdc86c8d9936015b59ce2e5..9f1d13ee9981696905d9383abfde395aa2162c1b 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -87,7 +87,7 @@ struct SearchExample { .searchButton('SEARCH') .width(400) .height(40) - .backgroundColor(Color.White) + .backgroundColor('#F5F5F5') .placeholderColor(Color.Grey) .placeholderFont({ size: 14, weight: 400 }) .textFont({ size: 14, weight: 400 }) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md index c1a9e51ca723ae92a530c9df98798acca7418d2e..8bb39f7eaa9cad64eb6c56936a42ddd88eaa75c6 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md @@ -25,7 +25,7 @@ Select(options: Array\<[SelectOption](#selectoption)\>) | Name | Type | Description | | ----------------------- | ------------------------------------- | --------------------------------------------- | -| selected | number | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.| +| selected | number | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.
If this attribute is not set, the default value **-1** is used, indicating that no option is selected.| | value | string | Text of the drop-down button. | | font | [Font](ts-types.md#font) | Text font of the drop-down button. | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the drop-down button. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md index fab2a885c671b6b480cbf672aa46e66730ff5cb6..b8bf88b154875799dbaa04ace76d8ea12fcc5d03 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-slider.md @@ -24,7 +24,7 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty | min | number | No| Minimum value.
Default value: **0**| | max | number | No| Maximum value.
Default value: **100**| | step | number | No| Step of the slider.
Default value: **1**
Value range: [0.01, max]| -| style | SliderStyle | No| Style of the slider thumb and track.
Default value: **SliderStyle.OutSet**| +| style | [SliderStyle](#sliderstyle) | No| Style of the slider thumb and track.
Default value: **SliderStyle.OutSet**| | direction8+ | [Axis](ts-appendix-enums.md#axis) | No| Whether the slider moves horizontally or vertically.
Default value: **Axis.Horizontal**| | reverse8+ | boolean | No| Whether the slider values are reversed. By default, the values increase from left to right for a horizontal slider and from top to bottom for a vertical slider.
Default value: **false**| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md index 99562b3a4e04b591889fcef3444ef0db82336e5e..5b29d3de61a0454ec72890a778ffd61420fe3ad9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepper.md @@ -34,11 +34,11 @@ None | Name| Description| | -------- | -------- | -| onFinish(callback: () => void) | Invoked when the **nextLabel** of the last **\** in the **\** is clicked.| +| onFinish(callback: () => void) | Invoked when the **nextLabel** of the last **\** in the **\** is clicked and the **ItemState** attribute is set to **Normal**.| | onSkip(callback: () => void) | Invoked when the current **\** is **ItemState.Skip** and the **nextLabel** is clicked.| -| onChange(callback: (prevIndex?: number, index?: number) => void) | Invoked when the user switches to the previous or next step.
- **prevIndex**: index of the step page before the switching.
- **index**: index of the step page after the switching, that is, index of the previous or next page.| -| onNext(callback: (index?: number, pendingIndex?: number) => void) | Invoked when a user switches to the next step.
- **index**: index of the current step page.
- **pendingIndex**: index of the next page.| -| onPrevious(callback: (index?: number, pendingIndex?: number) => void) | Invoked when a user switches to the previous step.
- **index**: index of the current step page.
- **pendingIndex**: index of the previous page.| +| onChange(callback: (prevIndex?: number, index?: number) => void) | Invoked when the **prevLabel** of the current **\** is clicked to switch to the previous step page; or when the **nextLabel** of the current (not the last) **\** is clicked to switch to the next step page and the **ItemState** attribute is set to **Normal**.
- **prevIndex**: index of the step page before the switching.
- **index**: index of the step page after the switching, that is, index of the previous or next step page.| +| onNext(callback: (index?: number, pendingIndex?: number) => void) | Invoked when the **nextLabel** of the current (not the last) **\** is clicked and the **ItemState** attribute is set to **Normal**.
- **index**: index of the current step page.
- **pendingIndex**: index of the next step page.| +| onPrevious(callback: (index?: number, pendingIndex?: number) => void) | Invoked when the **prevLabel** of the current **\** is clicked to switch to the previous step page.
- **index**: index of the current step page.
- **pendingIndex**: index of the previous step page.| ## Example @@ -122,7 +122,6 @@ struct StepperExample { .itemTextStyle() }.itemStyle() } - .nextLabel('Finish') } .backgroundColor('#F1F3F5') .onFinish(() => { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md index bef2f119228f2f25d0d2d3c83a17bdded4f1b242..809b3f114fe2c2b9e0baba64f049d136d689a1cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md @@ -22,7 +22,7 @@ StepperItem() | Name| Type| Description| | -------- | -------- | -------- | -| prevLabel | string | Text label of the button on the left. When the **\** contains more than one page, the default value for all pages except the first page is **Back**.| +| prevLabel | string | Text label of the button on the left, which is not displayed on the first page. When the **\** contains more than one page, the default value for all pages except the first page is **Back**.| | nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.| | status | ItemState | Display status of **nextLabel** in the stepper.
Default value: **ItemState.Normal**| @@ -31,9 +31,9 @@ StepperItem() | Name | Value | Description| | -------- | -------- |-------- | | Normal | 0 |The button on the right is clickable and can navigate users to the next **\** when it is clicked.| -| Disabled | 1 |The button on the right is grayed out and unavailable.| +| Disabled | 1 |The button on the right is disabled.| | Waiting | 2 | The button on the right is not displayed, and a progress bar is displayed instead.| -| Skip | 3 |The button on the right reads "Skip". You can define the processing logic for this state in the **onSkip** callback of the stepper.| +| Skip | 3 |The button on the right reads "Skip" by default. You can define the processing logic for this state in the **onSkip** callback of the stepper.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index 354cd00042b8ba46a1cf9a68effc32f792c9f48a..67eedfeb76158d1cd94e57196811406d46dcbf3b 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -28,19 +28,19 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | ----------------------- | ----------------------------------- | ------------------------------------------- | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect.| -| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**
**NOTE**
The text takes up the full width of the **\** component. To set the vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute.| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect. | +| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed. | | lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: **{
type: TextDecorationType.None,
color: Color.Black
}** | +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
} | | baselineOffset | number \| string | Baseline offset of the text. The default value is **0**. | | letterSpacing | number \| string | Letter spacing. | -| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size. | -| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size. | +| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.
For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxline**, or a layout size constraint. | +| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.
For the setting to take effect, this attribute must be used together with **minFontSize**, **maxline**, or a layout size constraint. | | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**| -> **NOTE**
+> **NOTE** > > The **\** component cannot contain both the text and the child component **\**. If both of them exist, only the content in **\** is displayed. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 96dcafda243b4c930476bafbd8d172ab50a49ab2..b7a72430211190079eec4d628a61658bb664bc21 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -53,7 +53,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Next | The Enter key is labeled "Next."| | Done | The Enter key is labeled "Done." | -## InputType enums +## InputType | Name | Description | | ------------------ | ------------- | @@ -70,7 +70,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | | Inline | Inline input style. The background height of the selected text is the same as the height of the text box. | -## Event +## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md b/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md index a4b2b64dd884104060b94f874f2c7bc0255f7429..c586ea6669b6a5fb9a801ef1ef307a879b8d12a3 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md @@ -75,7 +75,7 @@ struct TextTimerExample { build() { Column() { - TextTimer({ controller: this.textTimerController, isCountDown: true, count: 30000 }) + TextTimer({ isCountDown: true, count: 30000, controller: this.textTimerController }) .format(this.format) .fontColor(Color.Black) .fontSize(50) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md index 12e1dd5287c21a12499361c6acae498ad11671f6..f1f8e0b31d765b58e10b43d23f19ffdab04bac1d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-toggle.md @@ -26,9 +26,9 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) ## ToggleType | Name | Description | | -------- | ---------------- | -| Checkbox | Check box type.
> **NOTE**
> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 14 vp,
right: 6 vp,
bottom: 14 vp,
left: 6 vp
} | +| Checkbox | Check box type.
**NOTE**
The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 14 vp,
right: 6 vp,
bottom: 14 vp,
left: 6 vp
} | | Button | Button type. The set string, if any, will be displayed inside the button. | -| Switch | Switch type.
> **NOTE**
> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 12 vp,
right: 12 vp,
bottom: 12 vp,
left: 12 vp
} | +| Switch | Switch type.
**NOTE**
The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 12 vp,
right: 12 vp,
bottom: 12 vp,
left: 12 vp
} | ## Attributes @@ -36,7 +36,7 @@ Toggle(options: { type: ToggleType, isOn?: boolean }) | Name | Parameter | Description | | ---------------- | --------------------------- | ---------------------- | | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component when it is turned on.| -| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the circular slider when the component is of the **Switch** type.
> **NOTE**
> This attribute is valid only when **type** is set to **ToggleType.Switch**.| +| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the circular slider when the component is of the **Switch** type.
**NOTE**
This attribute is valid only when **type** is set to **ToggleType.Switch**. | ## Events diff --git a/en/application-dev/reference/arkui-ts/ts-combined-gestures.md b/en/application-dev/reference/arkui-ts/ts-combined-gestures.md index d4a6320eb4ea942eeb262aa9973155fc0c1f972b..64aae057f5b24c1640fe2765bf6cd2ef2a5745c7 100644 --- a/en/application-dev/reference/arkui-ts/ts-combined-gestures.md +++ b/en/application-dev/reference/arkui-ts/ts-combined-gestures.md @@ -6,18 +6,19 @@ Continuous recognition, parallel recognition, and exclusive recognition are supp > > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - ## APIs GestureGroup(mode: GestureMode, ...gesture: GestureType[]) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | mode | [GestureMode](#gesturemode) | Yes| - | Recognition mode of combined gestures.| - | gesture | [TapGesture](ts-basic-gestures-tapgesture.md)
\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)
\| [PanGesture](ts-basic-gestures-pangesture.md)
\| [PinchGesture](ts-basic-gestures-pinchgesture.md)
\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Yes| - | Variable-length parameter, indicating one or more basic gesture types. These gestures are recognized in combination.| +**Parameters** + +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| mode | [GestureMode](#gesturemode) | Yes| - | Recognition mode of combined gestures.| +| gesture | [TapGesture](ts-basic-gestures-tapgesture.md)
\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)
\| [PanGesture](ts-basic-gestures-pangesture.md)
\| [PinchGesture](ts-basic-gestures-pinchgesture.md)
\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Yes| - | Variable-length parameter, indicating one or more basic gesture types. These gestures are recognized in combination.| ## GestureMode + | Name| Description| | -------- | -------- | | Sequence | Sequential recognition: Gestures are recognized in the registration sequence until all gestures are recognized successfully. When one gesture fails to be recognized, all gestures fail to be recognized.| diff --git a/en/application-dev/reference/arkui-ts/ts-container-badge.md b/en/application-dev/reference/arkui-ts/ts-container-badge.md index 98f9a6f785e635125a6c8837526e9c6b1ac9084d..91e41e1a16163adb8ccd9f1d2fdb00d59ebd903f 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/arkui-ts/ts-container-badge.md @@ -19,6 +19,7 @@ This component supports only one child component. Creates a badge. **Parameters** + | Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- | -------- | | count | number | Yes| - | Number of notifications.| diff --git a/en/application-dev/reference/arkui-ts/ts-container-column.md b/en/application-dev/reference/arkui-ts/ts-container-column.md index 913ba5cd08576515707930d267cfa72f860f3d7a..3f39abc38c116009f358d0470200798c7a51bc2c 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-column.md +++ b/en/application-dev/reference/arkui-ts/ts-container-column.md @@ -20,7 +20,7 @@ Column(value?: {space?: string | number}) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| space | string \| number | No| Vertical spacing between two adjacent child components.
Since API version 9, this parameter does not take effect when it is set to a negative number.
Default value: **0**| +| space | string \| number | No| Vertical spacing between two adjacent child components.
Since API version 9, this parameter does not take effect when it is set to a negative number or **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround** or **FlexAlign.SpaceEvenly**.
Default value: **0**| ## Attributes @@ -29,7 +29,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | | alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | Alignment mode of the child components in the horizontal direction.
Default value: **HorizontalAlign.Center**| -| justifyContent8+ | [FlexAlign](ts-container-flex.md) | Alignment mode of the child components in the vertical direction.
Default value: **FlexAlign.Start**| +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the vertical direction.
Default value: **FlexAlign.Start**| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-flex.md b/en/application-dev/reference/arkui-ts/ts-container-flex.md index a2de237b09f26589ff262ea1cabe89273bec72d9..e29fd91fd85ab9142191700d2b73042fe7f77440 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/arkui-ts/ts-container-flex.md @@ -3,15 +3,11 @@ The **\** component allows for flexible layout of child components. > **NOTE** +> > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - The **\** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[\](ts-container-column.md)** or **[\](ts-container-row.md)** instead under scenarios where consistently high performance is required. -## Required Permissions - -None - - ## Child Components Supported @@ -23,14 +19,15 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle Creates a standard **\** component. -- Parameters - | Name | Type | Mandatory | Default Value | Description | - | -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- | - | direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\** component, that is, the direction of the main axis. | - | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | - | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | - | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | - | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**. | +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- | +| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\** component, that is, the direction of the main axis. | +| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | +| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | +| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | +| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**. | ## Example @@ -96,7 +93,7 @@ struct FlexExample1 { } ``` -![en-us_image_0000001256978365](figures/en-us_image_0000001256978365.gif) +![en-us_image_0000001219744189](figures/en-us_image_0000001219744189.PNG) ```ts // xxx.ets @@ -142,7 +139,7 @@ struct FlexExample2 { } ``` -![en-us_image_0000001211898500](figures/en-us_image_0000001211898500.png) +![en-us_image_0000001174264366](figures/en-us_image_0000001174264366.png) ```ts // xxx.ets @@ -191,7 +188,7 @@ struct FlexExample3 { } ``` -![en-us_image_0000001212218462](figures/en-us_image_0000001212218462.gif) +![en-us_image_0000001174582854](figures/en-us_image_0000001174582854.PNG) ```ts // xxx.ets @@ -289,4 +286,4 @@ struct FlexExample5 { } ``` -![en-us_image_0000001256858413](figures/en-us_image_0000001256858413.gif) +![en-us_image_0000001174422906](figures/en-us_image_0000001174422906.PNG) diff --git a/en/application-dev/reference/arkui-ts/ts-container-grid.md b/en/application-dev/reference/arkui-ts/ts-container-grid.md index feea5dbcaed85e2f145d67425b7907a7110cacaf..db7aaa87e31c0e1cc15c90035a6b210a00faf8e1 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/en/application-dev/reference/arkui-ts/ts-container-grid.md @@ -17,6 +17,7 @@ This component contains the child component **[\](ts-container-gridite Grid(scroller?: Scroller) **Parameters** + | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | ----------------------- | | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.| diff --git a/en/application-dev/reference/arkui-ts/ts-container-griditem.md b/en/application-dev/reference/arkui-ts/ts-container-griditem.md index f5d0820467b44a515181c2e9a5cf3eb51e23079a..ca8e19332e7c8eb573c9086b25ec455a573ed5f0 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-griditem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-griditem.md @@ -25,7 +25,7 @@ GridItem() | rowEnd | number | End row number of the component.| | columnStart | number | Start column number of the component.| | columnEnd | number | End column number of the component.| -| forceRebuild | boolean | Whether to re-create the component when it is being built.
Default value: **false**| +| forceRebuild(deprecated) | boolean | Whether to re-create the component when it is being built.
This API is deprecated since API version 9. Whether to re-create the component is automatically determined based on the component attributes and child component changes. No manual configuration is required.
Default value: **false**| | selectable8+ | boolean | Whether the current grid item is selectable by the mouse.
> **NOTE**
> This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| @@ -43,29 +43,40 @@ GridItem() @Entry @Component struct GridItemExample { - @State numbers: string[] = Array.apply(null, Array(16)).map(function (item, i) { return i.toString() }) + @State numbers: string[] = Array.apply(null, { length: 16 }).map(function (item, i) { + return i.toString() + }) build() { Column() { Grid() { GridItem() { Text('4') - .fontSize(16).backgroundColor(0xFAEEE0) - .width('100%').height('100%').textAlign(TextAlign.Center) + .fontSize(16) + .backgroundColor(0xFAEEE0) + .width('100%') + .height('100%') + .textAlign(TextAlign.Center) }.rowStart(1).rowEnd(4) ForEach(this.numbers, (item) => { GridItem() { Text(item) - .fontSize(16).backgroundColor(0xF9CF93) - .width('100%').height('100%').textAlign(TextAlign.Center) - }.forceRebuild(false) + .fontSize(16) + .backgroundColor(0xF9CF93) + .width('100%') + .height('100%') + .textAlign(TextAlign.Center) + } }, item => item) GridItem() { Text('5') - .fontSize(16).backgroundColor(0xDBD0C0) - .width('100%').height('100%').textAlign(TextAlign.Center) + .fontSize(16) + .backgroundColor(0xDBD0C0) + .width('100%') + .height('100%') + .textAlign(TextAlign.Center) }.columnStart(1).columnEnd(5) } .columnsTemplate('1fr 1fr 1fr 1fr 1fr') diff --git a/en/application-dev/reference/arkui-ts/ts-container-gridrow.md b/en/application-dev/reference/arkui-ts/ts-container-gridrow.md index 266360307d199b1bfcbc713829b861efe66044c1..8522382eb79c938150837fae77a8067f63f19517 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-gridrow.md +++ b/en/application-dev/reference/arkui-ts/ts-container-gridrow.md @@ -16,6 +16,7 @@ This component can contain the **\** child component. GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | GutterOption, breakpoints?: BreakPoints, direction?: GridRowDirection}) **Parameters** + | Name|Type|Mandatory|Description| |-----|-----|----|----| |gutter|Length \| GutterOption| No |Gutter of the grid layout. **x** indicates the horizontal direction.| @@ -37,11 +38,11 @@ Describes the numbers of grid columns for different device width types. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | xs | number | No | Device of the minimum size. | -| sm | number | No | Small-sized device. | -| md | number | No | Medium-sized device. | -| lg | number | No | Large-sized device. | -| xl | number | No | Extra-large-sized device. | -| xxl | number | No | Ultra-large-sized device. | +| sm | number | No | Small-sized device. | +| md | number | No | Medium-sized device. | +| lg | number | No | Large-sized device. | +| xl | number | No | Extra-large-sized device. | +| xxl | number | No | Ultra-large-sized device. | ## GridRowSizeOption @@ -50,11 +51,11 @@ Describes the gutter sizes for different device width types. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | | xs | Length | No | Device of the minimum size. | -| sm | Length | No | Small-sized device. | -| md | Length | No | Medium-sized device. | -| lg | Length | No | Large-sized device. | -| xl | Length | No | Extra-large-sized device. | -| xxl | Length | No | Ultra-large-sized device. | +| sm | Length | No | Small-sized device. | +| md | Length | No | Medium-sized device. | +| lg | Length | No | Large-sized device. | +| xl | Length | No | Extra-large-sized device. | +| xxl | Length | No | Ultra-large-sized device. | ## BreakPoints diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index bc109daa464ac8f2ff0645885829d882922875c6..7a944fbdedacd17582182a44a8ef03c51f8af141 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -70,7 +70,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.
When calculating the index value, the **\** accounts for one index value as a whole, and the index values of the list items within are not calculated.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.| | onReachStart(event: () => void) | Triggered when the list reaches the start position.| | onReachEnd(event: () => void) | Triggered when the list reaches the end position.| -| onScrollBegin9+(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
- **dx**: amount by which the list will scroll in the horizontal direction.
- **dy**: amount by which the list will scroll in the horizontal direction.
- **dxRemain**: amount by which the list actually scrolls in the horizontal direction.
- **dyRemain**: amount by which the list actually scrolls in the vertical direction.| +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current sliding status.
- **offsetRemain**: required amount to scroll by in the horizontal direction.| +| onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).| | onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the dragged list element.| diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index 5ff83b20ec921e32c2b3c4e6d078f89941ec55d2..a101532880cdab858319d8a13cf7df487cfb3a33 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -101,8 +101,7 @@ struct ListItemExample2 { Column() { List({space:10}) { ListItem() { - Text(this.message) { - } + Text(this.message) .width('100%') .height(100) .fontSize(16) @@ -113,8 +112,7 @@ struct ListItemExample2 { .swipeAction({ end:this.itemEnd}) ListItem() { - Text(this.message) { - } + Text(this.message) .width('100%') .height(100) .fontSize(16) diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md index b836d4ea98c041b09d5f6eb7a4fc0304e905237e..978b93088cdb7c6eb729204b0b16d89af2066be5 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md @@ -5,7 +5,9 @@ The **\** component is used to display list item groups. It must > **NOTE** > > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. + ## Usage Guidelines + If the **listDirection** attribute of the parent **\** component is set to **Axis.Vertical**, the **height** attribute of the **\** component cannot be set. The height of a **\** component is the sum of its header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\** component is set to **Axis.Horizontal**, the **width** attribute of the **\** component cannot be set. The width of a **\** component is the sum of its header width, footer width, and total width of the list items. The list items in the **\** component cannot be edited, selected, or dragged. That is, the **editable** and **selectable** attributes of these list items do not take effect. diff --git a/en/application-dev/reference/arkui-ts/ts-container-row.md b/en/application-dev/reference/arkui-ts/ts-container-row.md index 6e7d1843e0222844d5fdf46cd537dfda346d9958..deb83273445d1b5d16e5540476ccfa9c8c9b1fba 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-row.md +++ b/en/application-dev/reference/arkui-ts/ts-container-row.md @@ -20,7 +20,7 @@ Row(value?:{space?: number | string }) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| space | string \| number | No| Horizontal spacing between two adjacent child components.
Since API version 9, this parameter does not take effect when it is set to a negative number.
Default value: **0**, in vp| +| space | string \| number | No| Horizontal spacing between two adjacent child components.
Since API version 9, this parameter does not take effect when it is set to a negative number or **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround** or **FlexAlign.SpaceEvenly**.
Default value: **0**, in vp| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index a0efd8457d392485781624d95fef53017706964a..1ebba8cc427bd9205fa7048310d9e97274f079ea 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -36,20 +36,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Horizontal | Only horizontal scrolling is supported. | | Vertical | Only vertical scrolling is supported. | | None | Scrolling is disabled. | -| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9.| +| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9. | ## Events | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onScrollBegin9+(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Invoked when scrolling starts.
Parameters:
- **dx**: amount to scroll by in the horizontal direction.
- **dy**: amount to scroll by in the vertical direction.
Return value:
- **dxRemain**: remaining amount to scroll by in the horizontal direction.
- **dyRemain**: remaining amount to scroll by in the vertical direction.| -| onScroll(event: (xOffset: number, yOffset: number) => void) | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | -| onScrollEdge(event: (side: Edge) => void) | Invoked when scrolling reaches the edge. | -| onScrollEnd(event: () => void) | Invoked when scrolling stops. | +| onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by.
\- **state**: current scrolling status.
- **offsetRemain**: required amount to scroll by in the horizontal direction.| +| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | +| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge. | +| onScrollEnd(event: () => void) | Triggered when scrolling stops.
This event is deprecated since API version 9. Use the **onScrollStop** event instead. | +| onScrollStart9+(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\** component or its scrollbar. This event will not be triggered if the scrolling is initiated by using [Scroller](#scroller).| +| onScrollStop9+(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](#scroller).| > **NOTE** > -> If the **onScrollBegin** event and **scrollBy** API are used to implement nested scrolling, you must set **edgeEffect** of the scrolling child node to **None**. For example, if a **\** is nested in the **\** component, the **edgeEffect** attribute of the **\** must be set to **EdgeEffect.None**. +> If the **onScrollFrameBegin** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\** is nested in the **\** component, **edgeEffect** of the **\** must be set to **EdgeEffect.None**. ## Scroller @@ -76,7 +78,7 @@ Scrolls to the specified position. | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | xOffset | Length | Yes | Horizontal scrolling offset. | | yOffset | Length | Yes | Vertical scrolling offset. | -| animation | {
duration: number,
curve: [Curve](ts-animatorproperty.md)
} | No | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve.| +| animation | {
duration: number,
curve: [Curve](ts-appendix-enums.md#curve)
} | No | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve.| ### scrollEdge @@ -104,7 +106,7 @@ Scrolls to the next or previous page. | Name | Type | Mandatory | Description | | --------- | ------- | ---- | ------------------------------ | | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| -| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | +| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | ### currentOffset @@ -131,7 +133,7 @@ Scrolls to the item with the specified index. > **NOTE** > -> Only the **\**, **\**, and **\** components are supported. +> Only the **\** and **\** components are supported. **Parameters** @@ -268,13 +270,13 @@ struct NestedScroll { .onReachEnd(() => { this.listPosition = 2 }) - .onScrollBegin((dx: number, dy: number) => { - if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) { - this.scrollerForScroll.scrollBy(0, -dy) - return { dxRemain: dx, dyRemain: 0 } + .onScrollFrameBegin((offset: number) => { + if ((this.listPosition == 0 && offset <= 0) || (this.listPosition == 2 && offset >= 0)) { + this.scrollerForScroll.scrollBy(0, offset) + return { offsetRemain: 0 } } this.listPosition = 1 - return { dxRemain: dx, dyRemain: dy }; + return { offsetRemain: offset }; }) Text("Scroll Area") diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index 400132c6ffd427a249df0c19b50e04c06eabcc3a..d874d686fd63a1e00b2892ec5d24a7e069786e02 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -23,13 +23,45 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
> **NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.| +| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. | +| tabBar9+ | [SubTabBarStyle](#subtabbarstyle) \| [BottomTabBarStyle](#bottomtabbarstyle) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.| > **NOTE** > - The **\** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\** component. > - The **\** component does not support setting of the common height attribute. Its height is determined by the height of the parent **\** component and the **\** component. -> - The **\** component does not support setting of the [touch target](ts-universal-attributes-touch-target.md). +## SubTabBarStyle9+ + +Implements the subtab style. + +### constructor9+ + +constructor(content: string | Resource) + +A constructor used to create a **SubTabBarStyle** instance. + +**Parameters** + +| Name| Type | Mandatory| Description| +| -------- | -------- | -------- | -------- | +| content | string \| [Resource](ts-types.md#resource) | Yes| Text for the tab.| + +## BottomTabBarStyle9+ + +Implements the bottom and side tab style. + +### constructor9+ + +constructor(icon: string | Resource, text: string | Resource) + +A constructor used to create a **BottomTabBarStyle** instance. + +**Parameters** + +| Name| Type | Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | string \| [Resource](ts-types.md#resource) | Yes| Image for the tab.| +| text | string \| [Resource](ts-types.md#resource) | Yes| Text for the tab.| ## Example @@ -194,3 +226,101 @@ struct TabContentExample { ``` ![tabContent](figures/tabContent2.gif) + +Example 3: + +```ts +// xxx.ets +@Entry +@Component +struct TabBarStyleExample { + build() { + Column({ space: 5 }) { + Text ("Subtab Style") + Column() { + Tabs({ barPosition: BarPosition.Start }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(new SubTabBarStyle('Pink')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow) + }.tabBar(new SubTabBarStyle('Yellow')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + }.tabBar(new SubTabBarStyle('Blue')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar(new SubTabBarStyle('Green')) + } + .vertical(false) + .scrollable(true) + .barMode(BarMode.Fixed) + .onChange((index: number) => { + console.info(index.toString()) + }) + .width('100%') + .backgroundColor(0xF1F3F5) + }.width('100%').height(200) + Text ("Bottom Tab Style") + Column() { + Tabs({ barPosition: BarPosition.End }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'pink')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Yellow')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Blue')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Green')) + } + .vertical(false) + .scrollable(true) + .barMode(BarMode.Fixed) + .onChange((index: number) => { + console.info(index.toString()) + }) + .width('100%') + .backgroundColor(0xF1F3F5) + }.width('100%').height(200) + Text ("Side Tab Style") + Column() { + Tabs({ barPosition: BarPosition.Start }) { + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Pink) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'pink')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Yellow) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Yellow')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Blue')) + + TabContent() { + Column().width('100%').height('100%').backgroundColor(Color.Green) + }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Green')) + } + .vertical(true).scrollable(true).barMode(BarMode.Fixed) + .onChange((index: number) => { + console.info(index.toString()) + }) + .width('100%') + .backgroundColor(0xF1F3F5) + }.width('100%').height(400) + } + } +} +``` + +![tabbarStyle](figures/TabBarStyle.jpeg) diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index b331d2efa09a4cb8da1b6880f642ced3ca411fb3..e1d90464b363777239c670b679a0cf1e2c5d711d 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -34,7 +34,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. The [touch target](ts-universal-attributes-touch-target.md) is not supported. +In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. | Name| Type| Description| | -------- | -------- | -------- | @@ -43,7 +43,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.
Default value: **BarMode.Fixed**| | barWidth | number \| Length8+ | Width of the tab bar. | | barHeight | number \| Length8+ | Height of the tab bar. | -| animationDuration | number | Animation duration of the tab content.
Default value: **200**| +| animationDuration | number | Duration of the slide animation for tab switching. If this parameter is set, the tab switching animation is played when the user switches between tabs by sliding or clicking. If this parameter is not set, the tab switching animation is played only when the user switches between tabs by sliding.
Default value: **200**| ## BarMode diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md index 4720e9731a7aa613f5ab15f2815754b5789730c1..f0645c5079ef86d29d848e059c5187bf76f5d8d3 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -74,9 +74,8 @@ struct PathExample { .width('90%') // Draw a straight line whose length is 900 px and width is 3 vp. Path() - .width(300) .height(10) - .commands('M0 0 L900 0') + .commands('M0 0 L600 0') .stroke(Color.Black) .strokeWidth(3) @@ -85,55 +84,43 @@ struct PathExample { .fontColor(0xCCCCCC) .width('90%') // Draw a straight line. - Row({ space: 20 }) { + Flex({ justifyContent: FlexAlign.SpaceBetween }) { Path() - .width(100) - .height(100) - .commands('M150 0 L300 300 L0 300 Z') + .commands('M100 0 L200 240 L0 240 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() - .width(100) - .height(100) - .commands('M0 0 H300 V300 H0 Z') + .commands('M0 0 H200 V200 H0 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() - .width(100) - .height(100) - .commands('M150 0 L0 150 L60 300 L240 300 L300 150 Z') + .commands('M100 0 L0 100 L50 200 L150 200 L200 100 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) - }.width('100%') + }.width('95%') Text('Curve graphics').fontSize(11).fontColor(0xCCCCCC).width('90%') // Draw an arc. - Row({ space: 20 }) { + Flex({ justifyContent: FlexAlign.SpaceBetween }) { Path() - .width(100) - .height(100) - .commands("M0 300 S150 0 300 300 Z") + .commands("M0 300 S100 0 240 300 Z") .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() - .width(100) - .height(100) - .commands('M0 150 C0 150 150 0 300 150 L150 300 Z') + .commands('M0 150 C0 100 140 0 200 150 L100 300 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) Path() - .width(100) - .height(100) - .commands('M0 200 A30 20 20 0 0 250 200 Z') + .commands('M0 100 A30 20 20 0 0 200 100 Z') .fillOpacity(0) .stroke(Color.Black) .strokeWidth(3) - } + }.width('95%') }.width('100%') .margin({ top: 5 }) } diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index 21bb3d6a2890f13215b0f331f3bbab298c0d1de0..feb0d96571dd263205252f8c849b5a0f6ee967b1 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -48,7 +48,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | muted | boolean | Whether to mute the video.
Default value: **false** | | autoPlay | boolean | Whether to enable auto play.
Default value: **false** | | controls | boolean | Whether to display the video playback control bar.
Default value: **true**| -| objectFit | [ImageFit](ts-basic-components-image.md) | Video scale type.
Default value: **Cover** | +| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Video scale type.
Default value: **Cover** | | loop | boolean | Whether to repeat the video.
Default value: **false** | ## Events @@ -243,5 +243,3 @@ struct VideoCreateComponent { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index c3db1cb598e80cd0b907f2eba3188cd0e23c712d..7615fe3729496bd536aebc57a9efc622fa3957a5 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -23,7 +23,7 @@ Defines and shows the action sheet. | autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.
Default value: **true**| | confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
action: () => void
} | No | Text content of the confirm button and callback upon button clicking.
Default value:
**value**: button text.
**action**: callback upon button clicking.| | cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | -| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Bottom**| +| alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Bottom**| | offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.
Default value: {
dx: 0,
dy: 0
} | | sheets | Array<SheetInfo> | Yes | Options in the dialog box. Each option supports the image, text, and callback.| diff --git a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index 21af1fc8ad17cbb3fc27c400d57ebad2293b133e..37bf4de513a5773e660b53d8a07c621882c21714 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -11,7 +11,7 @@ A custom dialog box is a dialog box you customize by using APIs of the **CustomD ## APIs -CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number}) +CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAniamtion?: AnimateParam}) **Parameters** @@ -23,9 +23,11 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, aut | autoCancel | boolean | No | Whether to allow users to click the overlay to exit.
Default value: **true** | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default** | | offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.| -| customStyle | boolean | No | Whether to use a custom style for the dialog box.
Default value: **false** | +| customStyle | boolean | No | Whether to use a custom style for the dialog box.
Default value: **false**, which means that the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height; the rounded corner is 24 vp. | | gridCount8+ | number | No | Number of [grid columns](../../ui/ui-ts-layout-grid-container-new.md) occupied by the dialog box.
The default value is 4, and the maximum value is the maximum number of columns supported by the system. If this parameter is set to an invalid value, the default value is used.| - +| maskColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Custom mask color.
Default value: **0x33000000** | +| openAnimation10+ | [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the open animation of the dialog box. | +| closeAniamtion10+| [AnimateParam](ts-explicit-animation.md#animateparam) | No | Parameters for defining the close animation of the dialog box. | ## CustomDialogController diff --git a/en/application-dev/reference/arkui-ts/ts-methods-menu.md b/en/application-dev/reference/arkui-ts/ts-methods-menu.md index 994984976e14b029d1ed82aae9375fd8387828e2..56e07e983a2e9ea10119c160f43b803d2ffb66b6 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-menu.md @@ -24,9 +24,9 @@ struct Index { @Builder MenuBuilder() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Button('Test ContextMenu1') - Divider().strokeWidth(2).margin(5) + Divider().strokeWidth(2).margin(5).color(Color.Black) Button('Test ContextMenu2') - Divider().strokeWidth(2).margin(5) + Divider().strokeWidth(2).margin(5).color(Color.Black) Button('Test ContextMenu3') } .width(200) diff --git a/en/application-dev/reference/arkui-ts/ts-state-management.md b/en/application-dev/reference/arkui-ts/ts-state-management.md index 6e6eaeafac441965e52b9b0fc5862ca557b90014..7a00f2233de4e3b9264e6a1927376b0bd6d5b861 100644 --- a/en/application-dev/reference/arkui-ts/ts-state-management.md +++ b/en/application-dev/reference/arkui-ts/ts-state-management.md @@ -1,6 +1,6 @@ # State Management with Application-level Variables -The state management module provides APIs for data storage, persistent data management, Ability data storage, and environment status required by applications. The APIs for Ability data storage are supported since API version 9. +The state management module provides APIs for data storage, persistent data management, **Ability** data storage, and environment status required by applications. > **NOTE** > @@ -77,7 +77,7 @@ let simple = AppStorage.Prop('simpleProp') ### SetAndProp -SetAndProp\(propName: string, defaultValue: S): SubscribedAbstractProperty\; +SetAndProp\(propName: string, defaultValue: S): SubscribedAbstractProperty\ Works in a way similar to the **Prop** API. If the current key is stored in the **AppStorage**, the value corresponding to the key is returned. If the key has not been created, a **Prop** instance corresponding to the default value is created and returned. @@ -162,7 +162,7 @@ Replaces the value of a saved key. | boolean | Returns **true** and the value if the key exists; returns **false** otherwise.| ```ts -let simple = AppStorage.Set('simpleProp', 121); +let simple = AppStorage.Set('simpleProp', 121) ``` ### SetOrCreate @@ -256,7 +256,7 @@ Deletes all attributes. | ------- | --------------------------------- | | boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.| -```typescript +```ts let simple = AppStorage.Clear() ``` @@ -313,7 +313,7 @@ Creates and initializes a **LocalStorage** object. | initializingProperties | Object | No | All object attributes and their values returned by **object.keys(obj)**.| ```ts -this.storage = new LocalStorage() +let storage = new LocalStorage() ``` ### GetShared9+ @@ -353,8 +353,8 @@ Checks whether the **LocalStorage** contains the specified attribute. | boolean | Returns whether the attribute exists.| ```ts -this.storage = new LocalStorage() -this.storage.has('storageSimpleProp') +let storage = new LocalStorage() +storage.has('storageSimpleProp') ``` ### get9+ @@ -376,8 +376,8 @@ Obtains the value of the specified key. | T \| undefined | Returns the value of the specified key if it exists; returns **undefined** otherwise.| ```ts -this.storage = new LocalStorage() -let simpleValue = this.storage.get('storageSimpleProp') +let storage = new LocalStorage() +let simpleValue = storage.get('storageSimpleProp') ``` ### set9+ @@ -400,8 +400,8 @@ Sets a new value for the specified key. | boolean | Returns **true** and the value if the key exists; returns **false** otherwise.| ```ts -this.storage = new LocalStorage() -this.storage.set('storageSimpleProp', 121) +let storage = new LocalStorage() +storage.set('storageSimpleProp', 121) ``` ### setOrCreate9+ @@ -424,8 +424,8 @@ Creates or updates the value of the specified key. | boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns false otherwise. **undefined** and **null** are not allowed.| ```ts -this.storage = new LocalStorage() -this.storage.setOrCreate('storageSimpleProp', 121) +let storage = new LocalStorage() +storage.setOrCreate('storageSimpleProp', 121) ``` ### link9+ @@ -447,8 +447,8 @@ Establishes two-way data binding between an attribute and this **LocalStorage** | T | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the **LocalStorage**, and attribute changes made through the **LocalStorage** will be synchronized to the variable or component. returns **undefined** if the attribute with the given key does not exist.| ```ts -this.storage = new LocalStorage() -let localStorage = this.storage.link('storageSimpleProp') +let storage = new LocalStorage() +let localStorage = storage.link('storageSimpleProp') ``` ### setAndLink9+ @@ -471,8 +471,8 @@ Works in a way similar to the **Link** API. | @Link | Returns the value corresponding to the key if the current key is stored in the **LocalStorage**; creates and returns a **Link** instance corresponding to the default value if the key has not been created.| ```ts -this.storage = new LocalStorage() -let localStorage = this.storage.setAndLink('storageSimpleProp', 121) +let storage = new LocalStorage() +let localStorage = storage.setAndLink('storageSimpleProp', 121) ``` ### prop9+ @@ -494,8 +494,8 @@ Establishes one-way data binding with an attribute to update its status. | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. One-way binding means that attribute changes made through the **LocalStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will not be synchronized to the **LocalStorage**. This API returns immutable variables and is applicable to mutable and immutable state variables alike. | ```ts -this.storage = new LocalStorage() -let localStorage = this.storage.prop('storageSimpleProp') +let storage = new LocalStorage() +let localStorage = storage.prop('storageSimpleProp') ``` ### setAndProp9+ @@ -518,8 +518,8 @@ Works in a way similar to the **Prop** API. | @Prop | Returns the value corresponding to the given key if the key is stored in the **LocalStorage**; creates and returns a **Prop** instance corresponding to the default value if the key has not been created.| ```ts -this.storage = new LocalStorage() -let localStorage = this.storage.setAndProp('storageSimpleProp', 121) +let storage = new LocalStorage() +let localStorage = storage.setAndProp('storageSimpleProp', 121) ``` ### delete9+ @@ -538,11 +538,11 @@ Deletes the key-value pair that matches the specified key. | Type | Description | | ------- | ---------------------------------------- | -| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** if the key-value pair does not exist, fails to be deleted, or is being referenced by a state variable.| +| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.| ```ts -this.storage = new LocalStorage() -this.storage.delete('storageSimpleProp') +let storage = new LocalStorage() +storage.delete('storageSimpleProp') ``` ### keys9+ @@ -558,8 +558,8 @@ Searches for all keys. | array\ | Returns an array of strings containing all keys that are not serializable.| ```ts -this.storage = new LocalStorage() -let simple = this.storage.keys() +let storage = new LocalStorage() +let simple = storage.keys() ``` ### size9+ @@ -575,8 +575,8 @@ Obtains the number of existing key-value pairs. | number | Returns the number of key-value pairs.| ```ts -this.storage = new LocalStorage() -let simple = this.storage.size() +let storage = new LocalStorage() +let simple = storage.size() ``` ### Clear9+ @@ -592,8 +592,8 @@ Deletes all attributes. | boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.| ```ts -this.storage = new LocalStorage() -let simple = this.storage.clear() +let storage = new LocalStorage() +let simple = storage.clear() ``` ## PersistentStorage @@ -612,7 +612,7 @@ Creates a **persistentstorage** object. | storage | Storage | Yes | **Storage** object. | ```ts -this.persistentstorage = new PersistentStorage(AppStorage,Storage) +let persistentstorage = new PersistentStorage(AppStorage,Storage) ``` ### PersistProp @@ -650,7 +650,7 @@ PersistentStorage.DeleteProp('highScore') ### PersistProps -PersistProps(properties: {key: string, defaultValue: any}[]): void; +PersistProps(properties: {key: string, defaultValue: any}[]): void Changes the attributes that match the specified keys to persistent data in the **AppStorage**. diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 0967cc433286589d8dcc7cdab305d1e5290b2193..d50f5ec504c3b9f215e033c4d33dd9dc48dba96d 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -16,7 +16,7 @@ You can draw an image around a component. | Name | Type | Description | | ---------- | ---------------------------------------- | --------------------------------------- | -| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image. | +| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.
**NOTE**
The border image source applies only to container components, such as **\**, **\**, and **\**.| | slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.
Default value: **0** | | width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.
Default value: **0** | | outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.
Default value: **0** | @@ -33,39 +33,31 @@ You can draw an image around a component. | Round | The source image's slices are tiled to fill the border box. Tiles may be compressed when needed.| | Space | The source image's slices are tiled to fill the border box. Extra space will be filled in between tiles. | - ## Example +### Example 1 + + ```ts // xxx.ets @Entry @Component struct Index { - @State outSetValue: number = 40 - build() { Row() { Column() { - Text('This is borderImage.').textAlign(TextAlign.Center).fontSize(50) + Text('This is gradient color.').textAlign(TextAlign.Center).height(50).width(200) .borderImage({ - source: $r('app.media.heart'), - slice: `${this.outSetValue}%`, - width: `${this.outSetValue}px`, - outset: '5px', - repeat: RepeatMode.Repeat, + source: { + angle: 90, + direction: GradientDirection.Left, + colors: [[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]] + }, + slice: { top: 10, bottom: 10, left: 10, right: 10 }, + width: { top: "10px", bottom: "10px", left: "10px", right: "10px" }, + repeat: RepeatMode.Stretch, fill: false }) - Slider({ - value: this.outSetValue, - min: 0, - max: 100, - style: SliderStyle.OutSet - }) - .margin({ top: 30 }) - .onChange((value: number, mode: SliderChangeMode) => { - this.outSetValue = value - console.info('value:' + value + 'mode:' + mode.toString()) - }) } .width('100%') } @@ -74,28 +66,42 @@ struct Index { } ``` -![en-us_image_borderImage](figures/borderImage.gif) +![en-us_image_borderImageGradient](figures/borderImageGradient.png) +### Example 2 ```ts // xxx.ets @Entry @Component struct Index { + @State outSetValue: number = 40 + build() { Row() { Column() { - Text('This is gradient color.').textAlign(TextAlign.Center).width(68) - .borderImage({ - source: { - angle: 90, - direction: GradientDirection.Left, - colors: [[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]] - }, - slice: { top: 10, bottom: 10, left: 10, right: 10 }, - width: { top: "10px", bottom: "10px", left: "10px", right: "10px" }, - repeat: RepeatMode.Stretch, - fill: false + Row() { + Text('This is borderImage.').textAlign(TextAlign.Center).fontSize(50) + } + .borderImage({ + source: $r('app.media.icon'), + slice: `${this.outSetValue}%`, + width: `${this.outSetValue}px`, + outset: '5px', + repeat: RepeatMode.Repeat, + fill: false + }) + + Slider({ + value: this.outSetValue, + min: 0, + max: 100, + style: SliderStyle.OutSet + }) + .margin({ top: 30 }) + .onChange((value: number, mode: SliderChangeMode) => { + this.outSetValue = value + console.info('value:' + value + 'mode:' + mode.toString()) }) } .width('100%') @@ -105,4 +111,4 @@ struct Index { } ``` -![en-us_image_borderImageGradient](figures/borderImageGradient.png) +![zh-cn_image_borderImage](figures/borderImage.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md index 53cc8c854b46f4acd7e8a51d618ad85595bb2d2e..7190a88277227e0fff0e94fc2ce6c6d8eeb954d8 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-focus.md @@ -48,6 +48,7 @@ Requests the focus to move to the specified component. This API can be used in g defaultFocus/groupDefaultFocus/focusOnTouch: **defaultFocus** sets the bound component as the initial focus of the page after the page is created. **groupDefaultFocus** sets the bound component as the initial focus of the **tabIndex** container after the container is created. **focusOnTouch** sets the bound component to obtain focus upon being clicked. + ```ts // focusTest.ets @Entry diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index 00099110825c5f1ba47594cf3ce9cd671f40f987..6fbaa35cdd66ca161b41999aedd1a2f06996f13d 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -12,7 +12,7 @@ Layout constraints refer to constraints on the aspect ratio and display priority | Name | Type | Description | | --------------- | ------ | ---------------------------------------- | | aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. | -| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components. | +| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components.| ## Example @@ -55,6 +55,7 @@ struct AspectRatioExample { Text(item) .backgroundColor(0xbbb2cb) .fontSize(40) + .height(160) .aspectRatio(1.5) } }, item => item) @@ -69,12 +70,10 @@ struct AspectRatioExample { } ``` -**Figure 1** Portrait display - +**Figure 1** Portrait display
![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif) -**Figure 2** Landscape display - +**Figure 2** Landscape display
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif) ```ts diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md index db1e33a8ed8e723c626e81fc4bbb6cd9915948fe..2ead12307d619826e4ae7ae26f29732df1302857 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md @@ -12,7 +12,7 @@ You can set the opacity of a component. | Name | Type | Description | | ------- | ---------------------------------------- | ---------------------------------------- | -| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout.
**NOTE**
A child component can inherit this attribute of its parent component. Default value: **1**| +| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout. Default value: **1**
**NOTE**
A component inherits the opacity setting from its parent component and multiplies it by its own setting. For example, if the opacity of a component is 0.8 and that of its parent component is 0.1, then the actual opacity of the component is 0.1 x 0.8 = 0.8.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 8330e79474aef2c523fadaf3677323c724e3570a..3fe2fd67e04bb818ccc5625f7f7d9d61e9347ea2 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -14,9 +14,9 @@ The text style attributes set the style for text in a component. | Name | Type | Description | | -----------| ---------------------------------------- | ------------------------------------ | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. | -| fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 10. This attribute cannot be set in percentage. | +| fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 16. This attribute cannot be set in percentage. | | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal** | -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in FontWeight.
Default value: **FontWeight.Normal** | +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal** | | fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
Default value: **'HarmonyOS Sans'**
Currently, only the default font is supported. | @@ -30,30 +30,24 @@ struct TextStyleExample { build() { Column({ space: 5 }) { Text('default text') - Divider() Text('text font color red').fontColor(Color.Red) - Divider() Text('text font default') Text('text font size 10').fontSize(10) Text('text font size 10fp').fontSize('10fp') Text('text font size 20').fontSize(20) - Divider() Text('text font style Italic').fontStyle(FontStyle.Italic) - Divider() Text('text fontWeight bold').fontWeight(700) Text('text fontWeight lighter').fontWeight(FontWeight.Lighter) - Divider() Text('red 20 Italic bold text') .fontColor(Color.Red) .fontSize(20) .fontStyle(FontStyle.Italic) .fontWeight(FontWeight.Bold) - Divider() Text('Orange 18 Normal text') .fontColor(Color.Orange) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md index 344fda5cd13ac94198bbe5e993d671122490028f..bf35ba4e5ee69b08d9621570b664af5ca6c0429e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md @@ -14,7 +14,7 @@ Transformation attributes allow you to rotate, translate, scale, or transform a | rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | Rotation axis. A positive angle indicates a clockwise rotation, and a negative angle indicates a counterclockwise rotation. The default value is **0**. **centerX** and **centerY** are used to set the rotation center point.
Default value:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
} | | translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | Translation distance along the x-, y-, and z-axis. The translation direction is determined by the positive and negative values. The value cannot be a percentage.
Default value:
{
x: 0,
y: 0,
z: 0
} | | scale | {
x?: number,
y?: number,
z?: number,
centerX?: number \| string,
centerY?: number \| string
} | Scale ratio along the x-, y-, and z-axis. The default value is **1**. **centerX** and **centerY** are used to set the scale center point.
Default value:
{
x: 1,
y: 1,
z: 1,
centerX:'50%',
centerY:'50%'
} | -| transform | Matrix4Transit | Transformation matrix of the component. | +| transform | [Matrix4Transit](../apis/js-apis-matrix4.md) | Transformation matrix of the component. | ## Example @@ -31,13 +31,13 @@ struct TransformExample { Text('rotate').width('90%').fontColor(0xCCCCCC).padding(15).fontSize(14) Row() .rotate({ - x: 1, - y: 1, + x: 0, + y: 0, z: 1, centerX: '50%', centerY: '50%', angle: 300 - }) // The component rotates around the center point of the rotation axis (1,1,1) clockwise by 300 degrees. + }) // The component rotates around the center point of the rotation axis (0,0,1) clockwise by 300 degrees. .width(100).height(100).backgroundColor(0xAFEEEE) Text('translate').width('90%').fontColor(0xCCCCCC).padding(10).fontSize(14) diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index be5c9602bb092bc06f992c8502d00e36dcb2a94a..7b89ff0c1414f229dc15a05fda291d4f52f7ed9f 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -32,8 +32,10 @@ - [reminderAgentManager Error Codes](errorcode-reminderAgentManager.md) - [workScheduler Error Codes](errorcode-workScheduler.md) - Security - - [Ability Access Control Error Codes](errorcode-access-token.md) + - [Ability Access Control Error Codes](errorcode-access-token.md) - [HUKS Error Codes](errorcode-huks.md) + - [Crypto Framework Error Codes](errorcode-crypto-framework.md) + - [Certificate Error Codes](errorcode-cert.md) - [User Authentication Error Codes](errorcode-useriam.md) - Data Management - [RDB Error Codes](errorcode-data-rdb.md) @@ -48,6 +50,7 @@ - Connectivity - [NFC Error Codes](errorcode-nfc.md) - [RPC Error Codes](errorcode-rpc.md) + - [Wi-Fi Error Codes](errorcode-wifi.md) - Basic Features - [Accessibility Error Codes](errorcode-accessibility.md) - [FaultLogger Error Codes](errorcode-faultlogger.md) @@ -57,6 +60,7 @@ - [Input Method Framework Error Codes](errorcode-inputmethod-framework.md) - [Pasteboard Error Codes](errorcode-pasteboard.md) - [Screen Lock Management Error Codes](errorcode-screenlock.md) + - [Time and Time Zone Service Error Codes](errorcode-time.md) - [Webview Error Codes](errorcode-webview.md) - Account Management - [Account Error Codes](errorcode-account.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md b/en/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md index 7c2246be4e0ad96b59bf22c8f5bb0cee9dcba2c6..2edb0dc58a5b83676839ec55eaa32c0c3af53bcc 100644 --- a/en/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md +++ b/en/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md @@ -58,7 +58,7 @@ Try again later or restart the device. **Error Message** -IPC communication failed. +IPC failed. **Description** @@ -94,7 +94,7 @@ Check whether the application exists. **Error Message** -Get application info failed. +Failed to get the application information. **Description** @@ -114,7 +114,7 @@ Check whether the input parameters are valid and whether the application exists. **Error Message** -Get system or actual time operation failed. +Failed to get the system time. **Description** @@ -132,7 +132,7 @@ Try again later or restart the device. **Error Message** -Application group operation failed. The application group are the the same or do not need te be updated. +Repeated operation on the application group. **Description** @@ -150,7 +150,7 @@ Do not repeatedly set application groups, or register or deregister a callback f **Error Message** -Get application group info failed. The application group infomation cannot be found. +Failed to get the application group information. **Description** diff --git a/en/application-dev/reference/errorcodes/errorcode-notification.md b/en/application-dev/reference/errorcodes/errorcode-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..9f1d5219020314fb4e8b945cda3b2435f67ac1eb --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-notification.md @@ -0,0 +1,219 @@ +# Notification Error Codes + +## 1600001 Internal Error + +**Error Message** + +Internal error. + +**Description** + +This error code is reported when an error occurs during internal processing, such as multi-thread processing or internal pointer checks. + +**Cause** + +Common kernel errors such as multi-thread processing and internal processing errors occur. + +**Solution** + +Make sure the system resources are sufficient. + +## 1600002 Marshalling or Unmarshalling Error + +**Error Message** + +marshalling or unmarshalling error. + +**Description** + +This error code is reported when a marshalling or unmarshalling error occurs before data transmission. + +**Cause** + +A parameter mismatch is detected between the application and the notification service. + +**Solution** + +Make sure the application SDK version matches the system version. + +## 1600003 Failed to Connect to the Notification Service + +**Error Message** + +Failed to connect service. + +**Description** + +This error code is reported when the application fails to connect to the notification service. + +**Cause** + +The notification service is busy or abnormal. + +**Solution** + +Restart the system. + +## 1600004 Notification Disabled + +**Error Message** + +Notification is not enabled. + +**Description** + +This error code is reported when notification is disabled. + +**Cause** + +The notification feature is not enabled for the application. + +**Solution** + +Enable notification for the application in the notification settings. + +## 1600005 Notification Slot Disabled + +**Error Message** + +Notification slot is not enabled. + +**Description** + +This error code is reported when the notification slot is not available. + +**Cause** + +The notification slot is disabled or has not been added. + +**Solution** + +1. Access the notification settings and check whether the application has the notification slot. If no, add it. + +2. Make sure the notification slot is enabled. + +## 1600006 Notification Deletion Failed + +**Error Message** + +Notification is not allowed to remove. + +**Description** + +This error code is reported when notification deletion is disabled. + +**Cause** + +The notification attribute **isUnremovable** is set to true. + +**Solution** + +Set **isUnremovable** as needed. For details, see [NotificationRequest](../apis/js-apis-notificationManager.md#notificationrequest). + +## 1600007 Notification Not Found + +**Error Message** + +The notification is not exist. + +**Description** + +This error code is reported when the notification service could not find the notification. + +**Cause** + +The notification has been canceled or deleted. + +**Solution** + +N/A + +## 1600008 User Not Found + +**Error Message** + +The user is not exist. + +**Description** + +This error code is reported when the specified user is not found in the information system. + +**Cause** + +The user information passed is incorrect. + +**Solution** + +Verify the user information. + +## 1600009 Notification Sending Limit Reached + +**Error Message** + +Over max number notifications per second. + +**Description** + +This error code is reported when the notification sending frequency reaches the upper limit. + +**Cause** + +More than 10 notifications are sent per second. + +**Solution** + +Reduce the notification sending frequency to no more than 10 per second. + +## 16000010 Distributed Operation Failed + +**Error Message** + +Distributed operation failed. + +**Description** + +This error code is reported when an error occurs with the distributed database operation or distributed API invoking. + +**Cause** + +The distributed database could not be operated or the distributed API could not be invoked. + +**Solution** + +Verify the distributed connection. + +## 16000011 Failed to Read the Template Configuration + +**Error Message** + +Read template config failed. + +**Description** + +This error code is reported when the attempt to read the template configuration file fails. + +**Cause** + +The template configuration file is lost in the system. + +**Solution** + +Check for the template configuration file: /system/etc/notification_template/external.json. + +## 16000012 Insufficient Memory Space + +**Error Message** + +No memory space. + +**Description** + +This error code is reported when a memory allocation error occurs. + +**Cause** + +A memory allocation error occurs. + +**Solution** + +Ensure sufficient system memory. diff --git a/en/application-dev/reference/errorcodes/errorcode-wifi.md b/en/application-dev/reference/errorcodes/errorcode-wifi.md new file mode 100644 index 0000000000000000000000000000000000000000..1d7443e49c03cc29f89c5b5d426eda752e7c36a7 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-wifi.md @@ -0,0 +1,124 @@ +# Wi-Fi Error Codes + +## 2401000 STA Internal Error + +**Error Message** + +Operation failed. + +**Description** + +An error occurs when the Wi-Fi service performs an operation related to the station (STA). + +**Possible Causes** + +1. Communication between the Wi-Fi service and the STA failed. +2. The Wi-Fi chip communication is abnormal. +3. An unknown error has occurred. + +**Solution** + +1. Disable and then enable the Wi-Fi function again. +2. If the error persists, restart the device. + +## 2501000 STA Internal Error + +**Error Message** + +Operation failed. + +**Description** + +An error occurs when the Wi-Fi service performs a STA-related operation. + +**Possible Causes** + +1. Communication between the Wi-Fi service and the STA failed. +2. The Wi-Fi chip communication is abnormal. +3. An unknown error has occurred. + +**Solution** + +1. Disable and then enable the Wi-Fi function again. +2. If the error persists, restart the device. + +## 2501001 STA Disabled + +**Error Message** + +Wifi is closed. + +**Description** + +The Wi-Fi STA function is disabled. + +**Possible Causes** + +The Wi-Fi function is disabled. + +**Solution** + +Enable the Wi-Fi function. + +## 2601000 Hotspot Module Error + +**Error Message** + +Operation failed. + +**Description** + +An error occurs when the Wi-Fi service performs a hotspot-related operation. + +**Possible Causes** + +1. Communication between the Wi-Fi service and the hotspot failed. +2. The Wi-Fi chip communication is abnormal. +3. An unknown error has occurred. + +**Solution** + +1. Disable and then enable the hotspot again. +2. If the error persists, restart the device. + +## 2701000 AP Extension Module Error + +**Error Message** + +Operation failed. + +**Description** + +An error occurs when the Wi-Fi service performs a hotspot-related operation. + +**Possible Causes** + +1. Communication between the Wi-Fi service and the hotspot failed. +2. The Wi-Fi chip communication is abnormal. +3. An unknown error has occurred. + +**Solution** + +1. Disable and then enable the hotspot again. +2. If the error persists, restart the device. + +## 2801000 P2P Module Error + +**Error Message** + +Operation failed. + +**Description** + +An error occurs when the Wi-Fi service performs a P2P-related operation. + +**Possible Causes** + +1. Communication with the Wi-Fi service failed. +2. The Wi-Fi chip communication is abnormal. +3. An unknown error has occurred. + +**Solution** + +1. Disable and then enable the Wi-Fi function again. +2. If the error persists, restart the device. diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index 1be1ec0532e899d933aaa672d3e49437c5822b68..65ee52d059ec38496df15214f669ed78f0252507 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -18,7 +18,7 @@ - Certificate - [Certificate Overview](cert-overview.md) - [Certificate Development](cert-guidelines.md) -- hapsigner +- hapsigner - [hapsigner Overview](hapsigntool-overview.md) - [hapsigner Guide](hapsigntool-guidelines.md) - [HarmonyAppProvision Configuration File](app-provision-structure.md) \ No newline at end of file diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md index 0ed590fbf850cfbbcac7e0c64ddcb0872d9d9353..0012db0fffb7538984e5b8168ec63ead567f3cc7 100644 --- a/en/application-dev/security/cryptoFramework-guidelines.md +++ b/en/application-dev/security/cryptoFramework-guidelines.md @@ -2,21 +2,18 @@ > **NOTE** > -> This development guide applies to API version 9, OpenHarmony SDK version 3.2.7 or later, and JS development. +> This guide applies to JS development using OpenHarmony API version 9 and SDK version 3.2.7 or later. -## Generating and Converting Keys +## Generating and Converting a Key **When to Use** Typical key generation operations involve the following: -1. Randomly create a key instance. This instance can be used for subsequent encryption and decryption. -2. Convert external or stored binary data into a key instance. This instance can be used for subsequent encryption and decryption. -3. Obtain the binary data of a key for storage or transmission. -> **NOTE** -> -> The key instance can be a symmetric key instance (**SymKey**) or an asymmetric key pair instance (**KeyPair**). The **KeyPair** instance consists a public key (PubKey) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). - +- Randomly create a key instance for subsequent encryption and decryption. +- Convert external or stored binary data into a key instance for subsequent encryption and decryption. +- Obtain the binary data of a key for storage or transmission. +> **NOTE**
The key instance can be a symmetric key instance (**SymKey**) or an asymmetric key pair instance (**KeyPair**). The **KeyPair** instance consists a public key (**PubKey**) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). **Available APIs** @@ -32,10 +29,10 @@ The table below describes the APIs used in this guide. |AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.| |SymKeyGenerator|generateSymKey(callback : AsyncCallback\) : void|Generates a symmetric key randomly. This API uses an asynchronous callback to return the result.| |SymKeyGenerator|generateSymKey() : Promise\|Generates a symmetric key randomly. This API uses a promise to return the result.| -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts the binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) | -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) | -| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts the binary data into a symmetric key. This API uses an asynchronous callback to return the result. | -| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts the binary data into a symmetric key. This API uses a promise to return the result. | +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.)| +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts binary data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.)| +| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts binary data into a symmetric key. This API uses an asynchronous callback to return the result.| +| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.| | Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)| **How to Develop** @@ -46,7 +43,7 @@ Example 1: Randomly generate an asymmetric key pair and obtain its binary data. 2. Randomly generate an asymmetric key pair using **AsyKeyGenerator**. 3. Obtain binary data of the key pair generated. -For example, randomly generate an RSA key (1024 bits and two primes) using promise-based APIs. +The following sample code presents how to randomly generate an RSA key (1024 bits and two primes) using promise-based APIs: ```javascript import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -75,7 +72,7 @@ Example 2: Randomly generate a symmetric key and obtain its binary data. 2. Randomly generate a symmetric key using **SymKeyGenerator**. 3. Obtain binary data of the key generated. -For example, randomly generate an AES key (256 bits) using promise-based APIs. +The following sample code presents how to randomly generate a 256-bit AES key using promise-based APIs: ```javascript import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -103,7 +100,7 @@ function testGenerateAesKey() { Example 3: Generate an asymmetric key pair from the binary RSA key data. 1. Obtain the binary data of the RSA public or private key. The public key must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. The private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -2. Create an **AsyKeyGenerator** instance and call **convertKey()** to convert the key binary data (data of the private or public key, or both) passed in to a **KeyPair** instance. +2. Create an **AsyKeyGenerator** instance and call **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. ```javascript import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -123,17 +120,19 @@ function convertAsyKey() { > **NOTE** > -> The public key returned by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key must be in the DER format complying with PKCS #8 specifications. +> The public key material to be converted in **convertKey()** must be in the DER format complying with X.509 specifications, and the private key material must be in the DER format complying with PKCS #8 specifications. - Example 4: Generate an asymmetric key pair from the binary ECC key data. + + +Example 4: Generate an asymmetric key pair from the binary ECC key data. 1. Obtain the ECC binary key data and encapsulate it into a **DataBlob** instance. -2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) passed in to a **KeyPair** instance. +2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) into to a **KeyPair** instance. ```javascript function convertEccAsyKey() { - let pubKeyArray = new Uint8Array([4,196,55,233,100,227,224,38,38,5,128,81,53,112,129,7,59,189,116,105,182,87,190,85,31,248,172,116,213,7,206,85,190,65,169,193,138,173,232,187,74,54,78,251,29,131,192,223,251,227,170,138,80,7,98,193,216,168,235,114,255,188,70,134,104]); - let priKeyArray = new Uint8Array([255,70,89,220,189,19,41,157,175,173,83,60,74,216,195,96,24,181,231,23,112,247,150,126,15,155,24,79,33,97,31,225]); + let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); + let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,115,56,137,35,207,0,60,191,90,61,136,105,210,16,27,4,171,57,10,61,123,40,189,28,34,207,236,22,45,223,10,189,160,10,6,8,42,134,72,206,61,3,1,7]); let pubKeyBlob = { data: pubKeyArray }; let priKeyBlob = { data: priKeyArray }; let generator = cryptoFrameWork.createAsyKeyGenerator("ECC256"); @@ -146,13 +145,13 @@ function convertEccAsyKey() { } ``` -Example 5: Generate a symmetric key from binary key data. +Example 5: Generate a symmetric key from binary data. 1. Create a **SymKeyGenerator** instance. 2. Generate a symmetric key from the binary data passed in. 3. Obtain binary data of the key generated. -For example, generate a 3DES key (192 bits only) using callback-based APIs. +The following sample code presents how to generate a 3DES key (192 bits only) using callback-based APIs: ```javascript import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -201,12 +200,12 @@ function testConvertAesKey() { **When to Use** Important data needs to be encrypted in data storage or transmission for security purposes. Typical encryption and decryption operations involve the following: -1. Encrypt and decrypt data using a symmetric key. -2. Encrypt and decrypt data using an asymmetric key pair. +- Encrypt and decrypt data using a symmetric key. +- Encrypt and decrypt data using an asymmetric key pair. **Available APIs** -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
Due to the complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs in the API reference to ensure correct use of these APIs. The table below describes the APIs used in this guide. @@ -229,7 +228,7 @@ Example 1: Encrypt and decrypt data using a symmetric key. 3. Create a **Cipher** instance. 4. Encrypt or decrypt data. -For example, use AES GCM to encrypt and decrypt data using promise-based APIs. +The following sample code presents how to use the AES-GCM to encrypt and decrypt data with promise-based APIs: ```js import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -250,8 +249,9 @@ function genGcmParamsSpec() { arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes let dataTag = new Uint8Array(arr); - let tagBlob = {data : dataTag}; - let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algoName : "GcmParamsSpec"}; + let tagBlob = {data : dataTag}; // The authTag of GCM is obtained by doFinal() in encryption and passed in params of init() in decryption. + + let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algName : "GcmParamsSpec"}; return gcmParamsSpec; } @@ -298,8 +298,8 @@ function testAesGcm() { }, 10) }).then(() => { // Create a SymKeyGenerator instance. - let symAlgoName = 'AES128'; - let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); + let symAlgName = 'AES128'; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); if (symKeyGenerator == null) { console.error('createSymKeyGenerator failed'); return; @@ -311,9 +311,9 @@ function testAesGcm() { globalGcmParams = genGcmParamsSpec(); // Create a Cipher instance. - let cipherAlgoName = 'AES128|GCM|PKCS7'; + let cipherAlgName = 'AES128|GCM|PKCS7'; try { - globalCipher = cryptoFramework.createCipher(cipherAlgoName); + globalCipher = cryptoFramework.createCipher(cipherAlgName); console.info(`cipher algName: ${globalCipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); @@ -339,7 +339,7 @@ function testAesGcm() { let promiseFinal = globalCipher.doFinal(null); // doFinal return promiseFinal; }).then(authTag => { - // Obtain the authentication information after encryption. + // In GCM mode, the encrypted authentication information needs to be obtained from the output of doFinal() and passed in globalGcmParams of init() in decryption. globalGcmParams.authTag = authTag; return; }).then(() => { @@ -355,7 +355,7 @@ function testAesGcm() { let promiseFinal = globalCipher.doFinal(null); // doFinal return promiseFinal; }).then(finalOutput => { - if (finalOutput == null) { + if (finalOutput == null) { // Check whether the result is null before using finalOutput.data. console.info('GCM finalOutput is null'); } }).catch(error => { @@ -364,7 +364,7 @@ function testAesGcm() { } ``` -For example, 3DES ECB is used. Generate a key from the existing data to encrypt and decrypt data using callback-based APIs. +The following sample code presents how to use the the 3DES ECB to convert existing data into a key and encrypt and decrypt data using callback-based APIs: ```js import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -408,11 +408,11 @@ function genKeyMaterialBlob() { return {data : keyMaterial}; } -// For example, 3DES ECB is used. Use existing data to generate a key to encrypt and decrypt data, and return the result in a callback. +// Use the 3DES ECB to Generate a key from the existing data and encrypt and decrypt data using callback-based APIs. function test3DesEcb() { // Create a SymKeyGenerator instance. - let symAlgoName = '3DES192'; - let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); + let symAlgName = '3DES192'; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); if (symKeyGenerator == null) { console.error('createSymKeyGenerator failed'); return; @@ -420,9 +420,9 @@ function test3DesEcb() { console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); // Create a Cipher instance. - let cipherAlgoName = '3DES192|ECB|PKCS7'; + let cipherAlgName = '3DES192|ECB|PKCS7'; try { - globalCipher = cryptoFramework.createCipher(cipherAlgoName); + globalCipher = cryptoFramework.createCipher(cipherAlgName); console.info(`cipher algName: ${globalCipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); @@ -473,7 +473,7 @@ function test3DesEcb() { console.info('decrypt plainText: ' + uint8ArrayToString(updateOutput.data)); // doFinal globalCipher.doFinal(null, (error, finalOutput) => { - if (finalOutput != null) { + if (finalOutput == null) { // Check whether the result is null before using finalOutput.data. console.info("decrypt plainText:" + uint8ArrayToString(finalOutput.data)); } }) @@ -489,12 +489,153 @@ function test3DesEcb() { } } ``` +The following sample code presents how to call **update()** multiple times to implement AES GCM encryption and decryption by using promise-based APIs: + +```javascript +import cryptoFramework from '@ohos.security.cryptoFramework'; + +var globalCipher; +var globalGcmParams; +var globalKey; +var globalCipherText; +var globalPlainText; + +function genGcmParamsSpec() { + let arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0 , 0, 0]; // 12 bytes + let dataIv = new Uint8Array(arr); + let ivBlob = {data : dataIv}; + + arr = [0, 0, 0, 0 , 0, 0, 0, 0]; // 8 bytes + let dataAad = new Uint8Array(arr); + let aadBlob = {data : dataAad}; + + arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes + let dataTag = new Uint8Array(arr); + let tagBlob = {data : dataTag}; + let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algName : "GcmParamsSpec"}; + return gcmParamsSpec; +} + +// Output the byte streams in hexadecimal format. +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +// Convert byte streams into strings in plaintext. +function uint8ArrayToString(array) { + let arrayString = ''; + for (let i = 0; i < array.length; i++) { + arrayString += String.fromCharCode(array[i]); + } + return arrayString; +} + +// The algorithm library does not limit the number of update() times and the amount of data to be encrypted and decrypted each time. You can use update() multiple times based on the memory usage. +function testAesMultiUpdate() { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve('testAesMultiUpdate'); + }, 10) + }).then(() => { + // Create a SymKeyGenerator instance. + let symAlgName = 'AES128'; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); + if (symKeyGenerator == null) { + console.error('createSymKeyGenerator failed'); + return; + } + console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); + // Use the key generator to randomly generate a 128-bit symmetric key. + let promiseSymKey = symKeyGenerator.generateSymKey(); + // Constructor + globalGcmParams = genGcmParamsSpec(); + + // Create a Cipher instance. + let cipherAlgName = 'AES128|GCM|PKCS7'; + try { + globalCipher = cryptoFramework.createCipher(cipherAlgName); + console.info(`cipher algName: ${globalCipher.algName}`); + } catch (error) { + console.error(`createCipher failed, ${error.code}, ${error.message}`); + return; + } + return promiseSymKey; + }).then(key => { + let encodedKey = key.getEncoded(); + console.info('key hex:' + uint8ArrayToShowStr(encodedKey.data)); + globalKey = key; + return key; + }).then(key => { + // Initialize the cipher environment and start encryption. + let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE; + let promiseInit = globalCipher.init(mode, key, globalGcmParams); // init + return promiseInit; + }).then(async () => { + let plainText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the plaintext contains 43 bytes. + let messageArr = []; + let updateLength = 20; // Pass in 20 bytes by update() each time. + globalCipherText = []; + + for (let i = 0; i <= plainText.length; i++) { + if ((i % updateLength == 0 || i == plainText.length) && messageArr.length != 0) { + let message = new Uint8Array(messageArr); + let messageBlob = { data : message }; + let updateOutput = await globalCipher.update(messageBlob); // Update by segment. + // Combine the result of each update() to obtain the ciphertext. In certain cases, the doFinal() results need to be combined, which depends on the cipher block mode + // and padding mode you use. In this example, the doFinal() result in GCM mode contains authTag but not ciphertext. Therefore, there is no need to combine the results. + globalCipherText = globalCipherText.concat(Array.from(updateOutput.data)); + messageArr = []; + } + if (i < plainText.length) { + messageArr.push(plainText.charCodeAt(i)); + } + } + return; + }).then(() => { + let promiseFinal = globalCipher.doFinal(null); // doFinal + return promiseFinal; + }).then(authTag => { + // Obtain the authentication information after encryption. + globalGcmParams.authTag = authTag; + return; + }).then(() => { + // Initialize the cipher environment and start decryption. + let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; + let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init + return promiseInit; + }).then(async () => { + let updateLength = 20; + let updateTimes = Math.ceil(globalCipherText.length / updateLength); // Round up to the nearest integer. + globalPlainText = ""; + for (let i = 0; i < updateTimes; i++) { + let messageArr = globalCipherText.slice(i * updateLength, (i + 1) * updateLength); + let message = new Uint8Array(messageArr); + let messageBlob = { data : message }; + let updateOutput = await globalCipher.update(messageBlob); // Pass in data by segment. + globalPlainText += uint8ArrayToString(updateOutput.data); // Restore the original plaintext. + } + return; + }).then(() => { + let promiseFinal = globalCipher.doFinal(null); // doFinal + return promiseFinal; + }).then(finalOutput => { + if (finalOutput == null) { + console.info('GCM finalOutput is null'); + } + console.info(`decrypt output: ${globalPlainText}`); + }).catch(error => { + console.error(`catch error, ${error.code}, ${error.message}`); + }) +} +``` Example 2: Encrypt and decrypt data using an asymmetric key pair. -1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. -2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. -3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. +3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -538,25 +679,166 @@ function encryptMessageCallback() { }) }) } + +function decryptMessageProMise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + let decoder = cryptoFramework.createCipher("RSA1024|PKCS1"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + let keyPair; + let cipherDataBlob; + let input = { data : stringToUint8Array(plan) }; + keyGenPromise.then(rsaKeyPair => { + keyPair = rsaKeyPair; + return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); + }).then(() => { + return cipher.doFinal(input); + }).then(dataBlob => { + console.info("EncryptOutPut is " + dataBlob.data); + AlertDialog.show({message : "output" + dataBlob.data}); + cipherDataBlob = dataBlob; + return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null); + }).then(() => { + return decoder.doFinal(cipherDataBlob); + }).then(decodeData => { + if (decodeData.data.toString() === input.data.toString()) { + AlertDialog.show({message : "decrypt success"}); + return; + } + AlertDialog.show({message : "decrypt fail"}); + }); +} + +function decryptMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + let decoder = cryptoFramework.createCipher("RSA1024|PKCS1"); + let plainText = "this is cipher text"; + let input = {data : stringToUint8Array(plainText) }; + let cipherData; + let keyPair; + rsaGenerator.generateKeyPair(function (err, newKeyPair) { + keyPair = newKeyPair; + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, function (err, data) { + cipher.doFinal(input, function (err, data) { + AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); + cipherData = data; + decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, function (err, data) { + decoder.doFinal(cipherData, function (err, data) { + if (input.data.toString() === data.data.toString()) { + AlertDialog.show({ message : "decrype success"} ); + return; + } + AlertDialog.show({ message : "decrype fail"} ); + }); + }); + }); + }); + }); +} +``` +The following sample code presents how to implement RSA asymmetric encryption and decryption (**doFinal()** is called multiple times): +```javascript +import cryptoFramework from "@ohos.security.cryptoFramework" + +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +// Convert byte streams into strings in plaintext. +function uint8ArrayToString(array) { + let arrayString = ''; + for (let i = 0; i < array.length; i++) { + arrayString += String.fromCharCode(array[i]); + } + return arrayString; +} + +function encryptLongMessagePromise() { + let globalPlainText = "This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!"; + let globalCipherOutput; + let globalDecodeOutput; + var globalKeyPair; + let plainTextSplitLen = 64; // The length of the plaintext to be encrypted or decrypted each time by RSA depends on the number of key bits and padding mode. For details, see the Crypto Framework Overview. + let cipherTextSplitLen = 128; // Length of the ciphertext = Number of key bits/8 + let keyGenName = "RSA1024"; + let cipherAlgName = "RSA1024|PKCS1"; + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // Create an AsyKeyGenerator object. + let cipher = cryptoFramework.createCipher(cipherAlgName); // Create a Cipher object. + let decoder = cryptoFramework.createCipher(cipherAlgName); // Create a Decoder object. + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve("testRsaMultiDoFinal"); + }, 10); + }).then(() => { + return asyKeyGenerator.generateKeyPair(); // Generate an RSA key. + }).then(keyPair => { + globalKeyPair = keyPair; // Save the key to global variables. + return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null); + }).then(async () => { + globalCipherOutput = []; + // Split the plaintext by 64 characters and cyclically call doFinal() to encrypt the plaintext. If a 1024-bit key is used, 128-byte ciphertext is generated each time. + for (let i = 0; i < (globalPlainText.length / plainTextSplitLen); i++) { + let tempStr = globalPlainText.substr(i * plainTextSplitLen, plainTextSplitLen); + let tempBlob = { data : stringToUint8Array(tempStr) }; + let tempCipherOutput = await cipher.doFinal(tempBlob); + globalCipherOutput = globalCipherOutput.concat(Array.from(tempCipherOutput.data)); + } + console.info(`globalCipherOutput len is ${globalCipherOutput.length}, data is: ${globalCipherOutput.toString()}`); + return; + }).then(() =>{ + return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, globalKeyPair.priKey, null); + }).then(async() => { + globalDecodeOutput = []; + // Split and decrypt the ciphertext by 128 bytes, and combine the plaintext obtained each time. + for (let i = 0; i < (globalCipherOutput.length / cipherTextSplitLen); i++) { + let tempBlobData = globalCipherOutput.slice(i * cipherTextSplitLen, (i + 1) * cipherTextSplitLen); + let message = new Uint8Array(tempBlobData); + let tempBlob = { data : message }; + let tempDecodeOutput = await decoder.doFinal(tempBlob); + globalDecodeOutput += uint8ArrayToString(tempDecodeOutput.data); + } + if (globalDecodeOutput === globalPlainText) { + console.info(`encode and decode success`); + } else { + console.info(`encode and decode error`); + } + return; + }).catch(error => { + console.error(`catch error, ${error.code}, ${error.message}`); + }) +} ``` > **NOTE** > -> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each of encryption and decryption. -> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Crypto Framework Overview](cryptoFramework-overview.md). +> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each encryption and decryption. +> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Cryptographic Framework Overview](cryptoFramework-overview.md). > - In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. -## Signing Data and Verifying Signatures +## Generating and Verifying a Signature **When to Use** A digital signature can be used to verify the authenticity of a message. Typical signing and signature verification operations involve the following: -- Use RSA to sign data and verify the signature. -- Use ECC to sign data and verify the signature. +- Use the RSA to generate and verify a signature. +- Use the ECC to generate and verify a signature. **Available APIs** -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
Due to the complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs in the API reference to ensure correct use of these APIs. |Instance|API|Description| |---|---|---| @@ -577,12 +859,12 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry **How to Develop** -Example 1: Use RSA to sign data and verify the signature. -1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. -2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. -3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. -4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. -5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. +Example 1: Use the RSA to generate and verify a signature. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -661,12 +943,12 @@ function verifyMessageCallback() { } ``` -Example 2: Using ECC to sign data and verify the signature. -1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. -2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. -3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. -4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. -5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. +Example 2: Use the ECDSA to generate and verify a signature. +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -745,18 +1027,85 @@ function verifyMessageCallback() { }) } ``` +The following sample code presents how to call **update()** multiple times to implement signing and signature verification: + +```javascript +import cryptoFramework from "@ohos.security.cryptoFramework" + +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +function signLongMessagePromise() { + let globalPlainText = "This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!" + + "This is a long plainTest! This is a long plainTest! This is a long plainTest! This is a long plainTest!"; + let globalSignData; + let textSplitLen = 64; // Customized data splitting length. + let keyGenName = "RSA1024"; + let cipherAlgName = "RSA1024|PKCS1|SHA256"; + let globalKeyPair; + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // Create an AsyKeyGenerator object. + let signer = cryptoFramework.createSign(cipherAlgName); //Create a cipher object for encryption. + let verifier = cryptoFramework.createVerify(cipherAlgName); // Create a Decoder object for decryption. + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve("testRsaMultiUpdate"); + }, 10); + }).then(() => { + return asyKeyGenerator.generateKeyPair(); // Generate an RSA key. + }).then(keyPair => { + globalKeyPair = keyPair; // Save the key to global variables. + return signer.init(globalKeyPair.priKey); + }).then(async () => { + // If the plaintext is too large, split the plaintext based on the specified length and cyclically call update() to pass in the plaintext. + for (let i = 0; i < (globalPlainText.length / textSplitLen); i++) { + let tempStr = globalPlainText.substr(i * textSplitLen, textSplitLen); + let tempBlob = { data : stringToUint8Array(tempStr) }; + await signer.update(tempBlob); + } + return signer.sign(null); + }).then(data =>{ + globalSignData = data.data; + console.info(`globalSignOutput len is ${globalSignData.length}, data is: ${globalSignData.toString()}`); + return verifier.init(globalKeyPair.pubKey); + }).then(async() => { + // Split and decrypt the ciphertext by 128 bytes, and combine the plaintext obtained each time. + for (let i = 0; i < (globalPlainText.length / textSplitLen); i++) { + let tempData = globalPlainText.slice(i * textSplitLen, (i + 1) * textSplitLen); + let tempBlob = { data : stringToUint8Array(tempData) }; + await verifier.update(tempBlob); + } + return verifier.verify(null, { data : globalSignData}); + }).then(res => { + console.info(`verify res is ${res}`); + }).catch(error => { + console.error(`catch error, ${error.code}, ${error.message}`); + }) +} +``` ## Generating a Digest **When to Use** -A message digest is a fixed size numeric representation of the content of a message, computed by a has function. The message digest is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified. +A message digest (MD) is a fixed size numeric representation of the content of a message, computed by a has function. It is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified. -Typical message digest operations involve the following: +Typical MD operations involve the following: 1. Create an **Md** instance. 2. Add one or more segments of data for generating a digest. -3. Compute a digest. +3. Compute a digest. 4. Obtain the algorithm and length of a digest. **Available APIs** @@ -776,7 +1125,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry **How to Develop** 1. Call **createMd()** to create an **Md** instance. -2. Call **update()** to update the data for computing a digest. **update()** can be called multiple times to update the data by segment. +2. Call **update()** to pass in the data for computing a digest. **update()** can be called multiple times to pass in the data by segment. 3. Call **digest()** to compute a digest. 4. Obtain the digest algorithm and length of the digest generated. @@ -805,7 +1154,7 @@ function GenDataBlob(dataBlobLen) { return dataBlob; } -// Compute a message digest using promise-based APIs. +// Compute an MD using promise-based APIs. function doMdByPromise(algName) { var md; try { @@ -814,8 +1163,13 @@ function doMdByPromise(algName) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("[Promise]: Md algName is: " + md.algName); + // Initial update(). var promiseMdUpdate = md.update(GenDataBlob(12)); promiseMdUpdate.then(() => { + // Call update() multiple times based on service requirements. + promiseMdUpdate = md.update(GenDataBlob(12)); + return promiseMdUpdate; + }).then(mdOutput => { var PromiseMdDigest = md.digest(); return PromiseMdDigest; }).then(mdOutput => { @@ -827,7 +1181,7 @@ function doMdByPromise(algName) { }); } -// Compute a message digest using callback-based APIs. +// Compute an MD using callback-based APIs. function doMdByCallback(algName) { var md; try { @@ -836,22 +1190,86 @@ function doMdByCallback(algName) { console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } console.error("[Callback]: Md algName is: " + md.algName); + // Initial update(). md.update(GenDataBlob(12), (err,) => { if (err) { console.error("[Callback]: err: " + err.code); } - md.digest((err1, mdOutput) => { + // Call update() multiple times based on service requirements. + md.update(GenDataBlob(12), (err1,) => { if (err1) { console.error("[Callback]: err: " + err1.code); - } else { - console.error("[Callback]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Callback]: MD len: " + mdLen); } + md.digest((err2, mdOutput) => { + if (err2) { + console.error("[Callback]: err: " + err2.code); + } else { + console.error("[Callback]: MD result: " + mdOutput.data); + var mdLen = md.getMdLength(); + console.error("[Callback]: MD len: " + mdLen); + } + }); }); }); } ``` +The following sample code presents how to call **update()** multiple times to update the MD: +```javascript +import cryptoFramework from "@ohos.security.cryptoFramework" + +async function updateData(index, obj, data) { + console.error("update " + (index + 1) + " MB data..."); + return obj.update(data); +} + +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +function GenDataBlob(dataBlobLen) { + var dataBlob; + if (dataBlobLen == 12) { + dataBlob = {data: stringToUint8Array("my test data")}; + } else { + console.error("GenDataBlob: dataBlobLen is invalid"); + dataBlob = {data: stringToUint8Array("my test data")}; + } + return dataBlob; +} + +function LoopMdPromise(algName, loopSize) { + var md; + try { + md = cryptoFramework.createMd(algName); + } catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); + return; + } + console.error("[Promise]: Md algName is: " + md.algName); + var promiseMdUpdate = md.update(GenDataBlob(12)); + promiseMdUpdate.then(() => { + var PromiseMdDigest = md.digest(); + return PromiseMdDigest; + }).then(async () => { + for (var i = 0; i < loopSize; i++) { + await updateData(i, md, GenDataBlob(12)); + } + var PromiseMdDigest = md.digest(); + return PromiseMdDigest; + }).then(mdOutput => { + console.error("[Promise]: MD result: " + mdOutput.data); + var mdLen = md.getMdLength(); + console.error("[Promise]: MD len: " + mdLen); + }).catch(error => { + console.error("[Promise]: error: " + error.message); + }); +} +``` ## Performing Key Agreement @@ -871,7 +1289,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry **How to Develop** -1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. 2. Generate a shared secret by using the private and public ECC keys. ```javascript @@ -970,7 +1388,6 @@ function GenDataBlob(dataBlobLen) { return dataBlob; } -// Generate a MAC using promise-based APIs. function doHmacByPromise(algName) { var mac; try { @@ -988,6 +1405,11 @@ function doHmacByPromise(algName) { var promiseMacInit = mac.init(symKey); return promiseMacInit; }).then(() => { + // Initial update(). + var promiseMacUpdate = mac.update(GenDataBlob(12)); + return promiseMacUpdate; + }).then(() => { + // Call update() multiple times based on service requirements. var promiseMacUpdate = mac.update(GenDataBlob(12)); return promiseMacUpdate; }).then(() => { @@ -1023,35 +1445,105 @@ function doHmacByCallback(algName) { if (err1) { console.error("[Callback]: err: " + err1.code); } + // Initial update(). mac.update(GenDataBlob(12), (err2, ) => { if (err2) { console.error("[Callback]: err: " + err2.code); } - mac.doFinal((err3, macOutput) => { + // Call update() multiple times based on service requirements. + mac.update(GenDataBlob(12), (err3, ) => { if (err3) { console.error("[Callback]: err: " + err3.code); - } else { - console.error("[Callback]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Callback]: MAC len: " + macLen); } + mac.doFinal((err4, macOutput) => { + if (err4) { + console.error("[Callback]: err: " + err4.code); + } else { + console.error("[Callback]: HMAC result: " + macOutput.data); + var macLen = mac.getMacLength(); + console.error("[Callback]: MAC len: " + macLen); + } + }); }); }); }); }); } ``` +The following sample code presents how to call **update()** multiple times to update the MAC: +```javascript +import cryptoFramework from "@ohos.security.cryptoFramework" + +async function updateData(index, obj, data) { + console.error("update " + (index + 1) + " MB data..."); + return obj.update(data); +} + +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; +} + +function GenDataBlob(dataBlobLen) { + var dataBlob; + if (dataBlobLen == 12) { + dataBlob = {data: stringToUint8Array("my test data")}; + } else { + console.error("GenDataBlob: dataBlobLen is invalid"); + dataBlob = {data: stringToUint8Array("my test data")}; + } + return dataBlob; +} +function LoopHmacPromise(algName, loopSize) { + var mac; + try { + mac = cryptoFramework.createMac(algName); + } catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); + return; + } + console.error("[Promise]: Mac algName is: " + mac.algName); + var KeyBlob = { + data : stringToUint8Array("12345678abcdefgh") + } + var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); + promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; + }).then(async () => { + for (var i = 0; i < loopSize; i++) { + await updateData(i, mac, GenDataBlob(12)); + } + var promiseMacUpdate = mac.update(GenDataBlob(12)); + return promiseMacUpdate; + }).then(() => { + var PromiseMacDoFinal = mac.doFinal(); + return PromiseMacDoFinal; + }).then(macOutput => { + console.error("[Promise]: HMAC result: " + macOutput.data); + var macLen = mac.getMacLength(); + console.error("[Promise]: MAC len: " + macLen); + }).catch(error => { + console.error("[Promise]: error: " + error.message); + }); +} +``` -## Generating Random Numbers +## Generating a Random Number **When to Use** Typical random number operations involve the following: -1. Generate a random number. -2. Set a seed based on the random number generated. +- Generate a random number. +- Set a seed based on the random number generated. **Available APIs** diff --git a/en/application-dev/security/cryptoFramework-overview.md b/en/application-dev/security/cryptoFramework-overview.md index c8b92f162e7186f4a593d220ef0e9acc94d884b9..72bbb1148908d177498d54cfc9585c12b3b1d73f 100644 --- a/en/application-dev/security/cryptoFramework-overview.md +++ b/en/application-dev/security/cryptoFramework-overview.md @@ -1,16 +1,16 @@ # Crypto Framework Overview -The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hashes, and secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. +The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, and operations of the message authentication code (MAC), hashes, and secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. > **NOTE** > -> The crypto framework provides cryptographic operations on keys, but not key management. It is used when the application keeps the key (for example, temporary session keys are used only in the memory or the application implements secure key storage). If the system is required to provide key management (such as key storage), use the [HUKS](huks-overview.md). +> The crypto framework provides cryptographic operations on keys, but not key management. It is used when the application keeps the key securely (for example, temporary session keys are used only in the memory or the application implements secure key storage). If the system is required to provide key management (such as key storage), use the [HUKS](huks-overview.md). ## Working Principles The crypto framework provides components in the following layers: - Interface layer: provides unified JS interface externally. -- Framework layer: implements third-party algorithm libraries. -- Plug-in layer: loads plug-ins at the plug-in layer to adapt to third-party algorithm libraries and shield implementation differences between these libraries. +- Plug-in layer: implements third-party algorithm libraries. +- Framework layer: loads plug-ins at the plug-in layer to adapt to third-party algorithm libraries and shield implementation differences between these libraries. ## Basic Concepts **Symmetric Key** @@ -30,7 +30,7 @@ In the asymmetric cryptography, a private and public key pair is required. The p - RSA key - The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows:
+ The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows: 1. Generate two large prime numbers **p** and **q**. @@ -40,8 +40,7 @@ In the asymmetric cryptography, a private and public key pair is required. The p 3. Choose an integer **e** such that 1 < **e** < (**p** - 1) x (**q** - 1), that is, **e** and (**p** - 1) x (**q** - 1) are coprime. - 4. Compute **d**.
**e** x **d** - 1 is a multiple of (**p** - 1) and (**q** - 1). - + 4. Compute **d**. **e** x **d** - 1 is a multiple of (**p** - 1) and (**q** - 1). The public key consists of the modulus **n** and the public exponent **e**. The private key consists of **n** and the private exponent **d**. @@ -57,51 +56,53 @@ In the asymmetric cryptography, a private and public key pair is required. The p The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes + - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - - - > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 128 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. + > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 128 bits. Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. - **Symmetric 3DES Encryption and Decryption** 3DES encryption and decryption apply the DES cipher three times to each data block to obtain the ciphertext or plaintext. The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: - - **NoPadding**: no padding. - - - **PKCS5**: pads a block cipher with a block size of 8 bytes - - - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - + - **NoPadding**: no padding. + - **PKCS5**: pads a block cipher with a block size of 8 bytes + - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 64 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. - **Asymmetric RSA Encryption and Decryption** - After the RSA public key (n, e) and private key (n, d) are held, the RSA encryption process is as follows:
Ciphertext = Plaintext ^ **e** mod **n**
The decryption process is as follows:
Plaintext = Ciphertext ^ **d** mod **n** + After the RSA public key (n, e) and private key (n, d) are held, the RSA encryption process is as follows: + + Ciphertext = Plaintext ^ **e** mod **n** + + The decryption process is as follows: + + Plaintext = Ciphertext ^ **d** mod **n** The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: - **NoPadding**: No padding is required. The length of the input or output data must be the same as that of the RSA key modulus. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. The length of the input data must be less than or equal to the RSA key modulus minus 11, and the length of the output data must be the same as that of the RSA key modulus. - - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus the **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - > **NOTE** - > - > Length of the RSA key modulus = (Number of RSA bits + 7)/8 + > **NOTE** + > + > Length of the RSA key modulus = (Number of RSA bits + 7)/8 **Signing and Signature Verification** - RSA signing and signature verification - After the RSA public key (n, e) and private key (n, d) are held, the RSA signature is generated as follows:
Signature = Message ^ **d** mod **n**
The signature verification process is as follows:
Message = Signature ^ **d** mod **n** + After the RSA public key (n, e) and private key (n, d) are held, the RSA signature is generated as follows: + + Signature = Message ^ **d** mod **n** + + The signature verification process is as follows: + + Message = Signature ^ **d** mod **n** The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest before signing the message. The crypto framework provides the following padding modes for signing and signature verification: @@ -128,9 +129,7 @@ When the same digest algorithm is used, the generated digest (hash value) has th - It is almost impossible to find two different messages with the same hash value. (The probability still exists, depending on the length of the digest.) There are three types of message digest algorithms: MD, SHA, and MAC. For details, see **HMAC**. - MD algorithms include MD2, MD4, and MD5. - Major SHA algorithms include SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. **HMAC** @@ -222,9 +221,8 @@ Random numbers are mainly used to generate temporary session keys or keys in asy |AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| > **NOTE** -> +> > - The options included in the square brackets ([]) are mutually exclusive. -> > - **String Parameter** is a combination of **Algorithm** (including the key length), **Block Cipher Mode**, and padding mode. It specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. **Asymmetric RSA Encryption and Decryption** @@ -263,45 +261,45 @@ The crypto framework provides three padding modes for RSA encryption/decryption: | Asymmetric Key Type| Padding Mode| Digest| Mask Digest| |---|---|---|---| |RSA512|PKCS1_OAEP|MD5| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| +|RSA512|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA512|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA512|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| |RSA768|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA768|PKCS1_OAEP|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA768|PKCS1_OAEP|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| +|RSA768|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA768|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA768|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| +|RSA768|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA768|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| |RSA1024|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| +|RSA1024|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| |RSA2048|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| |RSA3072|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| |RSA4096|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| |RSA8192|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512 ]| -|RSA8192|PKCS1_OAEP|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512 ]| +|RSA8192|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| ### Signing and Signature Verification Specifications @@ -325,51 +323,50 @@ The crypto framework provides two padding modes for RSA signing and signature ve > **NOTE** > > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. - > - > - Combine the asymmetric key type, padding mode, digest, and mask digest, with a vertical bar (|) in between. For example, **RSA2048|PSS|SHA256|MGF1_SHA256**. - - | Asymmetric Key Type| Padding Mode| Digest| Mask Digest| - |---|---|---|---| - |RSA512|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| - |RSA512|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| - |RSA512|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| - |RSA512|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]|RSA512\|PSS\|SHA256\|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| - |RSA768|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA768|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA768|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA768|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| - |RSA768|PSS|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| - |RSA768|PSS|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| - |RSA1024|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA1024|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA1024|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA1024|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA1024|PSS|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA1024|PSS|SHA-512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| - |RSA2048|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA2048|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA2048|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA2048|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA2048|PSS|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA2048|PSS|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA3072|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA3072|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA3072|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA3072|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA3072|PSS|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA3072|PSS|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA4096|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA4096|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA4096|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA4096|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA4096|PSS|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA4096|PSS|SHA-512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA8192|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA8192|PSS|SHA-1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA8192|PSS|SHA-224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA8192|PSS|SHA-256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA8192|PSS|SHA-384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - |RSA8192|PSS|SHA-512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + > - Combine the asymmetric key type, padding mode, digest, and mask digest, with a vertical bar (|) in between. For example, **RSA2048|PSS|SHA256|MGF1_SHA256**. + +| Asymmetric Key Type| Padding Mode| Digest| Mask Digest| +|---|---|---|---| +|RSA512|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA512|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA512|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA512|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]|RSA512\|PSS\|SHA256\|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| +|RSA768|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA768|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA768|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA768|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| +|RSA768|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| +|RSA768|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| +|RSA1024|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA1024|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| +|RSA2048|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA2048|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA3072|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA4096|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| +|RSA8192|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| **ECDSA Signing and Signature Verification** @@ -384,11 +381,11 @@ The crypto framework provides two padding modes for RSA signing and signature ve |Digest Algorithm|Supported Type| |---|---| - |HASH|SHA-1| - |HASH|SHA-224| - |HASH|SHA-256| - |HASH|SHA-384| - |HASH|SHA-512| + |HASH|SHA1| + |HASH|SHA224| + |HASH|SHA256| + |HASH|SHA384| + |HASH|SHA512| ### Key Agreement Specifications @@ -408,11 +405,11 @@ The crypto framework provides two padding modes for RSA signing and signature ve |Digest Algorithm|Supported Type| |---|---| - |HASH|SHA-1| - |HASH|SHA-224| - |HASH|SHA-256| - |HASH|SHA-384| - |HASH|SHA-512| + |HASH|SHA1| + |HASH|SHA224| + |HASH|SHA256| + |HASH|SHA384| + |HASH|SHA512| |HASH|MD5| ### HMAC Algorithm Specifications @@ -420,8 +417,8 @@ The crypto framework provides two padding modes for RSA signing and signature ve |Digest Algorithm|Supported Type| |---|---| - |HASH|SHA-1| - |HASH|SHA-224| - |HASH|SHA-256| - |HASH|SHA-384| - |HASH|SHA-512| + |HASH|SHA1| + |HASH|SHA224| + |HASH|SHA256| + |HASH|SHA384| + |HASH|SHA512| diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 743d89654a1b63961a66dfc13e260b909ff23b49..69885fb26ca0665683dad072fbeab5f3858d830b 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1498,6 +1498,26 @@ Allows an application to to access the Ability of the push service. **Enable via ACL**: TRUE +## ohos.permission.READ_APP_PUSH_DATA + +Allows the push service to read data from an application. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.WRITE_APP_PUSH_DATA + +Allows the push service to write data to an application. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + ## ohos.permission.RECEIVER_STARTUP_COMPLETED Allows an application to subscribe to the startup broadcast. @@ -1667,3 +1687,33 @@ Allows an application to call the system API of the lock screen service. **Authorization mode**: system_grant **Enable ACL**: FALSE + +## ohos.permission.PRINT + +Allows an application to obtain the print framework capability. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable via ACL**: TRUE + +## ohos.permission.MANAGE_PRINT_JOB + +Allows an application to obtain the capability of managing print tasks. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable via ACL**: TRUE + +## ohos.permission.CHANGE_OVERLAY_ENABLED_STATE + +Allows a system application to disable the application with the overlay feature enabled. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable via ACL**: TRUE diff --git a/en/application-dev/security/permission-verify-guidelines.md b/en/application-dev/security/permission-verify-guidelines.md index e1726db925256093c4f56badf362f8bbfedf7c82..e33d9e2021aeb0e29856253de897a92333530f29 100644 --- a/en/application-dev/security/permission-verify-guidelines.md +++ b/en/application-dev/security/permission-verify-guidelines.md @@ -2,15 +2,18 @@ ## When to Use -To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [Application Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. +To protect sensitive data and eliminate security threats on core abilities, you can use the permissions in the [Application Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. ## Available APIs -The table below lists only the API used for access permission verification. For more information, see [AbilityContext](../reference/apis/js-apis-ability-context.md). +The following describes only the API used for permission verification. For more information about the APIs, see [Application Access Control](../reference/apis/js-apis-abilityAccessCtrl.md). -| API | Description | -| ------------------------------------------------------------ | --------------------------------------------------- | -| verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> | Checks whether an application process has the specified permission.| +checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Token ID of the application. You can obtain the value from the [ApplicationInfo](../reference/apis/js-apis-bundleManager-applicationInfo.md) of the application. | +| permissionName | Permissions | Yes | Name of the permission to verify. Valid permission names are defined in the [Application Permission List](permission-list.md). | ## Example @@ -19,10 +22,9 @@ The procedure is as follows: 1. Obtain the caller's identity (**tokenId**). > **NOTE** - > - > You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md#getcallingtokenid8). -2. Determine the permission to verify, which is **ohos.permission.PERMISSION** in this example. -3. Call **verifyAccessToken()** to perform a permission verification for the caller. + > You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md). +2. Determine the permission to verify, which is **ohos.permission.ACCELEROMETER** in this example. +3. Call **checkAccessToken()** to perform a permission verification for the caller. 4. Proceed based on the permission verification result. ```js @@ -34,11 +36,14 @@ The procedure is as follows: let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); console.log("RpcServer: getCallingTokenId result: " + callerTokenId); var atManager = abilityAccessCtrl.createAtManager(); - var result = await atManager.verifyAccessToken(tokenID, "ohos.permission.PERMISSION"); - if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { - // Allow the caller to invoke the API provided by the app. - } else { - // Deny the caller's access to the API. + try { + atManager.checkAccessToken(callerTokenId, "ohos.permission.ACCELEROMETER").then((data) => { + console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); + }).catch((err) => { + console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); + }); + } catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); } return true; } diff --git a/en/application-dev/telephony/Readme-EN.md b/en/application-dev/telephony/Readme-EN.md index a5a60273c71f7002efa6f8cb862848c3f169de9d..20a349fabbbb47329f6f49b335315d273b3c9420 100644 --- a/en/application-dev/telephony/Readme-EN.md +++ b/en/application-dev/telephony/Readme-EN.md @@ -1,5 +1,5 @@ # Telephony - [Telephony Service Overview](telephony-overview.md) -- [Redirecting to the Dial Screen](jumping-to-the-dial-screen.md) -- [Obtaining Current Cellular Network Signal Information](cellular-network-signal-info.md) +- [Call Service Development](telephony-call.md) +- [SMS Service Development](telephony-sms.md) diff --git a/en/application-dev/telephony/cellular-network-signal-info.md b/en/application-dev/telephony/cellular-network-signal-info.md deleted file mode 100644 index 41cb90c05493cb4ce12313a9bd194cb14835f4a9..0000000000000000000000000000000000000000 --- a/en/application-dev/telephony/cellular-network-signal-info.md +++ /dev/null @@ -1,51 +0,0 @@ -# Obtaining Current Cellular Network Signal Information - - -## Use Cases - -Applications always need to obtain signal information of the registered cellular network to obtain the network quality. You can use this service to obtain the network signal information for the specified SIM card. - - -## Available APIs - -The radio module provides you with APIs to obtain network signal information. The observer module provides APIs to register or unregister the observer for cellular network status changes. The following table describes the related APIs. - -| Category| API| Description| Required Permission| -| -------- | -------- | -------- | -------- | -| Obtaining a **SignalInformation** object| radio.getSignalInformation​​() | Obtains the signal strength of the currently registered cellular network.| N/A| -| Registering the observer for signal information changes| observer.on('signalInfoChange') | Registers the observer for signal information changes.| N/A| -| Unregistering the observer for signal information changes| observer.off('signalInfoChange') | Unregisters the observer for signal information changes.| N/A| - - -## How to Develop - -1. Import required modules. - -2. Call the **getSignalInformation()** API to obtain the **SignalInformation** list. - -3. Traverse the **SignalInformation** list to obtain the signal strength for each radio access technology (RAT) indicated by **signalType**. - -4. (Optional) Register the observer for signal information changes. - - ```js - import radio from '@ohos.telephony.radio' - import observer from '@ohos.telephony.observer'; - - // Obtain the signal strength of the specified SIM card, for example, card 1. - let slotId = 0; - radio.getSignalInformation(slotId, (err, data) => { - if (!err) { - console.log("get signal information success."); - // Traverse the signal information list to obtain the signal strength for each RAT. - for (let j = 0; j < data.length; j++) { - console.log("type:" + data[j].signalType + ", level:" + data[j].signalLevel); - } - } else { - console.log("get signal information fail, err is:" + JSON.stringify(err)); - } - }); - // (Optional) Register the observer for signal information changes. - observer.on("signalInfoChange", (data) => { - console.log("signal info change, data is:" + JSON.stringify(data)); - }); - ``` diff --git a/en/application-dev/telephony/jumping-to-the-dial-screen.md b/en/application-dev/telephony/jumping-to-the-dial-screen.md deleted file mode 100644 index b314f4c138d93dbb8870f1d2098b5f5e9f10b6bc..0000000000000000000000000000000000000000 --- a/en/application-dev/telephony/jumping-to-the-dial-screen.md +++ /dev/null @@ -1,51 +0,0 @@ -# Redirecting to the Dial Screen - -You can use this service for your application to redirect users to the dial screen and display the dialed number. When the **makeCall** API is called, the device will automatically display the dial screen. On this screen, the user can choose to make an audio or video call and specify the SIM card. - - -## Available APIs - -The call module provides APIs for call management. The observer module provides APIs to register or unregister an observer for call service status changes. The following table describes the related APIs. - -| Category| API| Description| Required Permission| -| -------- | -------- | -------- | -------- | -| Checking call capabilities| call.hasVoiceCapability() | Checks whether the voice call function is supported.| N/A| -| Redirecting to the dial screen| call.makeCall() | Enables redirection to the dial screen and display of the dialed number.| N/A| -| Registering the observer for call service status changes| observer.on('callStateChange') | Registers the observer for call service status changes.| ohos.permission.READ_CALL_LOG (required for obtaining phone numbers)| -| Unregistering the observer for call service status changes| observer.off('callStateChange') | Unregisters the observer for call service status changes.| N/A| - - -## How to Develop - -1. Import required modules. - -2. Invoke the **hasVoiceCapability()** API to check whether the call function is supported. If supported, go to step 3; otherwise, calls will be rejected. - -3. Enable redirection to the dial screen and display of the dialed number. - -4. (Optional) Register the observer for call service status changes. - - ```js - // Import the required modules. - import call from '@ohos.telephony.call'; - import observer from '@ohos.telephony.observer'; - - // Check whether the voice call function is supported. - let isSupport = call.hasVoiceCapability(); - if (!isSupport) { - console.log("not support voice capability, return."); - return; - } - // If the voice call function is supported, the user will be redirected to the dial screen and the dialed number is displayed. - call.makeCall("13xxxx", (err)=> { - if (!err) { - console.log("make call success."); - } else { - console.log("make call fail, err is:" + JSON.stringify(err)); - } - }); - // (Optional) Register the observer for call service status changes. - observer.on("callStateChange", (data) => { - console.log("call state change, data is:" + JSON.stringify(data)); - }); - ``` diff --git a/en/application-dev/telephony/telephony-call.md b/en/application-dev/telephony/telephony-call.md new file mode 100644 index 0000000000000000000000000000000000000000..bbef181efb128f47ee08fd84d5adb0fd1aa031b2 --- /dev/null +++ b/en/application-dev/telephony/telephony-call.md @@ -0,0 +1,116 @@ +# Call Service Development + +## Scenario Description + +You can implement the call service in either of the following ways: +- For a system application, use the **dial** API to make a voice or video call. The call will be displayed on the application page. +- For a third-party application, use the **makecall** API to start the system call application. Users can then make calls as needed. + +## Basic Concepts + +- Call status code + A code used to report the current call status to the application, so that the application can then take appropriate logic processing. For example, if there is no ongoing call, the application allows you to make a new call. + + | Name | Value | Description | + | ------------------ | ---- | ------------------------------------------------------------ | + | CALL_STATE_UNKNOWN | -1 | The call status fails to be obtained and is unknown. | + | CALL_STATE_IDLE | 0 | No call is in progress. | + | CALL_STATE_RINGING | 1 | The call is in the ringing or waiting state. | + | CALL_STATE_OFFHOOK | 2 | At least one call is in dialing, active, or on hold, and no new incoming call is ringing or waiting.| + +## Constraints + +1. The call service is available only on standard-system devices. +2. An available SIM card must be present on the device. + + +## Available APIs + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [call API Reference](../reference/apis/js-apis-call.md). + +| Name | Description | +| ----------------------------------------------------------------------------------- | ------------------------------------------------------------ | +| hasVoiceCapability(): boolean; | Checks whether the voice function is available. | +| dial(phoneNumber: string, callback: AsyncCallback): void | Makes a call. This is a system API. | +| makeCall(phoneNumber: string, callback: AsyncCallback): void | Redirects to the dial screen and displays the called number. | + +The **observer** module provides the functions of subscribing to and unsubscribing from the call service status. For details about the APIs, see [observer API Reference](../reference/apis/js-apis-observer.md). + +| Name | Description | +| ------------------------------------------------------------ | ------------------ | +| on(type: 'callStateChange', options: { slotId: number }, callback: Callback<{ state: CallState, number: string }>): void | Listens to call status changes.| + +## How to Develop + +### Making a Call by Using the **dial** API (Only for System Applications) + +1. Declare the required permission: **ohos.permission.PLACE_CALL**. +This permission is of the **system\_basic** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met. Then, declare the corresponding permission by following instructions in [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). +2. Import the **call** and **observer** modules. +3. Invoke the **hasVoiceCapability** API to check whether the device supports the voice call function. + If the voice call function is supported, the user will be redirected to the dial screen and the dialed number is displayed. +4. Invoke the **dial** API to make a call. +5. (Optional) Register the observer for call status changes. + ```js + // Import the required modules. + import call from '@ohos.telephony.call' + import observer from '@ohos.telephony.observer' + + // Check whether the voice call function is supported. + let isSupport = call.hasVoiceCapability(); + if (!isSupport) { + console.log("not support voice capability, return."); + return; + } + // If the device supports the voice call function, call the following API to make a call. + call.dial("13xxxx", (err, data) => { + this.output = this.output + `dial: ${JSON.stringify(data)}\n` + console.log(`callback: dial err->${JSON.stringify(err)} data->${JSON.stringify(data)}`) + }) + + // (Optional) Register the observer for call service status changes. + observer.on("callStateChange", {slotId: 0}, (data) => { + console.log("call state change, data is:" + JSON.stringify(data)); + }); + ``` + +### Making a Call by Using the makecall API + +1. Import the **call** and **observer** modules. +2. Invoke the **hasVoiceCapability** API to check whether the device supports the voice call function. + If the voice call function is supported, the user will be redirected to the dial screen and the dialed number is displayed. +3. Invoke the **makecall** API to start the system call application and make a call. +4. (Optional) Register the observer for call status changes. + + ```js + // Import the required modules. + import call from '@ohos.telephony.call' + import observer from '@ohos.telephony.observer' + + // Check whether the voice call function is supported. + let isSupport = call.hasVoiceCapability(); + if (!isSupport) { + console.log("not support voice capability, return."); + return; + } + // If the voice call function is supported, the user will be redirected to the dial screen and the dialed number is displayed. + call.makeCall("13xxxx", (err)=> { + if (!err) { + console.log("make call success."); + } else { + console.log("make call fail, err is:" + JSON.stringify(err)); + } + }); + + // (Optional) Register the observer for call service status changes. + observer.on("callStateChange", {slotId: 0}, (data) => { + console.log("call state change, data is:" + JSON.stringify(data)); + }); + ``` + +## Samples + +The following sample is provided to help you better understand how to develop the call service: + +- [Call](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/Call) diff --git a/en/application-dev/telephony/telephony-overview.md b/en/application-dev/telephony/telephony-overview.md index 8fc3587c8c93428f1a243025a3e1743aca40bdb0..1ea731c56ba89fefb258174ca409e169dd4a5894 100644 --- a/en/application-dev/telephony/telephony-overview.md +++ b/en/application-dev/telephony/telephony-overview.md @@ -1,12 +1,17 @@ # Telephony Service Overview -The Telephony subsystem provides a series of APIs for [making calls](../reference/apis/js-apis-call.md), [obtaining current cellular network signal information](../reference/apis/js-apis-telephony-data.md) and [managing SIM cards](../reference/apis/js-apis-sim.md). +The telephony subsystem consists of the following modules that provide APIs to help you develop communication applications: -Your application can call related APIs to obtain the name of the currently registered network, network service status, signal strength, and SIM card information. For details, see [Obtaining Current Cellular Network Signal Information](cellular-network-signal-info.md). +- Call module: Allows an application to directly make a call and display the call on the application screen. A third-party application can start the system call application and redirect to the dialing screen to make a call. For details, see [Telephony Call Development](telephony-call.md). With the call module, the application can also format phone numbers and determine whether a number is an emergency number. For details, see [call API Reference](../reference/apis/js-apis-call.md). -To make calls, your application needs to declare the **ohos.permission.PLACE_CALL** permission. It is recommended that the application use **makeCall()** to redirect users to the dial screen and display the dialed number. For details, see [Redirecting to the Dial Screen](jumping-to-the-dial-screen.md). +- SMS module: Allows an application to create and send SMS messages. For details, see [Telephony SMS Development](telephony-sms.md). In addition, the the application can obtain and set the SMS service center address, and check whether the current device can send and receive SMS messages. For details, see the [sms API Reference](../reference/apis/js-apis-sms.md). +- Radio module: Allows an application to obtain the name of the currently registered network, network service status, and signal strength. For details, see [radio API Reference](../reference/apis/js-apis-radio.md). + +- Data module: Allows an application to access cellular data services. Cellular data is a wireless network communication standard that uses the packet switch technology throughout data transmission and switch to provide voice, data, and video services for mobile devices. It enables users to use applications on mobile devices or browse web pages on the mobile network. For details, see [data API Reference](../reference/apis/js-apis-telephony-data.md). + +- SIM module: Allows an application to obtain SIM card information, such as the service provider, International Organization for Standardization (ISO) country code, and home Public Land Mobile Network (PLMN) number. For details, see [sim API Reference](../reference/apis/js-apis-sim.md). ## Constraints -The accommodating device must be equipped with a modem and a SIM card capable of independent cellular communication. +Before calling telephony service APIs, ensure that the device is equipped with a modem and SIM card capable of independent cellular communication. diff --git a/en/application-dev/telephony/telephony-sms.md b/en/application-dev/telephony/telephony-sms.md new file mode 100644 index 0000000000000000000000000000000000000000..a8cf16532ae4537e2628821d2af933f7d0a0a176 --- /dev/null +++ b/en/application-dev/telephony/telephony-sms.md @@ -0,0 +1,118 @@ +# SMS Service Development + +## Scenario Description + +The Short Messaging Service (SMS) module provides basic SMS management functions. You can create and send SMS messages, and obtain the ID of the default SIM card used to send and receive SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. + +## Basic Concepts + +- SMS + + A service capable of SMS message storage and forwarding. It enables mobile phones to send and receive SMS messages. The content of the SMS message can be text, digits, or binary non-text data. The information about the sender is stored in the Short Message Service Center (SMSC) and forwarded to the recipient. + +- SMSC + + An entity that relays, stores, or forwards SMS messages between base stations and mobile devices. It uses the GMS 03.40 protocol for sending SMS messages to or receiving SMS messages from mobile phones. + +- PDU + + Protocol data unit, which uses the following encoding schemes to send and receive SMS messages: 7-bit, 8-bit, and UCS-2. 7-bit encoding is used to send common ASCII characters, 8-bit encoding to send data messages, and UCS-2 encoding to send Unicode characters. + +## Constraints + +1. The SMS service is available only on standard-system devices. +2. An available SIM card must be present on the device, and the permission to send SMS messages must be granted. + + +## Available APIs + +> **NOTE** +> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-sms.md). + +| Name | Description | +| ------------------------------------------------------------ | ------------------------------------------------------- | +| createMessage(pdu: Array, specification: string, callback: AsyncCallback): void | Creates an SMS message instance based on the PDU and the specified SMS protocol.| +| sendMessage(options: SendMessageOptions): void | Sends text or data SMS messages. | +| getDefaultSmsSlotId(callback: AsyncCallback): void | Obtains the ID of the default SIM card used to send SMS messages. | +| setSmscAddr(slotId: number, smscAddr: string, callback: AsyncCallback): void | Sets the SMSC address based on the specified slot ID. | +| getSmscAddr(slotId: number, callback: AsyncCallback): void | Obtains the SMSC address based on the specified slot ID. | + + +## How to Develop + +1. Declare the required permission: + - To send SMS messages, call the **sendMessage** API and declare the **ohos.permission.SEND\_MESSAGES** permission. The permission is of the **system\_basic** level. + - To set the SMSC address, call the** setSmscAddr** API and declare the **ohos.permission.SET\_TELEPHONY\_STATE** permission. The permission is of the **system\_basic** level. + - To obtain the SMSC address, call the** getSmscAddr** API and declare the **ohos.permission.GET\_TELEPHONY\_STATE** permission. The permission is of the **system\_basic** level. + Before applying for the permission, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met. Then, declare the corresponding permission by following instructions in [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Import the required modules. + +3. Create an SMS message instance based on the PDU and the specified SMS protocol. + +4. Send an SMS message. + + ```js + // Import the required modules. + import sms from '@ohos.telephony.sms' + + export default class SmsModel { + async createMessage() { + const specification = '3gpp' + const pdu = [0x08, 0x91] // Display PDUs in array format. The type is number. + const shortMessage = await sms.createMessage(pdu, specification) + Logger.info(`${TAG}, createMessageCallback: shortMessage = ${JSON.stringify(shortMessage)}`) + return shortMessage + } + + sendMessage(slotId, content, destinationHost, serviceCenter, destinationPort, handleSend, handleDelivery) { + Logger.info(`${TAG}, sendMessage start ${slotId} ${content} ${destinationHost} ${serviceCenter} ${destinationPort}`) + const options = + { + slotId: slotId, + content: content, + destinationHost: destinationHost, + serviceCenter: serviceCenter, + destinationPort: destinationPort, + sendCallback(err, data) { + Logger.info(`${TAG}, sendCallback: data = ${JSON.stringify(data)} err = ${JSON.stringify(err)}`) + handleSend(err, data) + }, + deliveryCallback(err, data) { + Logger.info(`${TAG}, deliveryCallback: data = ${JSON.stringify(data)} err = ${JSON.stringify(err)}`) + handleDelivery(err, data) + } + } + // Send an SMS message. + sms.sendMessage(options) + Logger.info(`${TAG}, sendMessage end`) + } + + // Obtain the ID of the default SIM card used to send SMS messages. + async getDefaultSmsSlotId() { + const defaultSmsSlotId = await sms.getDefaultSmsSlotId() + Logger.info(`${TAG}, getDefaultSmsSlotId: defaultSmsSlotId = ${defaultSmsSlotId}`) + return defaultSmsSlotId + } + + // Set the SMSC address based on the specified slot ID. + async setSmscAddr(slotId, smscAddr) { + const serviceCenter = await sms.setSmscAddr(slotId, smscAddr) + Logger.info(`${TAG}, setSmscAddr: serviceCenter = ${JSON.stringify(serviceCenter)}`) + return serviceCenter + } + + // Obtain the SMSC address based on the specified slot ID. + async getSmscAddr(slotId) { + const serviceCenter = await sms.getSmscAddr(slotId) + Logger.info(`${TAG}, getSmscAddr: serviceCenter = ${JSON.stringify(serviceCenter)}`) + return serviceCenter + } + } + ``` + + +## Samples + +The following sample is provided to help you better understand how to develop the SMS service: +- [SMS](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/Message) diff --git a/en/application-dev/tools/Readme-EN.md b/en/application-dev/tools/Readme-EN.md index 5dfe93a6a9584920a5da457ac61964dcb183a99c..7be1e5159712ec14a7b6f433883a0ccbcda64938 100644 --- a/en/application-dev/tools/Readme-EN.md +++ b/en/application-dev/tools/Readme-EN.md @@ -7,3 +7,4 @@ - [Unpacking Tool](unpacking-tool.md) - [Common Event Manager](cem-tool.md) - [Advanced Notification Manager](anm-tool.md) +- [restool](restool.md) diff --git a/en/application-dev/tools/aa-tool.md b/en/application-dev/tools/aa-tool.md index 69db1fd8814bd5880063bb063f6c77db1b4a281c..eb1e5955656595b6bf9529154a0f124c4e454da0 100644 --- a/en/application-dev/tools/aa-tool.md +++ b/en/application-dev/tools/aa-tool.md @@ -1,7 +1,11 @@ # Ability Assistant -The Ability Assistant provides the application debugging and testing capabilities that enable you to start applications and test cases. With this tool, you can send commands (started with **aa**) in the hdc shell to perform various system operations, such as starting application components, forcibly stopping processes, and printing application component information. +The ability assistant enables you to start applications and test cases. It provides basic application debugging and testing capabilities, for example, starting application components, forcibly stopping processes, and printing application component information. + +> **NOTE** +> +> Before using this tool, you must obtain the [hdc tool](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) and run the hdc shell command. - help diff --git a/en/application-dev/tools/anm-tool.md b/en/application-dev/tools/anm-tool.md index 5a738bc22ff538676158bb3da32aacf9b507097c..5f77e876ca2e0da4be95e0749fea79844066e854 100644 --- a/en/application-dev/tools/anm-tool.md +++ b/en/application-dev/tools/anm-tool.md @@ -1,6 +1,10 @@ # Advanced Notification Manager -The Advanced Notification Manager provides the notification debugging and testing capabilities that enable you to print notifications and set notification parameters. With this tool, you can send commands (started with **anm**) in the hdc shell to perform various system operations, such as printing notification details, setting the number of cached notifications, and enabling the notification capability. +The Advanced Notification Manager enables you to print notifications and set notification parameters. It provides the notification debugging and testing capabilities, for example, printing published notification details, setting the number of notification caches, and enabling the notification functionality. + +> **NOTE** +> +> Before using this tool, you must obtain the [hdc tool](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) and run the hdc shell command. ### help diff --git a/en/application-dev/tools/bm-tool.md b/en/application-dev/tools/bm-tool.md index 879a2f123b2e2ea9a1dc8ce30c38da81458dc2e3..fad43d6ec5b00af19ad1255614725d3fccef75cf 100644 --- a/en/application-dev/tools/bm-tool.md +++ b/en/application-dev/tools/bm-tool.md @@ -1,7 +1,12 @@ # Bundle Manager -The Bundle Manager provides the bundle debugging and testing capabilities that enable you to install, uninstall, update, and query a bundle (application). With this tool, you can send commands (started with **bm**) in the hdc shell to perform various system operations, such as installing and uninstalling a bundle and querying bundle information. +The Bundle Manager enables you to install, uninstall, update, and query a bundle (application). It provides the bundle debugging capabilities, for example, installing and uninstalling a bundle and querying bundle information. + +> **NOTE** +> +> Before using this tool, you must obtain the [hdc tool](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) and run the hdc shell command. + **Table 1** bm commands @@ -41,6 +46,7 @@ bm help bm install [-h] [-p path] [-u userId] [-r] [-w waitting-time] ``` + **Table 3** Installation command parameters | Name| Mandatory| Description| @@ -67,6 +73,7 @@ install bundle successfully. bm uninstall [-h help] [-n bundleName] [-m moduleName] [-u userId] [-k] ``` + **Table 4** Uninstall command parameters | Name| Mandatory| Description| @@ -96,6 +103,7 @@ bm dump [-h help] [-a] [-n bundleName] [-s shortcutInfo] [-u userId] [-d deviceI If **-u** is not specified, the command applies to all users. + **Table 5** Dump command parameters | Name| Mandatory| Description| @@ -131,6 +139,7 @@ bm clean [-h] [-c] [-n bundleName] [-d] [-u userId] If **-u** is not specified, the command applies to all active users. + **Table 6** Clean command parameters | Name| Description| @@ -164,6 +173,7 @@ bm enable [-h] [-n bundleName] [-a abilityName] [-u userId] If **-u** is not specified, the command applies to all active users. + **Table 7** Enable command parameters | Name| Description| @@ -193,6 +203,7 @@ bm disable [-h] [-n bundleName] [-a abilityName] [-u userId] If **-u** is not specified, the command applies to all active users. + **Table 8** Disabled command parameters | Name| Description| @@ -218,6 +229,7 @@ disable bundle successfully. bm get [-h] [-u] ``` + **Table 9** Parameters used in the command for obtaining the UDID | Name| Description| @@ -243,6 +255,7 @@ udid of current device is : bm quickfix [-h] [-a -f filePath] [-q -b bundleName] ``` + **Table 10** Parameters used in the command for quick fix | Name| Description| diff --git a/en/application-dev/tools/cem-tool.md b/en/application-dev/tools/cem-tool.md index beaf1a86e38b11508d5551a48e018cf98e7e7a6e..678078e5b7f0acd2da0a02b9ab9f69d5b4824743 100644 --- a/en/application-dev/tools/cem-tool.md +++ b/en/application-dev/tools/cem-tool.md @@ -1,6 +1,10 @@ # Common Event Manager -The Common Event Manager provides the common event debugging and testing capabilities that enable you to print common event information and publish common events. With this tool, you can send commands (started with **cem**) in the hdc shell to perform various system operations, such as printing all common event subscribers, sent common events, and recipients, as well as publishing common events. +The Common Event Manager enables you to print common event information and publish common events. It provides the common event debugging and testing capabilities, for example, printing all public event subscribers, sent public events, and recipients, and simulating public event release. + +> **NOTE** +> +> Before using this tool, you must obtain the [hdc tool](../../device-dev/subsystems/subsys-toolchain-hdc-guide.md) and run the hdc shell command. ## Commands diff --git a/en/application-dev/tools/restool.md b/en/application-dev/tools/restool.md new file mode 100644 index 0000000000000000000000000000000000000000..15baaa69411a5395c86e87b5ca7c95abe830b253 --- /dev/null +++ b/en/application-dev/tools/restool.md @@ -0,0 +1,74 @@ +# restool + + +## Overview + +restool is a resource compilation tool that creates resource indexes and parses resources by compiling resource files. The tool is stored in the **toolchains** subdirectory of the SDK installation directory. + +## Description + +The tool supports the following command options. + +| Option| Default Value Allowed| Argument Carried| Description| +| -------- | -------- | -------- | -------- | +| -i | No| Yes| Resource directory or resource intermediate file directory to create. The same command can run multiple times.| +| -j | No| Yes| Path of the **config.json** or **module.json** file.| +| -o | No| Yes| Output path of the compiled resource.| +| -p | No| Yes| Bundle name of the compiled resource.| +| -r | No| Yes| Header file path of the resource. The header file can be in .txt, .js, or .h format.| +| -e | Yes| Yes| Start ID of the generated resource, for example, **0x01000000**. The value range is [0x01000000, 0x06FFFFFF),[0x08000000, 0x41FFFFFF).| +| -f | Yes| No| An existing output path will be forcibly deleted and a new one will be generated.| +| -h | Yes| No| Help information.| +| -m | Yes| Yes| Module name. During joint module compilation, multiple module names can be specified, separated by commas (,).| +| -x | Yes| Yes| Resource directory for generating intermediate files or a single resource path. The same command can run multiple times.| +| -z | Yes| No| Compilation result generated based on the resource directory.| +| -v | Yes| No| Tool version.| +| --ids | Yes| Yes| Output directory of the generated **id_defined.json** file.| +| --defined-ids | Yes| Yes| Path of the **id_defined.json** file. Generally, the file is generated by using **--ids**.
**id_defined.json** contains a list of resource types, names, and IDs.
You can customize resource IDs in **id_defined.json**.| + +## Example + +An example **entry** directory structure is as follows: +``` +entry/src/main +| |----resource +| | |----base +| | | |----element +| | | |----media +| | | |----profile +| | |----rawfile +| |----config.json/module.json +``` + +Run the following command to build all resources: + +``` +restool -i entry/src/main -j entry/src/main/module.json -p com.ohos.demo -o out -r out/ResourceTable.txt -f +``` + +To build the resource incrementally (available only in preview mode), perform the following steps: + +1. Generate resource middleware. +``` +restool -x entry/src/main/resource -o out +``` +2. Compile the middleware. +``` +restool -i out1 -i out2 -o out -p com.ohos.demo -r out/ResourceTable.txt -j entry/src/main/module.json -f -z +``` + +The resource ID can be fixed in either of the following ways: + +Method 1: Store the custom **id_defined.json** file in the **resource/base/element/** directory. After the build is successful, the generated ID is the same as the custom ID in the **id_defined.json** file. + +Method 2: Run the **--ids** command to generate the **id_defined.json** file. The **--defined-ids** command specifies the **id_defined.json** file. After the build is successful, the generated ID is the same as the custom ID in the **id_defined.json** file. + +Generate the **id_defined.json** file. +``` +restool -i entry/src/main -j entry/src/main/module.json -p com.ohos.demo -o out -r out/ResourceTable.txt --ids out/id_defined.json -f +``` + +**id_defined.json** file with a fixed resource ID: +``` +restool -i entry/src/main -j entry/src/main/module.json -p com.ohos.demo -o out1 -r out1/ResourceTable.txt --defined-ids out/id_defined.json -f +``` diff --git a/en/application-dev/ui/figures/en-us_image_0000001218419614.png b/en/application-dev/ui/figures/en-us_image_0000001218419614.png index 101f60e44760d98db7a904189f387e2b3557cf32..6cb1dfdc2eedeb82fb0b32df1f2de8c73df08e85 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218419614.png and b/en/application-dev/ui/figures/en-us_image_0000001218419614.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218579606.png b/en/application-dev/ui/figures/en-us_image_0000001218579606.png index c8697767f19ae5cc5f7b30c4cbc2a23ffafb0844..42537bbffe87c2972e3130bf5ccc5fc6b055757a 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218579606.png and b/en/application-dev/ui/figures/en-us_image_0000001218579606.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218739566.png b/en/application-dev/ui/figures/en-us_image_0000001218739566.png index 4384ea3a2997c4417eee0fbe0e6475c4925b5c36..c5c7e29232e4f468c34faf3f521f594f6ef322bf 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218739566.png and b/en/application-dev/ui/figures/en-us_image_0000001218739566.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263019457.png b/en/application-dev/ui/figures/en-us_image_0000001263019457.png index dea13c34b80626c7fe1a0036afbe69d5f236910c..ee5931a95991c672e1b4812d9fa62541e2f8a880 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263019457.png and b/en/application-dev/ui/figures/en-us_image_0000001263019457.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263139409.png b/en/application-dev/ui/figures/en-us_image_0000001263139409.png index 395631e2ed4572806bd93bcdb8ff86486e0b5bdf..77364d35a2c56de8616a2d7ea77c4977b4b3e2bb 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263139409.png and b/en/application-dev/ui/figures/en-us_image_0000001263139409.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263259399.png b/en/application-dev/ui/figures/en-us_image_0000001263259399.png index dc4a266c02708116362da21577d5b1e582a011fd..938ded6d0b38dc838159990880c66c4211dd5aaa 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263259399.png and b/en/application-dev/ui/figures/en-us_image_0000001263259399.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263339459.png b/en/application-dev/ui/figures/en-us_image_0000001263339459.png index 99e18123d53b88779948b34c6c566005d989358b..97bdd1f5dc3bf6100e12e5d830290cdc0ad678a1 100644 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263339459.png and b/en/application-dev/ui/figures/en-us_image_0000001263339459.png differ diff --git a/en/application-dev/ui/ui-js-animate-background-position-style.md b/en/application-dev/ui/ui-js-animate-background-position-style.md index 26b8fe2b594e5c31efbf9fc2c0e9268695e319ba..c12792b4095319a7f01740b844729e5af2c6f57e 100644 --- a/en/application-dev/ui/ui-js-animate-background-position-style.md +++ b/en/application-dev/ui/ui-js-animate-background-position-style.md @@ -27,6 +27,7 @@ By changing the **background-position** attribute (where the first value is the .content{ width: 400px; height: 400px; + /* The aspect ratio 1:1 is not recommended. */ background-image: url('common/images/bg-tv.jpg'); background-size: 100%; background-repeat: no-repeat; diff --git a/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md b/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md index 18a633ce6e129be8d2b21c8c46d293e792cd727c..95a07736c69d3d99d90074bd37da895a5860dad7 100644 --- a/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md +++ b/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md @@ -228,6 +228,8 @@ Globally define the canvas (**el**) and brush (**ctx**), and create a rectangle ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -251,7 +253,6 @@ select{ ```js // xxx.js -import prompt from '@system.prompt'; export default { data:{ el: null, @@ -596,7 +597,6 @@ After creating an image object, use the **drawImage** attribute to draw the imag /* xxx.css */ .container{ width: 100%; - height: 100%; flex-direction: column; background-color: #F1F3F5; align-items: center; diff --git a/en/application-dev/ui/ui-ts-animation-feature.md b/en/application-dev/ui/ui-ts-animation-feature.md index c99ad94d8de1765fe4838205d2b212775ba95b52..f7933b9555ff6fb6312c4e8fabc1d2a5be30d168 100644 --- a/en/application-dev/ui/ui-ts-animation-feature.md +++ b/en/application-dev/ui/ui-ts-animation-feature.md @@ -99,7 +99,7 @@ The splash screen animation refers to the fade-in and fade-out of the logo. Afte .opacity(this.opacityValue) .onAppear(() => { animateTo({ - duration: 2000, + duration: 1000, curve: this.curve1, delay: 100, }, () => { @@ -170,9 +170,11 @@ The splash screen animation refers to the fade-in and fade-out of the logo. Afte Path() .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') .fill(Color.White) + .stroke(Color.Transparent) Path() .commands(this.pathCommands1) .fill('none') + .stroke(Color.Transparent) .linearGradient( { angle: 30, @@ -183,6 +185,7 @@ The splash screen animation refers to the fade-in and fade-out of the logo. Afte Path() .commands(this.pathCommands2) .fill('none') + .stroke(Color.Transparent) .linearGradient( { angle: 50, @@ -227,10 +230,10 @@ The splash screen animation refers to the fade-in and fade-out of the logo. Afte angle: 180, colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] }) - } + } } ``` - + ![animation-feature](figures/animation-feature.gif) ## Page Transition Animation diff --git a/en/application-dev/ui/ui-ts-creating-simple-page.md b/en/application-dev/ui/ui-ts-creating-simple-page.md index b33ed86346a2c88acace5e6992f75ac99afb9596..c3382498230de8e6aee8622970db3dc4375c46e5 100644 --- a/en/application-dev/ui/ui-ts-creating-simple-page.md +++ b/en/application-dev/ui/ui-ts-creating-simple-page.md @@ -2,7 +2,7 @@ In this section, we will develop an infographic food details page, by building custom components through the container components **\** and **\** as well as basic components **\** and **\**. -Before creating a page, create an ArkTS project. For details, see [Creating an ArkTS Project in FA model](../quick-start/start-with-ets-stage.md#creating-an-arkts-project) or [Creating an ArkTS Project in Stage model](../quick-start/start-with-ets-fa.md#creating-an-arkts-project). +Before creating a page, create an ArkTS project. For details, see [Creating an ArkTS Project in Stage Model](../quick-start/start-with-ets-stage.md#creating-an-arkts-project) or [Creating an ArkTS Project in FA Model](../quick-start/start-with-ets-fa.md#creating-an-arkts-project). ## Building the Stack Layout @@ -28,8 +28,9 @@ Before creating a page, create an ArkTS project. For details, see [Creating an A ![en-us_image_0000001214128687](figures/en-us_image_0000001214128687.png) 2. Display food pictures. + Create an **\** component and specify a URL for it. To display the **\** component above the **\** component, declare the **\** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `$rawfile('filename')` format, where **filename** indicates the relative path of the file in the **rawfile** folder. `$rawfile` only allows the **\** component to reference image resources. - + ```ts @Entry @Component @@ -45,14 +46,14 @@ Before creating a page, create an ArkTS project. For details, see [Creating an A } ``` - ![en-us_image_0000001168410342](figures/en-us_image_0000001168410342.png) 3. Access images through resources. + In addition to specifying the image path, you can also use the media resource symbol **$r** to reference resources based on the resource qualifier rules in the **resources** folder. Right-click the **resources** folder, choose **New** > **Resource Directory** from the shortcut menu, and set **Resource Type** to **Media** (image resource). - + Place **Tomato.png** in the **media** folder. You can then reference the application resources in the `$r('app.type.name')` format, which is `$r('app.media.Tomato')` in this example. - + ```ts @Entry @Component @@ -69,9 +70,11 @@ Before creating a page, create an ArkTS project. For details, see [Creating an A } } ``` - + 4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. + If the image fills the entire screen, the possible causes are as follows: + 1. The width and height of the image are not set. 2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked. @@ -215,12 +218,13 @@ Use the **Flex** layout to build a food composition table. In this way, cell siz ``` 2. Create a **\** component to display two food composition categories in the tomato: **Calories** and **Nutrition**. + **Calories** contains information about calories. **Nutrition** contains information about protein, fat, carbohydrates, and vitamin C. - + Create the **Calories** class. Create a **\** component and set its height to **280**, and the top, right, and left margins to **30**. The **Flex** component contains three **\** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the **Flex** component are arranged horizontally. - + In the following example, code of **FoodImageDisplay** is omitted, and only code of **ContentTable** is provided. - + ```ts @Component struct ContentTable { @@ -307,12 +311,13 @@ Use the **Flex** layout to build a food composition table. In this way, cell siz } } ``` - + ![en-us_image_0000001215079443](figures/en-us_image_0000001215079443.png) - + 4. Create the **Nutrient** class in a similar process. **Nutrition** consists of four parts: **Protein**, **Fat**, **Carbohydrates**, and **VitaminC**. The names of the last three parts are omitted in the table and represented by spaces. + Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**. - + ```ts @Component struct ContentTable { @@ -406,17 +411,18 @@ Use the **Flex** layout to build a food composition table. In this way, cell siz } } ``` - + ![en-us_image_0000001215199399](figures/en-us_image_0000001215199399.png) 5. Use the custom constructor **\@Builder** to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure. - + ![en-us_image_0000001169599582](figures/en-us_image_0000001169599582.png) - + + Currently, all food groups are declared, resulting in code duplication and redundancy. You can use **\@Builder** to build a custom method and abstract the same UI structure declaration. The **\@Builder** decorated method and the **build** method for the **@Component** decorated component are used to declare some UI rendering structures and comply with the same ArkTS syntax. You can define one or more methods decorated by **\@Builder**, but a component decorated by **@Component** can have only one **build** method. - + Declare the **IngredientItem** method decorated by **\@Builder** in **ContentTable** to declare the UI descriptions for the category name, content name, and content value. - + ```ts @Component struct ContentTable { @@ -438,9 +444,9 @@ Declare the **IngredientItem** method decorated by **\@Builder** in **ContentTab } } ``` - + When the **IngredientItem** API is called in the **build** method of **ContentTable**, **this** needs to be used to invoke the method in the scope of the component to distinguish the global method call. - + ```ts @Component struct ContentTable { @@ -458,9 +464,9 @@ When the **IngredientItem** API is called in the **build** method of **ContentTa } } ``` - + The overall code of the **ContentTable** component is as follows: - + ```ts @Component struct ContentTable { @@ -506,7 +512,7 @@ The overall code of the **ContentTable** component is as follows: } } ``` - + ![en-us_image_0000001215199399](figures/en-us_image_0000001215199399.png) You've learned how to build a simple food details page. Read on to learn how to define the page layout and connection. diff --git a/en/application-dev/ui/ui-ts-drawing-feature.md b/en/application-dev/ui/ui-ts-drawing-feature.md index 3c9085735def3ef93e814abe7c7f7508ed41d6eb..bc23bea735490686d903740612cc20ceb0140ef1 100644 --- a/en/application-dev/ui/ui-ts-drawing-feature.md +++ b/en/application-dev/ui/ui-ts-drawing-feature.md @@ -92,7 +92,7 @@ In the food component table on the **FoodDetail** page, each food group is label In addition to drawing basic geometric shapes, you can also use the **\** component to draw a custom path. The following describes how to draw an application logo. -1. Create a page **Logo.ets** in the **pages** folder. +1. Create the page **Logo.ets** in the **pages** folder. ![drawing-feature1](figures/drawing-feature1.png) @@ -217,10 +217,11 @@ In addition to drawing basic geometric shapes, you can also use the **\** ![drawing-feature4](figures/drawing-feature4.png) - In the sample code, the fill color is white. + In the sample code, the fill color is white and the stroke is transparent. ```ts .fill(Color.White) + .stroke(Color.Transparent) ``` ```ts @@ -233,6 +234,7 @@ In addition to drawing basic geometric shapes, you can also use the **\** Path() .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') .fill(Color.White) + .stroke(Color.Transparent) } .height('630px') .width('630px') @@ -256,6 +258,7 @@ In addition to drawing basic geometric shapes, you can also use the **\** Path() .commands('M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z') .fill('none') + .stroke(Corlor.Transparent) .linearGradient( { angle: 30, @@ -276,6 +279,7 @@ In addition to drawing basic geometric shapes, you can also use the **\** Path() .commands(this.pathCommands1) .fill('none') + .stroke(Color.Transparent) .linearGradient( { angle: 30, @@ -303,10 +307,12 @@ In addition to drawing basic geometric shapes, you can also use the **\** Path() .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') .fill(Color.White) + .stroke(Color.Transparent) Path() .commands(this.pathCommands1) .fill('none') + .stroke(Color.Transparent) .linearGradient( { angle: 30, @@ -317,6 +323,7 @@ In addition to drawing basic geometric shapes, you can also use the **\** Path() .commands(this.pathCommands2) .fill('none') + .stroke(Color.Transparent) .linearGradient( { angle: 50, @@ -348,33 +355,37 @@ In addition to drawing basic geometric shapes, you can also use the **\** @Entry @Component struct Logo { - private pathCommands1:string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' - private pathCommands2:string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + private pathCommands1: string = 'M319.5 128.1 c103.5 0 187.5 84 187.5 187.5 v15 a172.5 172.5 0 0 3 -172.5 172.5 H198 a36 36 0 0 3 -13.8 -1 207 207 0 0 0 87 -372 h48.3 z' + private pathCommands2: string = 'M270.6 128.1 h48.6 c51.6 0 98.4 21 132.3 54.6 a411 411 0 0 3 -45.6 123 c-25.2 45.6 -56.4 84 -87.6 110.4 a206.1 206.1 0 0 0 -47.7 -288 z' + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Shape() { Path() .commands('M162 128.7 a222 222 0 0 1 100.8 374.4 H198 a36 36 0 0 3 -36 -36') .fill(Color.White) + .stroke(Color.Transparent) Path() .commands(this.pathCommands1) .fill('none') + .stroke(Color.Transparent) .linearGradient( - { - angle: 30, - colors: [["#C4FFA0", 0], ["#ffffff", 1]] - }) + { + angle: 30, + colors: [["#C4FFA0", 0], ["#ffffff", 1]] + }) .clip(new Path().commands(this.pathCommands1)) Path() .commands(this.pathCommands2) .fill('none') + .stroke(Color.Transparent) .linearGradient( - { - angle: 50, - colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] - }) + { + angle: 50, + colors: [['#8CC36A', 0.1], ["#B3EB90", 0.4], ["#ffffff", 0.7]] + }) .clip(new Path().commands(this.pathCommands2)) } .height('630px') @@ -383,22 +394,22 @@ In addition to drawing basic geometric shapes, you can also use the **\** Text('Healthy Diet') .fontSize(26) .fontColor(Color.White) - .margin({ top:300 }) + .margin({ top: 300 }) Text('Healthy life comes from a balanced diet') .fontSize(17) .fontColor(Color.White) - .margin({ top:4 }) + .margin({ top: 4 }) } .width('100%') .height('100%') .linearGradient( { angle: 180, - colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] - }) + colors: [['#BDE895', 0.1], ["#95DE7F", 0.6], ["#7AB967", 1]] + }) } } ``` - + ![drawing-feature8](figures/drawing-feature8.png) diff --git a/en/application-dev/ui/ui-ts-layout-flex.md b/en/application-dev/ui/ui-ts-layout-flex.md index 20ea6ca4cedba93562ccc8ddf2d2233ea9edc1ca..a74d01cfb5183c6ebc6bcbeef5a45695bbdf217f 100644 --- a/en/application-dev/ui/ui-ts-layout-flex.md +++ b/en/application-dev/ui/ui-ts-layout-flex.md @@ -356,7 +356,7 @@ Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { // The it }.width('90%').height(220).backgroundColor(0xAFEEEE) ``` -![](figures/alignself.png) +![alignself](figures/alignself.png) In the preceding example, both **alignItems** of the **\** component and the **alignSelf** attribute of the child component are set. In this case, the **alignSelf** settings take effect. @@ -452,7 +452,7 @@ Use the **alignContent** parameter to set how space is distributed between and a - **FlexAlign.SpaceEvenly**: The items are evenly distributed in the container along the cross axis. The spacing between each two adjacent items, the spacing between the start edge and the first item, and the spacing between the end edge and the last item, are the same. ```ts - Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceEvenly }) { Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) Text('2').width('60%').height(20).backgroundColor(0xD2B48C) Text('3').width('40%').height(20).backgroundColor(0xD2B48C) @@ -496,7 +496,7 @@ When the size of the container in the flex layout is not large enough, the follo }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) ``` - ![](figures/flexbasis.png) + ![flexbasis](figures/flexbasis.png) - **flexGrow**: percentage of the flex layout's remaining space that is allocated to the child component. In other words, it is the grow factor of the child component. @@ -508,7 +508,7 @@ When the size of the container in the flex layout is not large enough, the follo .height(100) .backgroundColor(0xF5DEB3) - Text('flexGrow(3)') + Text('flexGrow(2)') .flexGrow(2) .width(100) .height(100) @@ -521,7 +521,7 @@ When the size of the container in the flex layout is not large enough, the follo }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) ``` - ![](figures/flexgrow.png) + ![flexgrow](figures/flexgrow.png) In the preceding figure, the width of the parent container is 400 vp, the original width of the three child components is 100 vp, which adds up to the total width of 300 vp. The remaining space 100 vp is allocated to the child components based on their **flexGrow** settings. Child components that do not have **flexGrow** set are not involved in the allocation of remaining space. The first child component and the second child component receive their share of remaining space at the 2:3 ratio. The width of the first child component is 100 vp + 100 vp x 2/5 = 140 vp, and the width of the second child component is 100 vp + 100 vp x 3/5 = 160 vp. @@ -549,7 +549,7 @@ The first child component and the second child component receive their share of }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) ``` - ![](figures/flexshrink.png) + ![flexshrink](figures/flexshrink.png) ## Example Scenario diff --git a/en/application-dev/ui/ui-ts-layout-grid.md b/en/application-dev/ui/ui-ts-layout-grid.md index c736c25f7ccb85c67524651e5d5068224c0d004d..941519f0a3d86bf980d1595e48536e1c9e6b069a 100644 --- a/en/application-dev/ui/ui-ts-layout-grid.md +++ b/en/application-dev/ui/ui-ts-layout-grid.md @@ -159,7 +159,7 @@ Grid() { .fontSize(16) .textAlign(TextAlign.Center) .textStyle() - }.rowStart(2).rowEnd(3) // The grid item spans the second and third columns. + }.rowStart(2).rowEnd(3) // The grid item spans the second and third rows. GridItem() { Text('4') diff --git a/en/application-dev/ui/ui-ts-layout-mediaquery.md b/en/application-dev/ui/ui-ts-layout-mediaquery.md index 2ff489108f81cd46d1d17af1d579181090827fce..205265a30d244ad6100e0f1fc0a19c81859ae3d3 100644 --- a/en/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/en/application-dev/ui/ui-ts-layout-mediaquery.md @@ -1,27 +1,31 @@ # Media Query +[Media queries](../reference/apis/js-apis-mediaquery.md) are at the core of responsive design and widely used on mobile devices. You can use them to create different application styles depending on the device type or device state. Specifically, media queries allow you to: -Media queries are widely used on mobile devices. You can use them to modify the application style based on the device type or specific features and device parameters (such as the screen resolution). Specifically, media queries allow you to: - - -1. Design a layout style based on the device and app attributes. +1. Design a layout style based on the device and application attributes (such as display area, dark light color, and resolution). 2. Update the page layout to adapt to dynamic screen changes (for example, screen splitting or switching between landscape and portrait modes). + ## Usage Invoke the **mediaquery** API to set the media query condition and the callback, and change the page layout or implement service logic in the callback corresponding to the condition. -First, import the mediaquery module, as shown below: +First, import the **mediaquery** module, as shown below: + ```ts import mediaquery from '@ohos.mediaquery' ``` + Then, use the **matchMediaSync** API to set the media query condition and save the returned listener, as shown below: + ```ts listener = mediaquery.matchMediaSync('(orientation: landscape)') ``` -Finally, register the callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows: + +Finally, register the **onPortrait** callback using the saved listener, and change the page layout or implement service logic in the callback. When the media query condition is matched, the callback is triggered. The sample code is as follows: + ```ts onPortrait(mediaQueryResult) { if (mediaQueryResult.matches) { @@ -33,19 +37,25 @@ onPortrait(mediaQueryResult) { listener.on('change', onPortrait) ``` -## Syntax of Media Query Conditions +## Media Query Conditions + +The media query condition consists of the media type (optional), logical operator, and media feature. The logical operator is used to connect different media types and media features. A media feature must be enclosed in parentheses (). There may be multiple media features. The specific rules are as follows: + +### Syntax + ``` [media-type] [and|not|only] [(media-feature)] ``` + Examples are as follows: - `screen and (round-screen: true)` // The query is valid when the device screen is round. +**screen and (round-screen: true)**: The query is valid when the device screen is round. - `(max-height: 800)` // The query is valid when the height does not exceed 800. +**(max-height: 800)**: The query is valid when the height is less than or equal to 800. - `(height <= 800)` // The query is valid when the height does not exceed 800. +**(height <= 800)**: The query is valid when the height is less than or equal to 800. - `screen and (device-type: tv) or (resolution < 2)` // The query is valid only when all media features are true. +**screen and (device-type: tv) or (resolution < 2)**: The query is valid when the device type is TV or the device resolution is less than 2. This is a multi-condition query that contains multiple media features. ### media-type @@ -53,59 +63,58 @@ Examples are as follows: | ------ | -------------- | | screen | Media query based on screen-related parameters.| - -### Media Logic Operation (and|not|only) +### Media Logic Operation (and|or|not|only) You can use logical operators (**and**, **or**, **not**, and **only**) to compose complex media queries. You can also combine them using comma (,). The following table describes the operators. -**Table 1** Media logical operators + **Table 1** Media logical operators | Type | Description | | -------- | ---------------------------------------- | -| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.
For example, **screen and (device-type: wearable) and (max-height: 600) ** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.| -| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.
For example, **screen and (max-height: 1000) or (round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round. | -| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.
For example, **not screen and (min-height: 50) and (max-height: 600) ** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.
**NOTE**
When the **not** operator is used, the media type must be specified. | -| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:
screen and (min-height: 50)
The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.
**NOTE**
When the **only** operator is used, the media type must be specified. | -| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.
For example, **screen and (min-height: 1000), (round-screen: true) ** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.| +| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.
For example, **screen and (device-type: wearable) and (max-height: 600)** indicates that the query is valid when the device type is wearable and the maximum height of the application is 600 pixel units.| +| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.
For example, **screen and (max-height: 1000) or (round-screen: true)** indicates that the query is valid when the maximum height of the application is 1000 pixel units or the device screen is round.| +| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned.
For example, **not screen and (min-height: 50) and (max-height: 600)** indicates that the query is valid when the height of the application is less than 50 pixel units or greater than 600 pixel units.
You must specify the media type when using the **not** operator.| +| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:
screen and (min-height: 50)
The browsers of earlier versions would mislead this sentence into screen, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.
You must specify the media type when using the **only** operator.| +| , (comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.
For example, **screen and (min-height: 1000), (round-screen: true)** indicates that the query is valid when the minimum height of the application is 1000 pixel units or the device screen is round.| At MediaQuery Level 4, range query is imported so that you can use the operators including <=, >=, <, and > besides the max- and min-operators. -**Table 2** Logical operators for range query + **Table 2** Logical operators for range query | Type | Description | | ----- | ---------------------------------------- | -| <= | Less than or equal to, for example, **screen and (50 <= height)**.| -| >= | Greater than or equal to, for example, **screen and (600 >= height)**.| -| < | Less than, for example, **screen and (50 < height)**.| -| > | Greater than, for example, **screen and (600 > height)**.| - +| < = | Less than or equal to, for example, **screen and (50 <= height)**.| +| > = | Greater than or equal to, for example, **screen and (600 >= height)**.| +| < | Less than, for example, **screen and (50 < height)**.| +| > | Greater than, for example, **screen and (600 > height)**.| ### media-feature -| Type | Description | -| ----------------- | ---------------------------------------- | -| height | Height of the display area on the application page. | -| min-height | Minimum height of the display area on the application page. | -| max-height | Maximum height of the display area on the application page. | -| width | Width of the display area on the app page. | -| min-width | Minimum width of the display area on the application page. | -| max-width | Maximum width of the display area on the application page. | +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| height | Height of the display area on the application page. | +| min-height | Minimum height of the display area on the application page. | +| max-height | Maximum height of the display area on the application page. | +| width | Width of the display area on the app page. | +| min-width | Minimum width of the display area on the application page. | +| max-width | Maximum width of the display area on the application page. | | resolution | Resolution of the device. The unit can be dpi, dppx, or dpcm.
- **dpi** indicates the number of physical pixels per inch. 1 dpi ≈ 0.39 dpcm.
- **dpcm** indicates the number of physical pixels per centimeter. 1 dpcm ≈ 2.54 dpi.
- **dppx** indicates the number of physical pixels in each pixel. (This unit is calculated based on this formula: 96 px = 1 inch, which is different from the calculation method of the px unit on the page.) 1 dppx = 96 dpi.| -| min-resolution | Minimum device resolution. | -| max-resolution | Maximum device resolution. | +| min-resolution | Minimum device resolution. | +| max-resolution | Maximum device resolution. | | orientation | Screen orientation.
Options are as follows:
- orientation: portrait
- orientation: landscape| -| device-height | Height of the device. | -| min-device-height | Minimum height of the device. | -| max-device-height | Maximum height of the device. | -| device-width | Width of the device. | -| min-device-width | Minimum width of the device. | -| max-device-width | Maximum width of the device. | +| device-height | Height of the device. | +| min-device-height | Minimum height of the device. | +| max-device-height | Maximum height of the device. | +| device-width | Width of the device. | +| device-type | Type of the device.
Value range: **default** | +| min-device-width | Minimum width of the device. | +| max-device-width | Maximum width of the device. | | round-screen | Screen type. The value **true** means that the screen is round, and **false** means the opposite. | -| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite. | +| dark-mode | Whether the device is in dark mode. The value **true** means that the device is in dark mode, and **false** means the opposite. | ## Example Scenario -Use media queries to apply different content and styles to the page text when the screen is switched between landscape and portrait modes. +In the following example, media queries are used to apply different content and styles to the page text when the screen is switched between landscape and portrait modes. ```ts import mediaquery from '@ohos.mediaquery' @@ -142,8 +151,11 @@ struct MediaQueryExample { } } ``` -When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700.
+ +When the device is in landscape orientation, the text content is displayed in landscape mode in the color of #FFD700. + ![en-us_image_0000001262954829](figures/en-us_image_0000001262954829.png) -When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093.
-![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png) \ No newline at end of file +When the device is not in landscape orientation, the text content is displayed in portrait mode in the color of #DB7093. + +![en-us_image_0000001263074739](figures/en-us_image_0000001263074739.png) diff --git a/en/application-dev/webgl/webgl-guidelines.md b/en/application-dev/webgl/webgl-guidelines.md index b169d0586096c5e5932da39625fe656b50b21733..dc0001c50222b72b0e81f94842a6b1552dcf6ca2 100644 --- a/en/application-dev/webgl/webgl-guidelines.md +++ b/en/application-dev/webgl/webgl-guidelines.md @@ -4,6 +4,10 @@ WebGL helps you process graphics at the frontend, for example, drawing color graphics. +> **NOTE** +> +> WebGL can be used only in the JavaScript-compatible web-like development paradigm. + ## Available APIs @@ -696,6 +700,7 @@ To use WebGL to draw a color triangle (GPU drawing), perform the following steps } ``` + **Figure 2** Effect of clicking the button to draw a color triangle ![en-us_image_0000001192429306](figures/en-us_image_0000001192429306.gif) diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 34fb5393b7ca3ebec8b7b5762606f576981bf77b..2364014ef49503250393370882bcb6ebae8d4a48 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -1,5 +1,4 @@ # Application Development - - [Application Development Overview](application-dev-guide.md) - Quick Start - Getting Started @@ -72,7 +71,7 @@ - [Using Explicit Want to Start an Ability](application-models/ability-startup-with-explicit-want.md) - [Using Implicit Want to Open a Website](application-models/ability-startup-with-implicit-want.md) - [Using Want to Share Data Between Applications](application-models/data-share-via-want.md) - - [Component Startup Rules](application-models/component-startup-rules.md) + - [Component Startup Rules (Stage Model)](application-models/component-startup-rules.md) - Inter-Device Application Component Interaction (Continuation) - [Continuation Overview](application-models/inter-device-interaction-hop-overview.md) - [Cross-Device Migration](application-models/hop-cross-device-migration.md) @@ -269,11 +268,14 @@ - [Animation Effect](ui/ui-js-animate-dynamic-effects.md) - [Animation Frame](ui/ui-js-animate-frame.md) - [Custom Components](ui/ui-js-custom-components.md) - - Common Event and Notification - - [Common Event and Notification Overview](notification/notification-brief.md) - - [Common Event Development](notification/common-event.md) - - [Notification Development](notification/notification-guidelines.md) - - [Debugging Assistant Usage](notification/assistant-guidelines.md) + - Notification + - [Notification Overview](notification/notification-overview.md) + - [Notification Subscription (Open Only to System Applications)](notification/notification-subscription.md) + - [Enabling Notification](notification/notification-enable.md) + - Publishing a Notification + - [Publishing a Basic Notification](notification/text-notification.md) + - [Publishing a Progress Notification](notification/progress-bar-notification.md) + - [Adding a WantAgent Object to a Notification](notification/notification-with-wantagent.md) - Window Manager - [Window Overview](windowmanager/window-overview.md) - [Application Window Development (Stage Mode)](windowmanager/application-window-stage.md) @@ -283,10 +285,8 @@ - [WebGL Overview](webgl/webgl-overview.md) - [WebGL Development](webgl/webgl-guidelines.md) - Media - - Audio + - Audio and Video - [Audio Overview](media/audio-overview.md) - - [Audio Playback Development](media/audio-playback.md) - - [Audio Recording Development](media/audio-recorder.md) - [Audio Rendering Development](media/audio-renderer.md) - [Audio Stream Management Development](media/audio-stream-manager.md) - [Audio Capture Development](media/audio-capturer.md) @@ -295,7 +295,10 @@ - [Audio Interruption Mode Development](media/audio-interruptmode.md) - [Volume Management Development](media/audio-volume-manager.md) - [Audio Routing and Device Management Development](media/audio-routing-manager.md) - - Video + - [AVPlayer Development (Recommended)](media/avplayer-playback.md) + - [AVRecorder Development (Recommended)](media/avrecorder.md) + - [Audio Playback Development](media/audio-playback.md) + - [Audio Recording Development](media/audio-recorder.md) - [Video Playback Development](media/video-playback.md) - [Video Recording Development](media/video-recorder.md) - AVSession @@ -321,6 +324,9 @@ - Crypto Framework - [Crypto Framework Overview](security/cryptoFramework-overview.md) - [Crypto Framework Development](security/cryptoFramework-guidelines.md) + - Certificate + - [Certificate Overview](security/cert-overview.md) + - [Certificate Development](security/cert-guidelines.md) - hapsigner - [hapsigner Overview](security/hapsigntool-overview.md) - [hapsigner Guide](security/hapsigntool-guidelines.md) @@ -337,8 +343,8 @@ - [Subscribing to State Changes of a Remote Object](connectivity/subscribe-remote-state.md) - Telephony - [Telephony Service Overview](telephony/telephony-overview.md) - - [Redirecting to the Dial Screen](telephony/jumping-to-the-dial-screen.md) - - [Obtaining Current Cellular Network Signal Information](telephony/cellular-network-signal-info.md) + - [Call Service Development](telephony/telephony-call.md) + - [SMS Service Development](telephony/telephony-sms.md) - Data Management - Distributed Data Service - [Distributed Data Service Overview](database/database-mdds-overview.md) @@ -363,12 +369,14 @@ - [Album Management](file-management/medialibrary-album-guidelines.md) - File Access Framework - [File Access Framework Overview](file-management/file-access-framework-overview.md) + - [FilePicker Guide](file-management/filepicker-guidelines.md) - Task Management - Background Task Management - [Background Task Management Overview](task-management/background-task-overview.md) - [Transient Task Development](task-management/transient-task-dev-guide.md) - [Continuous Task Development](task-management/continuous-task-dev-guide.md) - [Work Scheduler Development](task-management/work-scheduler-dev-guide.md) + - [WorkSchedulerExtensionAbility Development](task-management/workscheduler-extensionability.md) - [Efficiency Resource Request Development](task-management/efficiency-resources-apply-dev-guide.md) - Agent-Powered Reminder - [Agent-Powered Reminder Overview](task-management/reminder-agent-overview.md) @@ -378,9 +386,7 @@ - [USB Service Overview](device/usb-overview.md) - [USB Service Development](device/usb-guidelines.md) - Location - - [Location Overview](device/device-location-overview.md) - - [Obtaining Device Location Information](device/device-location-info.md) - - [Geocoding and Reverse Geocoding Capabilities](device/device-location-geocoding.md) + - [Location Development](device/location-guidelines.md) - Sensor - [Sensor Overview](device/sensor-overview.md) - [Sensor Development](device/sensor-guidelines.md) @@ -496,6 +502,7 @@ - [DataPanel](reference/arkui-ts/ts-basic-components-datapanel.md) - [DatePicker](reference/arkui-ts/ts-basic-components-datepicker.md) - [Divider](reference/arkui-ts/ts-basic-components-divider.md) + - [Formcomponent](reference/arkui-ts/ts-basic-components-formcomponent.md) - [Gauge](reference/arkui-ts/ts-basic-components-gauge.md) - [Image](reference/arkui-ts/ts-basic-components-image.md) - [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md) @@ -745,71 +752,60 @@ - [API Reference Document Description](reference/apis/development-intro.md) - Ability Framework - Stage Model (Recommended) - - [@ohos.app.ability.Ability](reference/apis/js-apis-app-ability-ability.md) - - [@ohos.app.ability.AbilityConstant](reference/apis/js-apis-app-ability-abilityConstant.md) - - [@ohos.app.ability.abilityLifecycleCallback](reference/apis/js-apis-app-ability-abilityLifecycleCallback.md) - - [@ohos.app.ability.AbilityStage](reference/apis/js-apis-app-ability-abilityStage.md) - - [@ohos.app.ability.common](reference/apis/js-apis-app-ability-common.md) - - [@ohos.app.ability.contextConstant](reference/apis/js-apis-app-ability-contextConstant.md) - - [@ohos.app.ability.EnvironmentCallback](reference/apis/js-apis-app-ability-environmentCallback.md) - - [@ohos.app.ability.ExtensionAbility](reference/apis/js-apis-app-ability-extensionAbility.md) - - [@ohos.app.ability.ServiceExtensionAbility](reference/apis/js-apis-app-ability-serviceExtensionAbility.md) - - [@ohos.app.ability.StartOptions](reference/apis/js-apis-app-ability-startOptions.md) - - [@ohos.app.ability.UIAbility](reference/apis/js-apis-app-ability-uiAbility.md) - - [@ohos.app.form.FormExtensionAbility](reference/apis/js-apis-app-form-formExtensionAbility.md) + - [@ohos.app.ability.Ability (Ability Base Class)](reference/apis/js-apis-app-ability-ability.md) + - [@ohos.app.ability.AbilityConstant (AbilityConstant)](reference/apis/js-apis-app-ability-abilityConstant.md) + - [@ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback)](reference/apis/js-apis-app-ability-abilityLifecycleCallback.md) + - [@ohos.app.ability.AbilityStage (AbilityStage)](reference/apis/js-apis-app-ability-abilityStage.md) + - [@ohos.app.ability.common (Context)](reference/apis/js-apis-app-ability-common.md) + - [@ohos.app.ability.contextConstant (ContextConstant)](reference/apis/js-apis-app-ability-contextConstant.md) + - [@ohos.app.ability.EnvironmentCallback (EnvironmentCallback)](reference/apis/js-apis-app-ability-environmentCallback.md) + - [@ohos.app.ability.ExtensionAbility (ExtensionAbility Base Class)](reference/apis/js-apis-app-ability-extensionAbility.md) + - [@ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility)](reference/apis/js-apis-app-ability-serviceExtensionAbility.md) + - [@ohos.app.ability.StartOptions (StartOptions)](reference/apis/js-apis-app-ability-startOptions.md) + - [@ohos.app.ability.UIAbility (UIAbility)](reference/apis/js-apis-app-ability-uiAbility.md) + - [@ohos.app.form.FormExtensionAbility (FormExtensionAbility)](reference/apis/js-apis-app-form-formExtensionAbility.md) + - [@ohos.application.DataShareExtensionAbility (DataShare Extension Ability)](reference/apis/js-apis-application-dataShareExtensionAbility.md) + - [@ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility)](reference/apis/js-apis-application-staticSubscriberExtensionAbility.md) - Stage Model (To Be Deprecated Soon) - - [@ohos.application.Ability](reference/apis/js-apis-application-ability.md) - - [@ohos.application.AbilityConstant](reference/apis/js-apis-application-abilityConstant.md) - - [@ohos.application.AbilityLifecycleCallback](reference/apis/js-apis-application-abilityLifecycleCallback.md) - - [@ohos.application.AbilityStage](reference/apis/js-apis-application-abilityStage.md) - - [@ohos.application.context](reference/apis/js-apis-application-context.md) - - [@ohos.application.DataShareExtensionAbility](reference/apis/js-apis-application-dataShareExtensionAbility.md) - - [@ohos.application.EnvironmentCallback](reference/apis/js-apis-application-environmentCallback.md) - - [@ohos.application.ExtensionAbility](reference/apis/js-apis-application-extensionAbility.md) - - [@ohos.application.FormExtension](reference/apis/js-apis-application-formExtension.md) - - [@ohos.application.ServiceExtensionAbility](reference/apis/js-apis-application-serviceExtensionAbility.md) - - [@ohos.application.StartOptions](reference/apis/js-apis-application-startOptions.md) - - [@ohos.application.StaticSubscriberExtensionAbility](reference/apis/js-apis-application-staticSubscriberExtensionAbility.md) + - [@ohos.application.EnvironmentCallback (EnvironmentCallback)](reference/apis/js-apis-application-environmentCallback.md) - FA Model - - [@ohos.ability.ability](reference/apis/js-apis-ability-ability.md) - - [@ohos.ability.featureAbility](reference/apis/js-apis-ability-featureAbility.md) - - [@ohos.ability.particleAbility](reference/apis/js-apis-ability-particleAbility.md) + - [@ohos.ability.ability (Ability)](reference/apis/js-apis-ability-ability.md) + - [@ohos.ability.featureAbility (FeatureAbility)](reference/apis/js-apis-ability-featureAbility.md) + - [@ohos.ability.particleAbility (ParticleAbility)](reference/apis/js-apis-ability-particleAbility.md) - Both Models (Recommended) - - [@ohos.app.ability.abilityDelegatorRegistry](reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md) - - [@ohos.app.ability.abilityManager](reference/apis/js-apis-app-ability-abilityManager.md) - - [@ohos.app.ability.appManager](reference/apis/js-apis-app-ability-appManager.md) - - [@ohos.app.ability.appRecovery](reference/apis/js-apis-app-ability-appRecovery.md) - - [@ohos.app.ability.Configuration](reference/apis/js-apis-app-ability-configuration.md) - - [@ohos.app.ability.ConfigurationConstant](reference/apis/js-apis-app-ability-configurationConstant.md) - - [@ohos.app.ability.dataUriUtils](reference/apis/js-apis-app-ability-dataUriUtils.md) - - [@ohos.app.ability.errorManager](reference/apis/js-apis-app-ability-errorManager.md) - - [@ohos.app.ability.missionManager](reference/apis/js-apis-app-ability-missionManager.md) - - [@ohos.app.ability.quickFixManager](reference/apis/js-apis-app-ability-quickFixManager.md) - - [@ohos.app.ability.Want](reference/apis/js-apis-app-ability-want.md) - - [@ohos.app.ability.wantAgent](reference/apis/js-apis-app-ability-wantAgent.md) - - [@ohos.app.ability.wantConstant](reference/apis/js-apis-app-ability-wantConstant.md) - - [@ohos.app.form.formBindingData](reference/apis/js-apis-app-form-formBindingData.md) - - [@ohos.app.form.formHost](reference/apis/js-apis-app-form-formHost.md) - - [@ohos.app.form.formInfo](reference/apis/js-apis-app-form-formInfo.md) - - [@ohos.app.form.formProvider](reference/apis/js-apis-app-form-formProvider.md) + - [@ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry)](reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md) + - [@ohos.app.ability.abilityManager (AbilityManager)](reference/apis/js-apis-app-ability-abilityManager.md) + - [@ohos.app.ability.appManager (appManager)](reference/apis/js-apis-app-ability-appManager.md) + - [@ohos.app.ability.appRecovery (appRecovery)](reference/apis/js-apis-app-ability-appRecovery.md) + - [@ohos.app.ability.Configuration (Configuration)](reference/apis/js-apis-app-ability-configuration.md) + - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](reference/apis/js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.errorManager (ErrorManager)](reference/apis/js-apis-app-ability-errorManager.md) + - [@ohos.app.ability.missionManager (missionManager)](reference/apis/js-apis-app-ability-missionManager.md) + - [@ohos.app.ability.quickFixManager (quickFixManager)](reference/apis/js-apis-app-ability-quickFixManager.md) + - [@ohos.app.ability.Want (Want)](reference/apis/js-apis-app-ability-want.md) + - [@ohos.app.ability.wantAgent (WantAgent)](reference/apis/js-apis-app-ability-wantAgent.md) + - [@ohos.app.ability.wantConstant (wantConstant)](reference/apis/js-apis-app-ability-wantConstant.md) + - [@ohos.app.form.formBindingData (formBindingData)](reference/apis/js-apis-app-form-formBindingData.md) + - [@ohos.app.form.formHost (FormHost)](reference/apis/js-apis-app-form-formHost.md) + - [@ohos.app.form.formInfo (FormInfo)](reference/apis/js-apis-app-form-formInfo.md) + - [@ohos.app.form.formProvider (FormProvider)](reference/apis/js-apis-app-form-formProvider.md) - Both Models (To Be Deprecated Soon) - - [@ohos.ability.dataUriUtils](reference/apis/js-apis-ability-dataUriUtils.md) - - [@ohos.ability.errorCode](reference/apis/js-apis-ability-errorCode.md) - - [@ohos.ability.wantConstant](reference/apis/js-apis-ability-wantConstant.md) - - [@ohos.application.abilityDelegatorRegistry](reference/apis/js-apis-application-abilityDelegatorRegistry.md) - - [@ohos.application.abilityManager](reference/apis/js-apis-application-abilityManager.md) - - [@ohos.application.appManager](reference/apis/js-apis-application-appManager.md) - - [@ohos.application.Configuration](reference/apis/js-apis-application-configuration.md) - - [@ohos.application.ConfigurationConstant](reference/apis/js-apis-application-configurationConstant.md) - - [@ohos.application.errorManager](reference/apis/js-apis-application-errorManager.md) - - [@ohos.application.formBindingData](reference/apis/js-apis-application-formBindingData.md) - - [@ohos.application.formError](reference/apis/js-apis-application-formError.md) - - [@ohos.application.formHost](reference/apis/js-apis-application-formHost.md) - - [@ohos.application.formInfo](reference/apis/js-apis-application-formInfo.md) - - [@ohos.application.formProvider](reference/apis/js-apis-application-formProvider.md) - - [@ohos.application.missionManager](reference/apis/js-apis-application-missionManager.md) - - [@ohos.application.Want](reference/apis/js-apis-application-want.md) - - [@ohos.wantAgent](reference/apis/js-apis-wantAgent.md) + - [@ohos.ability.dataUriUtils (DataUriUtils)](reference/apis/js-apis-ability-dataUriUtils.md) + - [@ohos.ability.errorCode (ErrorCode)](reference/apis/js-apis-ability-errorCode.md) + - [@ohos.ability.wantConstant (wantConstant)](reference/apis/js-apis-ability-wantConstant.md) + - [@ohos.application.abilityDelegatorRegistry (AbilityDelegatorRegistry)](reference/apis/js-apis-application-abilityDelegatorRegistry.md) + - [@ohos.application.abilityManager (AbilityManager)](reference/apis/js-apis-application-abilityManager.md) + - [@ohos.application.appManager (appManager)](reference/apis/js-apis-application-appManager.md) + - [@ohos.application.Configuration (Configuration)](reference/apis/js-apis-application-configuration.md) + - [@ohos.application.ConfigurationConstant (ConfigurationConstant)](reference/apis/js-apis-application-configurationConstant.md) + - [@ohos.application.formBindingData (formBindingData)](reference/apis/js-apis-application-formBindingData.md) + - [@ohos.application.formError (FormError)](reference/apis/js-apis-application-formError.md) + - [@ohos.application.formHost (FormHost)](reference/apis/js-apis-application-formHost.md) + - [@ohos.application.formInfo (FormInfo)](reference/apis/js-apis-application-formInfo.md) + - [@ohos.application.formProvider (FormProvider)](reference/apis/js-apis-application-formProvider.md) + - [@ohos.application.missionManager (missionManager)](reference/apis/js-apis-application-missionManager.md) + - [@ohos.application.Want (Want)](reference/apis/js-apis-application-want.md) + - [@ohos.wantAgent (WantAgent)](reference/apis/js-apis-wantAgent.md) - Dependent Elements and Definitions - ability - [abilityResult](reference/apis/js-apis-inner-ability-abilityResult.md) @@ -824,7 +820,6 @@ - [context](reference/apis/js-apis-inner-app-context.md) - [processInfo](reference/apis/js-apis-inner-app-processInfo.md) - application - - [AbilityContext](reference/apis/js-apis-ability-context.md) - [abilityDelegator](reference/apis/js-apis-inner-application-abilityDelegator.md) - [abilityDelegatorArgs](reference/apis/js-apis-inner-application-abilityDelegatorArgs.md) - [abilityMonitor](reference/apis/js-apis-inner-application-abilityMonitor.md) @@ -849,13 +844,13 @@ - [MissionListener](reference/apis/js-apis-inner-application-missionListener.md) - [MissionParameter](reference/apis/js-apis-inner-application-missionParameter.md) - [MissionSnapshot](reference/apis/js-apis-inner-application-missionSnapshot.md) - - [PermissionRequestResult](reference/apis/js-apis-inner-application-permissionRequestResult.md) - [ProcessData](reference/apis/js-apis-inner-application-processData.md) - [ProcessRunningInfo](reference/apis/js-apis-inner-application-processRunningInfo.md) - - [ProcessRunningInformation](reference/apis/js-apis-inner-application-processRunningInformation.md) + - [ProcessInformation](reference/apis/js-apis-inner-application-processInformation.md) - [ServiceExtensionContext](reference/apis/js-apis-inner-application-serviceExtensionContext.md) - [UIAbilityContext](reference/apis/js-apis-inner-application-uiAbilityContext.md) - [shellCmdResult](reference/apis/js-apis-inner-application-shellCmdResult.md) + - [WindowExtensionContext](reference/apis/js-apis-inner-application-windowExtensionContext.md) - wantAgent - [triggerInfo](reference/apis/js-apis-inner-wantAgent-triggerInfo.md) - [wantAgentInfo](reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) @@ -865,24 +860,24 @@ - [continuationExtraParams](reference/apis/js-apis-continuation-continuationExtraParams.md) - [continuationResult](reference/apis/js-apis-continuation-continuationResult.md) - Common Event and Notification - - [@ohos.commonEventManager](reference/apis/js-apis-commonEventManager.md) - - [@ohos.events.emitter](reference/apis/js-apis-emitter.md) - - [@ohos.notificationManager (Recommended)](reference/apis/js-apis-notificationManager.md) - - [@ohos.notificationSubscribe (Recommended)](reference/apis/js-apis-notificationSubscribe.md) - - [@ohos.commonEvent (To Be Deprecated Soon)](reference/apis/js-apis-commonEvent.md) - - [@ohos.notification](reference/apis/js-apis-notification.md) + - [@ohos.commonEventManager (Common Event) (Recommended)](reference/apis/js-apis-commonEventManager.md) + - [@ohos.events.emitter (Emitter)](reference/apis/js-apis-emitter.md) + - [@ohos.notificationManager (NotificationManager) (Recommended)](reference/apis/js-apis-notificationManager.md) + - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](reference/apis/js-apis-notificationSubscribe.md) + - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](reference/apis/js-apis-commonEvent.md) + - [@ohos.notification (Notification) (To Be Deprecated Soon)](reference/apis/js-apis-notification.md) - application - [EventHub](reference/apis/js-apis-inner-application-eventHub.md) - Bundle Management - - [@ohos.bundle.appControl](reference/apis/js-apis-appControl.md) - - [@ohos.bundle.bundleManager](reference/apis/js-apis-bundleManager.md) - - [@ohos.bundle.bundleMonitor](reference/apis/js-apis-bundleMonitor.md) - - [@ohos.bundle.defaultAppManager](reference/apis/js-apis-defaultAppManager.md) - - [@ohos.bundle.distributedBundle](reference/apis/js-apis-distributedBundle.md) - - [@ohos.bundle.freeInstall](reference/apis/js-apis-freeInstall.md) - - [@ohos.bundle.installer](reference/apis/js-apis-installer.md) - - [@ohos.bundle.launcherBundleManager](reference/apis/js-apis-launcherBundleManager.md) - - [@ohos.zlib](reference/apis/js-apis-zlib.md) + - [@ohos.bundle.appControl(appControl)](reference/apis/js-apis-appControl.md) + - [@ohos.bundle.bundleManager (bundleManager)](reference/apis/js-apis-bundleManager.md) + - [@ohos.bundle.bundleMonitor (bundleMonitor)](reference/apis/js-apis-bundleMonitor.md) + - [@ohos.bundle.defaultAppManager (Default Application Management)](reference/apis/js-apis-defaultAppManager.md) + - [@ohos.bundle.distributedBundle (distributedBundleManager)](reference/apis/js-apis-distributedBundleManager.md) + - [@ohos.bundle.freeInstall (freeInstall)](reference/apis/js-apis-freeInstall.md) + - [@ohos.bundle.installer (installer)](reference/apis/js-apis-installer.md) + - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](reference/apis/js-apis-launcherBundleManager.md) + - [@ohos.zlib (Zip)](reference/apis/js-apis-zlib.md) - bundleManager - [abilityInfo](reference/apis/js-apis-bundleManager-abilityInfo.md) - [applicationInfo](reference/apis/js-apis-bundleManager-applicationInfo.md) @@ -893,235 +888,244 @@ - [hapModuleInfo](reference/apis/js-apis-bundleManager-hapModuleInfo.md) - [launcherAbilityInfo](reference/apis/js-apis-bundleManager-launcherAbilityInfo.md) - [metadata](reference/apis/js-apis-bundleManager-metadata.md) - - [packInfo](reference/apis/js-apis-bundleManager-packInfo.md) - [permissionDef](reference/apis/js-apis-bundleManager-permissionDef.md) - [remoteAbilityInfo](reference/apis/js-apis-bundleManager-remoteAbilityInfo.md) - [shortcutInfo](reference/apis/js-apis-bundleManager-shortcutInfo.md) - UI Page - - [@ohos.animator](reference/apis/js-apis-animator.md) - - [@ohos.curves](reference/apis/js-apis-curve.md) - - [@ohos.matrix4](reference/apis/js-apis-matrix4.md) - - [@ohos.mediaquery](reference/apis/js-apis-mediaquery.md) - - [@ohos.promptAction](reference/apis/js-apis-promptAction.md) - - [@ohos.router](reference/apis/js-apis-router.md) + - [@ohos.animator (Animator)](reference/apis/js-apis-animator.md) + - [@ohos.curves (Interpolation Calculation)](reference/apis/js-apis-curve.md) + - [@ohos.matrix4 (Matrix Transformation)](reference/apis/js-apis-matrix4.md) + - [@ohos.mediaquery (Media Query)](reference/apis/js-apis-mediaquery.md) + - [@ohos.promptAction (Prompt)](reference/apis/js-apis-promptAction.md) + - [@ohos.router (Page Routing)](reference/apis/js-apis-router.md) - Graphics - - [@ohos.animation.windowAnimationManager](reference/apis/js-apis-windowAnimationManager.md) - - [@ohos.application.WindowExtensionAbility](reference/apis/js-apis-application-windowExtensionAbility.md) - - [@ohos.display](reference/apis/js-apis-display.md) - - [@ohos.effectKit](reference/apis/js-apis-effectKit.md) - - [@ohos.graphics.colorSpaceManager](reference/apis/js-apis-colorSpaceManager.md) - - [@ohos.screen](reference/apis/js-apis-screen.md) - - [@ohos.screenshot](reference/apis/js-apis-screenshot.md) - - [@ohos.window](reference/apis/js-apis-window.md) + - [@ohos.animation.windowAnimationManager (Window Animation Management)](reference/apis/js-apis-windowAnimationManager.md) + - [@ohos.application.WindowExtensionAbility (WindowExtensionAbility)](reference/apis/js-apis-application-windowExtensionAbility.md) + - [@ohos.display (Display)](reference/apis/js-apis-display.md) + - [@ohos.effectKit (Image Effects)](reference/apis/js-apis-effectKit.md) + - [@ohos.graphics.colorSpaceManager (Color Space Management)](reference/apis/js-apis-colorSpaceManager.md) + - [@ohos.screen (Screen)](reference/apis/js-apis-screen.md) + - [@ohos.screenshot (Screenshot)](reference/apis/js-apis-screenshot.md) + - [@ohos.window (Window)](reference/apis/js-apis-window.md) - webgl - - [webgl](reference/apis/js-apis-webgl.md) - - [webgl2](reference/apis/js-apis-webgl2.md) + - [WebGL](reference/apis/js-apis-webgl.md) + - [WebGL2](reference/apis/js-apis-webgl2.md) - Media - - [@ohos.multimedia.audio](reference/apis/js-apis-audio.md) - - [@ohos.multimedia.avsession](reference/apis/js-apis-avsession.md) - - [@ohos.multimedia.camera](reference/apis/js-apis-camera.md) - - [@ohos.multimedia.image](reference/apis/js-apis-image.md) - - [@ohos.multimedia.media](reference/apis/js-apis-media.md) + - [@ohos.multimedia.audio (Audio Management)](reference/apis/js-apis-audio.md) + - [@ohos.multimedia.avsession (AVSession Management)](reference/apis/js-apis-avsession.md) + - [@ohos.multimedia.camera (Camera Management)](reference/apis/js-apis-camera.md) + - [@ohos.multimedia.image (Image Processing)](reference/apis/js-apis-image.md) + - [@ohos.multimedia.media (Media)](reference/apis/js-apis-media.md) - Resource Management - - [@ohos.i18n](reference/apis/js-apis-i18n.md) - - [@ohos.intl](reference/apis/js-apis-intl.md) - - [@ohos.resourceManager](reference/apis/js-apis-resource-manager.md) + - [@ohos.i18n (Internationalization)](reference/apis/js-apis-i18n.md) + - [@ohos.intl (Internationalization)](reference/apis/js-apis-intl.md) + - [@ohos.resourceManager (Resource Manager)](reference/apis/js-apis-resource-manager.md) - Resource Scheduling - - [@ohos.distributedMissionManager](reference/apis/js-apis-distributedMissionManager.md) - - [@ohos.reminderAgentManager](reference/apis/js-apis-reminderAgentManager.md) - - [@ohos.resourceschedule.backgroundTaskManager](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) - - [@ohos.resourceschedule.workScheduler](reference/apis/js-apis-resourceschedule-workScheduler.md) - - [@ohos.resourceschedule.usageStatistics](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md) - - [@ohos.WorkSchedulerExtensionAbility](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) + - [@ohos.distributedMissionManager (Distributed Mission Management)](reference/apis/js-apis-distributedMissionManager.md) + - [@ohos.reminderAgentManager (Reminder Agent Management)](reference/apis/js-apis-reminderAgentManager.md) + - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) + - [@ohos.resourceschedule.workScheduler (Work Scheduler)](reference/apis/js-apis-resourceschedule-workScheduler.md) + - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md) + - [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) - Security - - [@ohos.abilityAccessCtrl](reference/apis/js-apis-abilityAccessCtrl.md) - - [@ohos.privacyManager](reference/apis/js-apis-privacyManager.md) - - [@ohos.security.cryptoFramework](reference/apis/js-apis-cryptoFramework.md) - - [@ohos.security.huks](reference/apis/js-apis-huks.md) - - [@ohos.userIAM.faceAuth](reference/apis/js-apis-useriam-faceauth.md) - - [@ohos.userIAM.userAuth](reference/apis/js-apis-useriam-userauth.md) - - [@system.cipher](reference/apis/js-apis-system-cipher.md) + - [@ohos.abilityAccessCtrl (Ability Access Control)](reference/apis/js-apis-abilityAccessCtrl.md) + - [@ohos.privacyManager (Privacy Management)](reference/apis/js-apis-privacyManager.md) + - [@ohos.security.cert (Certificate)](reference/apis/js-apis-cert.md) + - [@ohos.security.cryptoFramework (Crypto Framework)](reference/apis/js-apis-cryptoFramework.md) + - [@ohos.security.huks (HUKS)](reference/apis/js-apis-huks.md) + - [@ohos.userIAM.faceAuth (Facial Authentication)](reference/apis/js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth (User Authentication)](reference/apis/js-apis-useriam-userauth.md) + - [@system.cipher (Cipher Algorithm)](reference/apis/js-apis-system-cipher.md) + - security + - [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md) - Data Management - - [@ohos.data.dataAbility](reference/apis/js-apis-data-ability.md) - - [@ohos.data.dataShare](reference/apis/js-apis-data-dataShare.md) - - [@ohos.data.dataSharePredicates](reference/apis/js-apis-data-dataSharePredicates.md) - - [@ohos.data.dataShareResultSet](reference/apis/js-apis-data-DataShareResultSet.md) - - [@ohos.data.distributedDataObject](reference/apis/js-apis-data-distributedobject.md) - - [@ohos.data.distributedKVStore](reference/apis/js-apis-distributedKVStore.md) - - [@ohos.data.preferences](reference/apis/js-apis-data-preferences.md) - - [@ohos.data.rdb](reference/apis/js-apis-data-rdb.md) + - [@ohos.data.dataAbility (DataAbility Predicates)](reference/apis/js-apis-data-ability.md) + - [@ohos.data.dataShare (DataShare)](reference/apis/js-apis-data-dataShare.md) + - [@ohos.data.dataSharePredicates (DataShare Predicates)](reference/apis/js-apis-data-dataSharePredicates.md) + - [@ohos.data.dataShareResultSet (DataShare Result Set)](reference/apis/js-apis-data-DataShareResultSet.md) + - [@ohos.data.distributedDataObject (Distributed Data Object)](reference/apis/js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore (Distributed KV Store)](reference/apis/js-apis-distributedKVStore.md) + - [@ohos.data.preferences (Preferences)](reference/apis/js-apis-data-preferences.md) + - [@ohos.data.relationalStore (RDB Store)](reference/apis/js-apis-data-relationalStore.md) - [@ohos.data.ValuesBucket](reference/apis/js-apis-data-valuesBucket.md) - data/rdb - - [resultSet](reference/apis/js-apis-data-resultset.md) + - [resultSet (Result Set)](reference/apis/js-apis-data-resultset.md) - File Management - - [@ohos.environment](reference/apis/js-apis-environment.md) - - [@ohos.data.fileAccess](reference/apis/js-apis-fileAccess.md) - - [@ohos.fileExtensionInfo](reference/apis/js-apis-fileExtensionInfo.md) - - [@ohos.fileio](reference/apis/js-apis-fileio.md) - - [@ohos.filemanagement.userFileManager](reference/apis/js-apis-userFileManager.md) - - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) - - [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md) - - [@ohos.statfs](reference/apis/js-apis-statfs.md) - - [@ohos.storageStatistics](reference/apis/js-apis-storage-statistics.md) - - [@ohos.volumeManager](reference/apis/js-apis-volumemanager.md) + - [@ohos.file.environment (Directory Environment Capability)](reference/apis/js-apis-file-environment.md) + - [@ohos.file.fileAccess (User File Access and Management)](reference/apis/js-apis-fileAccess.md) + - [@ohos.file.fileExtensionInfo (User File Extension Information)](reference/apis/js-apis-fileExtensionInfo.md) + - [@ohos.file.fs (File Management)](reference/apis/js-apis-file-fs.md) + - [@ohos.file.hash (File Hash Processing)](reference/apis/js-apis-file-hash.md) + - [@ohos.file.securityLabel (Data Label)](reference/apis/js-apis-file-securityLabel.md) + - [@ohos.file.statvfs (File System Space Statistics)](reference/apis/js-apis-file-statvfs.md) + - [@ohos.storageStatistics (Application Storage Statistics)](reference/apis/js-apis-file-storage-statistics.md) + - [@ohos.volumeManager (Volume Management)](reference/apis/js-apis-file-volumemanager.md) + - [@ohos.filemanagement.userFileManager (User Data Management)](reference/apis/js-apis-userFileManager.md) + - [@ohos.multimedia.medialibrary (Media Library Management)](reference/apis/js-apis-medialibrary.md) - Telephony Service - - [@ohos.contact](reference/apis/js-apis-contact.md) - - [@ohos.telephony.call](reference/apis/js-apis-call.md) - - [@ohos.telephony.data](reference/apis/js-apis-telephony-data.md) - - [@ohos.telephony.observer](reference/apis/js-apis-observer.md) - - [@ohos.telephony.radio](reference/apis/js-apis-radio.md) - - [@ohos.telephony.sim](reference/apis/js-apis-sim.md) - - [@ohos.telephony.sms](reference/apis/js-apis-sms.md) + - [@ohos.contact (Contacts)](reference/apis/js-apis-contact.md) + - [@ohos.telephony.call (Call)](reference/apis/js-apis-call.md) + - [@ohos.telephony.data (Cellular Data)](reference/apis/js-apis-telephony-data.md) + - [@ohos.telephony.observer (Observer)](reference/apis/js-apis-observer.md) + - [@ohos.telephony.radio (Network Search)](reference/apis/js-apis-radio.md) + - [@ohos.telephony.sim (SIM Management)](reference/apis/js-apis-sim.md) + - [@ohos.telephony.sms (SMS)](reference/apis/js-apis-sms.md) - Network Management - - [@ohos.net.connection](reference/apis/js-apis-net-connection.md) - - [@ohos.net.ethernet](reference/apis/js-apis-net-ethernet.md) - - [@ohos.net.http](reference/apis/js-apis-http.md) - - [@ohos.net.sharing](reference/apis/js-apis-net-sharing.md) - - [@ohos.net.socket](reference/apis/js-apis-socket.md) - - [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md) - - [@ohos.request](reference/apis/js-apis-request.md) + - [@ohos.net.connection (Network Connection Management)](reference/apis/js-apis-net-connection.md) + - [@ohos.net.ethernet (Ethernet Connection Management)](reference/apis/js-apis-net-ethernet.md) + - [@ohos.net.http (Data Request)](reference/apis/js-apis-http.md) + - [@ohos.net.sharing (Network Sharing)](reference/apis/js-apis-net-sharing.md) + - [@ohos.net.socket (Socket Connection)](reference/apis/js-apis-socket.md) + - [@ohos.net.webSocket (WebSocket Connection)](reference/apis/js-apis-webSocket.md) + - [@ohos.request (Upload and Download)](reference/apis/js-apis-request.md) - Connectivity - - [@ohos.bluetooth](reference/apis/js-apis-bluetooth.md) - - [@ohos.connectedTag](reference/apis/js-apis-connectedTag.md) - - [@ohos.nfc.cardEmulation](reference/apis/js-apis-cardEmulation.md) - - [@ohos.nfc.controller](reference/apis/js-apis-nfcController.md) - - [@ohos.nfc.tag](reference/apis/js-apis-nfcTag.md) - - [@ohos.rpc](reference/apis/js-apis-rpc.md) - - [@ohos.wifiManager (Recommended)](reference/apis/js-apis-wifiManager.md) - - [@ohos.wifiManagerExt (Recommended)](reference/apis/js-apis-wifiManagerExt.md) - - [@ohos.wifi (To Be Deprecated Soon)](reference/apis/js-apis-wifi.md) - - [@ohos.wifiext (To Be Deprecated Soon)](reference/apis/js-apis-wifiext.md) + - [@ohos.bluetooth (Bluetooth)](reference/apis/js-apis-bluetooth.md) + - [@ohos.connectedTag (Active Tags)](reference/apis/js-apis-connectedTag.md) + - [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](reference/apis/js-apis-cardEmulation.md) + - [@ohos.nfc.controller (Standard NFC)](reference/apis/js-apis-nfcController.md) + - [@ohos.nfc.tag (Standard NFC Tags)](reference/apis/js-apis-nfcTag.md) + - [@ohos.rpc (RPC)](reference/apis/js-apis-rpc.md) + - [@ohos.wifiManager (WLAN)](reference/apis/js-apis-wifiManager.md) + - [@ohos.wifiManagerExt (WLAN Extension)](reference/apis/js-apis-wifiManagerExt.md) + - [@ohos.wifi (To Be Deprecated)](reference/apis/js-apis-wifi.md) + - [@ohos.wifiext (To Be Deprecated)](reference/apis/js-apis-wifiext.md) - tag - - [nfctech](reference/apis/js-apis-nfctech.md) - - [tagSession](reference/apis/js-apis-tagSession.md) + - [nfctech (Standard NFC Technologies)](reference/apis/js-apis-nfctech.md) + - [tagSession (Standard NFC Tag Session)](reference/apis/js-apis-tagSession.md) - Basic Features - - [@ohos.accessibility](reference/apis/js-apis-accessibility.md) - - [@ohos.accessibility.config](reference/apis/js-apis-accessibility-config.md) - - [@ohos.accessibility.GesturePath](reference/apis/js-apis-accessibility-GesturePath.md) - - [@ohos.accessibility.GesturePoint](reference/apis/js-apis-accessibility-GesturePoint.md) - - [@ohos.application.AccessibilityExtensionAbility](reference/apis/js-apis-application-accessibilityExtensionAbility.md) - - [@ohos.faultLogger](reference/apis/js-apis-faultLogger.md) - - [@ohos.hichecker](reference/apis/js-apis-hichecker.md) - - [@ohos.hidebug](reference/apis/js-apis-hidebug.md) - - [@ohos.hilog](reference/apis/js-apis-hilog.md) - - [@ohos.hiSysEvent](reference/apis/js-apis-hisysevent.md) - - [@ohos.hiTraceChain](reference/apis/js-apis-hitracechain.md) - - [@ohos.hiTraceMeter](reference/apis/js-apis-hitracemeter.md) - - [@ohos.hiviewdfx.hiAppEvent](reference/apis/js-apis-hiviewdfx-hiappevent.md) - - [@ohos.inputmethod](reference/apis/js-apis-inputmethod.md) - - [@ohos.inputmethodengine](reference/apis/js-apis-inputmethodengine.md) - - [@ohos.inputmethodextensionability](reference/apis/js-apis-inputmethod-extension-ability.md) - - [@ohos.inputmethodextensioncontext](reference/apis/js-apis-inputmethod-extension-context.md) - - [@ohos.inputmethodsubtype](reference/apis/js-apis-inputmethod-subtype.md) - - [@ohos.pasteboard](reference/apis/js-apis-pasteboard.md) - - [@ohos.screenLock](reference/apis/js-apis-screen-lock.md) - - [@ohos.systemTime](reference/apis/js-apis-system-time.md) - - [@ohos.systemTimer](reference/apis/js-apis-system-timer.md) - - [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md) - - [@ohos.web.webview](reference/apis/js-apis-webview.md) - - [console](reference/apis/js-apis-logs.md) + - [@ohos.accessibility (Accessibility)](reference/apis/js-apis-accessibility.md) + - [@ohos.accessibility.config (System Accessibility Configuration)](reference/apis/js-apis-accessibility-config.md) + - [@ohos.accessibility.GesturePath (Gesture Path)](reference/apis/js-apis-accessibility-GesturePath.md) + - [@ohos.accessibility.GesturePoint (Gesture Point)](reference/apis/js-apis-accessibility-GesturePoint.md) + - [@ohos.application.AccessibilityExtensionAbility (AccessibilityExtensionAbility)](reference/apis/js-apis-application-accessibilityExtensionAbility.md) + - [@ohos.faultLogger (FaultLogger)](reference/apis/js-apis-faultLogger.md) + - [@ohos.hichecker (HiChecker)](reference/apis/js-apis-hichecker.md) + - [@ohos.hidebug (HiDebug)](reference/apis/js-apis-hidebug.md) + - [@ohos.hilog (HiLog)](reference/apis/js-apis-hilog.md) + - [@ohos.hiSysEvent (System Event Logging)](reference/apis/js-apis-hisysevent.md) + - [@ohos.hiTraceChain (Distributed Call Chain Tracing)](reference/apis/js-apis-hitracechain.md) + - [@ohos.hiTraceMeter (Performance Tracing)](reference/apis/js-apis-hitracemeter.md) + - [@ohos.hiviewdfx.hiAppEvent (Application Event Logging)](reference/apis/js-apis-hiviewdfx-hiappevent.md) + - [@ohos.inputMethod (Input Method Framework)](reference/apis/js-apis-inputmethod.md) + - [@ohos.inputMethodEngine (Input Method Service)](reference/apis/js-apis-inputmethodengine.md) + - [@ohos.InputMethodExtensionAbility (InputMethodExtensionAbility)](reference/apis/js-apis-inputmethod-extension-ability.md) + - [@ohos.InputMethodExtensionContext (InputMethodExtensionContext)](reference/apis/js-apis-inputmethod-extension-context.md) + - [@ohos.InputMethodSubtype (Input Method Subtype)](reference/apis/js-apis-inputmethod-subtype.md) + - [@ohos.pasteboard (Pasteboard)](reference/apis/js-apis-pasteboard.md) + - [@ohos.screenLock (Screenlock)](reference/apis/js-apis-screen-lock.md) + - [@ohos.systemDateTime (System Time and Time Zone)](reference/apis/js-apis-system-date-time.md) + - [@ohos.systemTimer (System Timer)](reference/apis/js-apis-system-timer.md) + - [@ohos.wallpaper (Wallpaper)](reference/apis/js-apis-wallpaper.md) + - [@ohos.web.webview (Webview)](reference/apis/js-apis-webview.md) + - [console (Log)](reference/apis/js-apis-logs.md) - [Timer](reference/apis/js-apis-timer.md) - application - [AccessibilityExtensionContext](reference/apis/js-apis-inner-application-accessibilityExtensionContext.md) - Device Management - - [@ohos.batteryInfo](reference/apis/js-apis-battery-info.md) - - [@ohos.batteryStatistics](reference/apis/js-apis-batteryStatistics.md) - - [@ohos.brightness](reference/apis/js-apis-brightness.md) - - [@ohos.deviceInfo](reference/apis/js-apis-device-info.md) - - [@ohos.distributedHardware.deviceManager](reference/apis/js-apis-device-manager.md) - - [@ohos.geoLocationManager](reference/apis/js-apis-geoLocationManager.md) - - [@ohos.multimodalInput.inputConsumer](reference/apis/js-apis-inputconsumer.md) - - [@ohos.multimodalInput.inputDevice](reference/apis/js-apis-inputdevice.md) - - [@ohos.multimodalInput.inputDeviceCooperate](reference/apis/js-apis-cooperate.md) - - [@ohos.multimodalInput.inputEvent](reference/apis/js-apis-inputevent.md) - - [@ohos.multimodalInput.inputEventClient](reference/apis/js-apis-inputeventclient.md) - - [@ohos.multimodalInput.inputMonitor](reference/apis/js-apis-inputmonitor.md) - - [@ohos.multimodalInput.keyCode](reference/apis/js-apis-keycode.md) - - [@ohos.multimodalInput.keyEvent](reference/apis/js-apis-keyevent.md) - - [@ohos.multimodalInput.mouseEvent](reference/apis/js-apis-mouseevent.md) - - [@ohos.multimodalInput.pointer](reference/apis/js-apis-pointer.md) - - [@ohos.multimodalInput.touchEvent](reference/apis/js-apis-touchevent.md) - - [@ohos.power](reference/apis/js-apis-power.md) - - [@ohos.runningLock](reference/apis/js-apis-runninglock.md) - - [@ohos.sensor](reference/apis/js-apis-sensor.md) - - [@ohos.settings](reference/apis/js-apis-settings.md) - - [@ohos.stationary](reference/apis/js-apis-stationary.md) - - [@ohos.systemParameterV9](reference/apis/js-apis-system-parameterV9.md) - - [@ohos.thermal](reference/apis/js-apis-thermal.md) - - [@ohos.update](reference/apis/js-apis-update.md) - - [@ohos.usb](reference/apis/js-apis-usb.md) - - [@ohos.vibrator](reference/apis/js-apis-vibrator.md) + - [@ohos.batteryInfo (Battery Information)](reference/apis/js-apis-battery-info.md) + - [@ohos.batteryStatistics (Battery Statistics)](reference/apis/js-apis-batteryStatistics.md) + - [@ohos.brightness (Screen Brightness)](reference/apis/js-apis-brightness.md) + - [@ohos.deviceInfo (Device Information)](reference/apis/js-apis-device-info.md) + - [@ohos.distributedHardware.deviceManager (Device Management)](reference/apis/js-apis-device-manager.md) + - [@ohos.geoLocationManager (Geolocation Manager)](reference/apis/js-apis-geoLocationManager.md) + - [@ohos.multimodalInput.inputConsumer (Input Consumer)](reference/apis/js-apis-inputconsumer.md) + - [@ohos.multimodalInput.inputDevice (Input Device)](reference/apis/js-apis-inputdevice.md) + - [@ohos.multimodalInput.inputDeviceCooperate (Screen Hopping)](reference/apis/js-apis-cooperate.md) + - [@ohos.multimodalInput.inputEvent (Input Event)](reference/apis/js-apis-inputevent.md) + - [@ohos.multimodalInput.inputEventClient (Key Event Injection)](reference/apis/js-apis-inputeventclient.md) + - [@ohos.multimodalInput.inputMonitor (Input Monitor)](reference/apis/js-apis-inputmonitor.md) + - [@ohos.multimodalInput.keyCode (Key Code)](reference/apis/js-apis-keycode.md) + - [@ohos.multimodalInput.keyEvent (Key Event)](reference/apis/js-apis-keyevent.md) + - [@ohos.multimodalInput.mouseEvent (Mouse Event)](reference/apis/js-apis-mouseevent.md) + - [@ohos.multimodalInput.pointer (Mouse Pointer)](reference/apis/js-apis-pointer.md) + - [@ohos.multimodalInput.touchEvent (Touch Event)](reference/apis/js-apis-touchevent.md) + - [@ohos.power (System Power Management)](reference/apis/js-apis-power.md) + - [@ohos.runningLock (Runninglock)](reference/apis/js-apis-runninglock.md) + - [@ohos.sensor (Sensor)](reference/apis/js-apis-sensor.md) + - [@ohos.settings (Data Item Settings)](reference/apis/js-apis-settings.md) + - [@ohos.stationary (Device Status Awareness Framework)](reference/apis/js-apis-stationary.md) + - [@ohos.systemCapability (SystemCapability)](reference/apis/js-apis-system-capability.md) + - [@ohos.systemParameterEnhance (System Parameter)](reference/apis/js-apis-system-parameterEnhance.md) + - [@ohos.thermal (Thermal Management)](reference/apis/js-apis-thermal.md) + - [@ohos.update (Update)](reference/apis/js-apis-update.md) + - [@ohos.usbManager (USB Management)](reference/apis/js-apis-usbManager.md) + - [@ohos.vibrator (Vibrator)](reference/apis/js-apis-vibrator.md) - Account Management - - [@ohos.account.appAccount](reference/apis/js-apis-appAccount.md) - - [@ohos.account.distributedAccount](reference/apis/js-apis-distributed-account.md) - - [@ohos.account.osAccount](reference/apis/js-apis-osAccount.md) + - [@ohos.account.appAccount (App Account Management)](reference/apis/js-apis-appAccount.md) + - [@ohos.account.distributedAccount (Distributed Account Management)](reference/apis/js-apis-distributed-account.md) + - [@ohos.account.osAccount (OS Account Management)](reference/apis/js-apis-osAccount.md) - Custom Management - - [@ohos.configPolicy](reference/apis/js-apis-configPolicy.md) - - [@ohos.enterprise.deviceInfo](reference/apis/js-apis-enterprise-deviceInfo.md) - - [@ohos.enterprise.EnterpriseAdminExtensionAbility](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) - - [@ohos.enterprise.adminManager](reference/apis/js-apis-enterprise-adminManager.md) - - [@ohos.enterprise.dateTimeManager](reference/apis/js-apis-enterprise-dateTimeManager.md) + - [@ohos.configPolicy (Configuration Policy)](reference/apis/js-apis-configPolicy.md) + - [@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.adminManager (Enterprise Device Management)](reference/apis/js-apis-enterprise-adminManager.md) + - [@ohos.enterprise.dateTimeManager (System Time Management)](reference/apis/js-apis-enterprise-dateTimeManager.md) - Language Base Class Library - - [@ohos.buffer](reference/apis/js-apis-buffer.md) - - [@ohos.convertxml](reference/apis/js-apis-convertxml.md) - - [@ohos.process](reference/apis/js-apis-process.md) - - [@ohos.uri](reference/apis/js-apis-uri.md) - - [@ohos.url](reference/apis/js-apis-url.md) - - [@ohos.util](reference/apis/js-apis-util.md) - - [@ohos.util.ArrayList](reference/apis/js-apis-arraylist.md) - - [@ohos.util.Deque](reference/apis/js-apis-deque.md) - - [@ohos.util.HashMap](reference/apis/js-apis-hashmap.md) - - [@ohos.util.HashSet](reference/apis/js-apis-hashset.md) - - [@ohos.util.LightWeightMap](reference/apis/js-apis-lightweightmap.md) - - [@ohos.util.LightWeightSet](reference/apis/js-apis-lightweightset.md) - - [@ohos.util.LinkedList](reference/apis/js-apis-linkedlist.md) - - [@ohos.util.List](reference/apis/js-apis-list.md) - - [@ohos.util.PlainArray](reference/apis/js-apis-plainarray.md) - - [@ohos.util.Queue](reference/apis/js-apis-queue.md) - - [@ohos.util.Stack](reference/apis/js-apis-stack.md) - - [@ohos.util.TreeMap](reference/apis/js-apis-treemap.md) - - [@ohos.util.TreeSet](reference/apis/js-apis-treeset.md) - - [@ohos.util.Vector](reference/apis/js-apis-vector.md) - - [@ohos.worker](reference/apis/js-apis-worker.md) - - [@ohos.xml](reference/apis/js-apis-xml.md) + - [@ohos.buffer (Buffer)](reference/apis/js-apis-buffer.md) + - [@ohos.convertxml (XML-to-JavaScript Conversion)](reference/apis/js-apis-convertxml.md) + - [@ohos.process (Obtaining Process Information)](reference/apis/js-apis-process.md) + - [@ohos.taskpool (Using the Task Pool)](reference/apis/js-apis-taskpool.md) + - [@ohos.uri (URI String Parsing)](reference/apis/js-apis-uri.md) + - [@ohos.url (URL String Parsing)](reference/apis/js-apis-url.md) + - [@ohos.util (util)](reference/apis/js-apis-util.md) + - [@ohos.util.ArrayList (Linear Container ArrayList)](reference/apis/js-apis-arraylist.md) + - [@ohos.util.Deque (Linear Container Deque)](reference/apis/js-apis-deque.md) + - [@ohos.util.HashMap (Nonlinear Container HashMap)](reference/apis/js-apis-hashmap.md) + - [@ohos.util.HashSet (Nonlinear Container HashSet)](reference/apis/js-apis-hashset.md) + - [@ohos.util.LightWeightMap (Nonlinear Container LightWeightMap)](reference/apis/js-apis-lightweightmap.md) + - [@ohos.util.LightWeightSet (Nonlinear Container LightWeightSet)](reference/apis/js-apis-lightweightset.md) + - [@ohos.util.LinkedList (Linear Container LinkedList)](reference/apis/js-apis-linkedlist.md) + - [@ohos.util.List (Linear Container List)](reference/apis/js-apis-list.md) + - [@ohos.util.PlainArray (Nonlinear Container PlainArray)](reference/apis/js-apis-plainarray.md) + - [@ohos.util.Queue (Linear Container Queue)](reference/apis/js-apis-queue.md) + - [@ohos.util.Stack (Linear Container Stack)](reference/apis/js-apis-stack.md) + - [@ohos.util.TreeMap (Nonlinear Container TreeMap)](reference/apis/js-apis-treemap.md) + - [@ohos.util.TreeSet (Nonlinear Container TreeSet)](reference/apis/js-apis-treeset.md) + - [@ohos.util.Vector (Linear Container Vector)](reference/apis/js-apis-vector.md) + - [@ohos.worker (Worker Startup)](reference/apis/js-apis-worker.md) + - [@ohos.xml (XML Parsing and Generation)](reference/apis/js-apis-xml.md) - Test - [@ohos.application.testRunner (TestRunner)](reference/apis/js-apis-application-testRunner.md) - [@ohos.uitest](reference/apis/js-apis-uitest.md) - APIs No Longer Maintained - - [@ohos.backgroundTaskManager](reference/apis/js-apis-backgroundTaskManager.md) - - [@ohos.bundle](reference/apis/js-apis-Bundle.md) - - [@ohos.bundle.innerBundleManager](reference/apis/js-apis-Bundle-InnerBundleManager.md) - - [@ohos.bundleState](reference/apis/js-apis-deviceUsageStatistics.md) - - [@ohos.bytrace](reference/apis/js-apis-bytrace.md) - - [@ohos.data.storage](reference/apis/js-apis-data-storage.md) - - [@ohos.data.distributedData](reference/apis/js-apis-distributed-data.md) - - [@ohos.distributedBundle](reference/apis/js-apis-Bundle-distributedBundle.md) - - [@ohos.document](reference/apis/js-apis-document.md) - - [@ohos.geolocation](reference/apis/js-apis-geolocation.md) - - [@ohos.hiAppEvent](reference/apis/js-apis-hiappevent.md) - - [@ohos.prompt](reference/apis/js-apis-prompt.md) - - [@ohos.reminderAgent](reference/apis/js-apis-reminderAgent.md) - - [@ohos.systemParameter](reference/apis/js-apis-system-parameter.md) - - [@ohos.usb](reference/apis/js-apis-usb-deprecated.md) - - [@system.app](reference/apis/js-apis-system-app.md) - - [@system.battery](reference/apis/js-apis-system-battery.md) - - [@system.bluetooth](reference/apis/js-apis-system-bluetooth.md) - - [@system.brightness](reference/apis/js-apis-system-brightness.md) - - [@system.configuration](reference/apis/js-apis-system-configuration.md) - - [@system.device](reference/apis/js-apis-system-device.md) - - [@system.fetch](reference/apis/js-apis-system-fetch.md) - - [@system.file](reference/apis/js-apis-system-file.md) - - [@system.geolocation](reference/apis/js-apis-system-location.md) - - [@system.mediaquery](reference/apis/js-apis-system-mediaquery.md) - - [@system.network](reference/apis/js-apis-system-network.md) - - [@system.notification](reference/apis/js-apis-system-notification.md) - - [@system.package](reference/apis/js-apis-system-package.md) - - [@system.prompt](reference/apis/js-apis-system-prompt.md) - - [@system.request](reference/apis/js-apis-system-request.md) - - [@system.router](reference/apis/js-apis-system-router.md) - - [@system.sensor](reference/apis/js-apis-system-sensor.md) - - [@system.storage](reference/apis/js-apis-system-storage.md) - - [@system.vibrator](reference/apis/js-apis-system-vibrate.md) + - [@ohos.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-backgroundTaskManager.md) + - [@ohos.bundle (Bundle)](reference/apis/js-apis-Bundle.md) + - [@ohos.bundle.innerBundleManager (innerBundleManager)](reference/apis/js-apis-Bundle-InnerBundleManager.md) + - [@ohos.bundleState (Device Usage Statistics)](reference/apis/js-apis-deviceUsageStatistics.md) + - [@ohos.bytrace (Performance Tracing)](reference/apis/js-apis-bytrace.md) + - [@ohos.data.distributedData (Distributed Data Management)](reference/apis/js-apis-distributed-data.md) + - [@ohos.data.storage (Lightweight Data Storage)](reference/apis/js-apis-data-storage.md) + - [@ohos.data.rdb (RDB)](reference/apis/js-apis-data-rdb.md) + - [@ohos.distributedBundle (Distributed Bundle Management)](reference/apis/js-apis-Bundle-distributedBundle.md) + - [@ohos.document (File Operation)](reference/apis/js-apis-document.md) + - [@ohos.fileio (File Management)](reference/apis/js-apis-fileio.md) + - [@ohos.geolocation (Geolocation)](reference/apis/js-apis-geolocation.md) + - [@ohos.hiAppEvent (Application Event Logging)](reference/apis/js-apis-hiappevent.md) + - [@ohos.prompt (Prompt)](reference/apis/js-apis-prompt.md) + - [@ohos.reminderAgent (Reminder Agent)](reference/apis/js-apis-reminderAgent.md) + - [@ohos.statfs (statfs)](reference/apis/js-apis-statfs.md) + - [@ohos.systemParameter (System Parameter)](reference/apis/js-apis-system-parameter.md) + - [@ohos.systemTime (System Time and Time Zone)](reference/apis/js-apis-system-time.md) + - [@ohos.usb (USB Management)](reference/apis/js-apis-usb-deprecated.md) + - [@ohos.usbV9 (USB Management)](reference/apis/js-apis-usb.md) + - [@system.app (Application Context)](reference/apis/js-apis-system-app.md) + - [@system.battery (Battery Information)](reference/apis/js-apis-system-battery.md) + - [@system.bluetooth (Bluetooth)](reference/apis/js-apis-system-bluetooth.md) + - [@system.brightness (Screen Brightness)](reference/apis/js-apis-system-brightness.md) + - [@system.configuration (Application Configuration)](reference/apis/js-apis-system-configuration.md) + - [@system.device (Device Information)](reference/apis/js-apis-system-device.md) + - [@system.fetch (Data Request)](reference/apis/js-apis-system-fetch.md) + - [@system.file (File Storage)](reference/apis/js-apis-system-file.md) + - [@system.geolocation (Geographic Location)](reference/apis/js-apis-system-location.md) + - [@system.mediaquery (Media Query)](reference/apis/js-apis-system-mediaquery.md) + - [@system.network (Network State)](reference/apis/js-apis-system-network.md) + - [@system.notification (Notification)](reference/apis/js-apis-system-notification.md) + - [@system.package (Bundle Management)](reference/apis/js-apis-system-package.md) + - [@system.prompt (Prompt)](reference/apis/js-apis-system-prompt.md) + - [@system.request (Upload and Download)](reference/apis/js-apis-system-request.md) + - [@system.router (Page Routing)](reference/apis/js-apis-system-router.md) + - [@system.sensor (Sensor)](reference/apis/js-apis-system-sensor.md) + - [@system.storage (Data Storage)](reference/apis/js-apis-system-storage.md) + - [@system.vibrator (Vibrator)](reference/apis/js-apis-system-vibrate.md) - bundle - [abilityInfo](reference/apis/js-apis-bundle-AbilityInfo.md) - [applicationInfo](reference/apis/js-apis-bundle-ApplicationInfo.md) @@ -1147,6 +1151,7 @@ - [zlib Error Codes](reference/errorcodes/errorcode-zlib.md) - Common Events and Notification - [Event Error Codes](reference/errorcodes/errorcode-CommonEventService.md) + - [Notification Error Codes](reference/errorcodes/errorcode-notification.md) - [DistributedNotificationService Error Codes](reference/errorcodes/errorcode-DistributedNotificationService.md) - UI Page - [Animator Error Codes](reference/errorcodes/errorcode-animator.md) @@ -1165,14 +1170,18 @@ - [Resource Manager Error Codes](reference/errorcodes/errorcode-resource-manager.md) - Resource Scheduling - [backgroundTaskManager Error Codes](reference/errorcodes/errorcode-backgroundTaskMgr.md) - - [DeviceUsageStatistics Error Codes](reference/errorcodes/errorcode-DeviceUsageStatistics.md) - [reminderAgentManager Error Codes](reference/errorcodes/errorcode-reminderAgentManager.md) - [workScheduler Error Codes](reference/errorcodes/errorcode-workScheduler.md) - Security - [Ability Access Control Error Codes](reference/errorcodes/errorcode-access-token.md) - [HUKS Error Codes](reference/errorcodes/errorcode-huks.md) + - [Crypto Framework Error Codes](reference/errorcodes/errorcode-crypto-framework.md) + - [Certificate Error Codes](reference/errorcodes/errorcode-cert.md) + - [User Authentication Error Codes](reference/errorcodes/errorcode-useriam.md) - Data Management - [RDB Error Codes](reference/errorcodes/errorcode-data-rdb.md) + - [DataShare Error Codes](reference/errorcodes/errorcode-datashare.md) + - [Distributed Data Object Error Codes](reference/errorcodes/errorcode-distributed-dataObject.md) - [Distributed KV Store Error Codes](reference/errorcodes/errorcode-distributedKVStore.md) - [Preferences Error Codes](reference/errorcodes/errorcode-preferences.md) - File Management @@ -1190,11 +1199,10 @@ - [HiDebug Error Codes](reference/errorcodes/errorcode-hiviewdfx-hidebug.md) - [Input Method Framework Error Codes](reference/errorcodes/errorcode-inputmethod-framework.md) - [Pasteboard Error Codes](reference/errorcodes/errorcode-pasteboard.md) - - [Screen Lock Management Error Codes](reference/errorcodes/errorcode-screenlock.md) + - [Time and Time Zone Service Error Codes](reference/errorcodes/errorcode-time.md) - [Webview Error Codes](reference/errorcodes/errorcode-webview.md) - Account Management - [Account Error Codes](reference/errorcodes/errorcode-account.md) - - [App Account Error Codes](reference/errorcodes/errorcode-app-account.md) - Device Management - [Power Consumption Statistics Error Codes](reference/errorcodes/errorcode-batteryStatistics.md) - [Brightness Error Codes](reference/errorcodes/errorcode-brightness.md) @@ -1209,8 +1217,11 @@ - [System Parameter Error Codes](reference/errorcodes/errorcode-system-parameterV9.md) - [USB Error Codes](reference/errorcodes/errorcode-usb.md) - [Update Error Codes](reference/errorcodes/errorcode-update.md) + - [DeviceUsageStatistics Error Codes](reference/errorcodes/errorcode-DeviceUsageStatistics.md) - Customization Management - [Enterprise Device Management Error Codes](reference/errorcodes/errorcode-enterpriseDeviceManager.md) + - Language Base Class Library + - [Utils Error Codes](reference/errorcodes/errorcode-utils.md) - Test - [UiTest Error Codes](reference/errorcodes/errorcode-uitest.md) - Native APIs diff --git a/en/application-dev/windowmanager/application-window-fa.md b/en/application-dev/windowmanager/application-window-fa.md index ee7848d49aaccd039c59a1bac2553f0b485ecc1c..3ffee6d6467c870581dd6ede6f55d5d111758a84 100644 --- a/en/application-dev/windowmanager/application-window-fa.md +++ b/en/application-dev/windowmanager/application-window-fa.md @@ -21,7 +21,7 @@ The table below lists the common APIs used for application window development. F | Instance| API| Description| | -------- | -------- | -------- | | Window static method| createWindow(config: Configuration, callback: AsyncCallback\): void | Creates a subwindow.
**config** specifies the parameters used for creating the window.| -| Window static method| findWindow(id: string, callback: AsyncCallback<Window>): void | Finds a window based on the ID.| +| Window static method| findWindow(name: string): Window | Finds a window based on the name.| | Window | SetUIContent(path: string, callback: AsyncCallback<void>): void | Loads the page content to this window.| | Window | moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void | Moves this window.| | Window | setWindowBackgroundColor(color: string, callback: AsyncCallback<void>): void | Sets the background color for this window.| @@ -62,14 +62,11 @@ You can create a subwindow, such as a dialog box, and set its properties. windowClass = data; }); // Method 2: Find a subwindow. - window.findWindow("subWindow", (err, data) => { - if (err.code) { - console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data)); - windowClass = data; - }); + try { + windowClass = window.findWindow('subWindow'); + } catch (exception) { + console.error('Failed to find the Window. Cause: ' + JSON.stringify(exception)); + } ``` 2. Set the properties of the subwindow. @@ -154,7 +151,7 @@ To create a better video watching and gaming experience, you can use the immersi let mainWindowClass = null; // Obtain the main window. - window.getLastWindow((err, data) => { + window.getLastWindow(this.context,(err, data) => { if (err.code) { console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err)); return; @@ -164,7 +161,7 @@ To create a better video watching and gaming experience, you can use the immersi }); ``` -2. Implement the immersive effect. You can use any of the following methods: +2. Implement the immersive effect. You can use either of the following methods: - Method 1: Call **setWindowSystemBarEnable** to hide the navigation bar and status bar. - Method 2: Call **setWindowLayoutFullScreen** to enable the full-screen mode for the main window layout. Call **setSystemProperties** to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window. diff --git a/en/application-dev/windowmanager/application-window-stage.md b/en/application-dev/windowmanager/application-window-stage.md index c9d15a6227008938ed361929f6811596d55ca2ad..6e46d564af66f6b7831d6b3e10de0962ae319dbe 100644 --- a/en/application-dev/windowmanager/application-window-stage.md +++ b/en/application-dev/windowmanager/application-window-stage.md @@ -49,7 +49,7 @@ The table below lists the common APIs used for application window development. F ## Setting the Main Window of an Application -In the stage model, the main window of an application is created and maintained by an **Ability** instance. In the **onWindowStageCreate** callback of the **Ability** instance, use **WindowStage** to obtain the main window of the application and set its properties. +In the stage model, the main window of an application is created and maintained by a **UIAbility** instance. In the **onWindowStageCreate** callback of the **UIAbility** instance, use **WindowStage** to obtain the main window of the application and set its properties. You can also set the properties (for example, **maxWindowWidth**) in the [module.json5 file](../quick-start/module-configuration-file.md#abilities). ### How to Develop @@ -66,41 +66,41 @@ In the stage model, the main window of an application is created and maintained Call **loadContent** to load the page content to the main window. -```ts -import UIAbility from '@ohos.app.ability.UIAbility'; - -export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage) { - // 1. Obtain the main window of the application. - let windowClass = null; - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); - // 2. Set the touchable property of the main window. - let isTouchable = true; - windowClass.setWindowTouchable(isTouchable, (err) => { - if (err.code) { - console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window to be touchable.'); - }) - }) - // 3. Load the page content to the main window. - windowStage.loadContent("pages/page2", (err) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content.'); - }); - } -}; -``` + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { + // 1. Obtain the main window of the application. + let windowClass = null; + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); + // 2. Set the touchable property of the main window. + let isTouchable = true; + windowClass.setWindowTouchable(isTouchable, (err) => { + if (err.code) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable.'); + }) + }) + // 3. Load the page content to the main window. + windowStage.loadContent("pages/page2", (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); + } + }; + ``` ## Setting a Subwindow of an Application @@ -211,7 +211,7 @@ To create a better video watching and gaming experience, you can use the immersi Call **getMainWindow** to obtain the main window of the application. -2. Implement the immersive effect. You can use any of the following methods: +2. Implement the immersive effect. You can use either of the following methods: - Method 1: Call **setWindowSystemBarEnable** to hide the navigation bar and status bar. - Method 2: Call **setWindowLayoutFullScreen** to enable the full-screen mode for the main window layout. Call **setWindowSystemBarProperties** to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window. @@ -282,7 +282,7 @@ To create a better video watching and gaming experience, you can use the immersi ## Setting a Floating Window -A floating window is created based on an existing task. It is always displayed in the foreground, even if the task used for creating the floating window is switched to the background. You can create a floating window and set its properties. +A floating window is created based on an existing task. It is always displayed in the foreground, even if the task used for creating the floating window is switched to the background. Generally, the floating window is above all application windows. You can create a floating window and set its properties. ### How to Develop diff --git a/en/contribute/template/js-template.md b/en/contribute/template/js-template.md index 70002f0f5080c274867ccea5a6741a7d4d021aa5..037e3ffce7bf743bc78828cec405643bad507a7b 100644 --- a/en/contribute/template/js-template.md +++ b/en/contribute/template/js-template.md @@ -97,7 +97,7 @@ import call from '@ohos.telephony.call'; **System capability**: SystemCapability.*A.B* (This part is mandatory.) -| Name | Type | Readable| Writable| Description | +| Name | Type | Read Only| Mandatory| Description | | ---------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------ | | pluggedType | [BatteryPluggedType]\(#batterypluggedtype) | Yes | No | Charger type of the current device. | | isBatteryPresent | boolean | Yes | No | Whether the battery is supported or present.| @@ -112,10 +112,10 @@ import call from '@ohos.telephony.call'; **System capability**: SystemCapability.*A.B* (This part is mandatory.) -| Name | Type | | Description | -| ---------------- | ----------------------------------------- | ------------------------------------------ | ------------------------------------------ | -| uid | number | 1 | User identifier (UID) of a process. | -| pid | number | 2 | Process ID (PID) of a process. | +| Name | Type | Value | Description | +| ---------------- | -----------------------------------| -------- | ------------------------------------------ | +| uid | number | 1 | User identifier (UID) of a process. | +| pid | number | 2 | Process ID (PID) of a process. | ## Methods @@ -154,15 +154,15 @@ Describe the method. For details, see the fourth and fifth points in "Writing In | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| parameterOne | number \| string \| [CustomType](#customtype) | Yes | Describe the parameter. Provide the value range and recommended value. If there is a fixed format, provide a format example, especially for the URI.
Provide a link for each custom parameter type.| -| callback | Callback\> | No | Describe the parameter. For an optional parameter, describe the consequences if it is not specified.
Example: If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.
For details about how to write callback methods, see item 14 in "General Writing Instructions."| +| parameterOne | number \| string \| [CustomType](#classinterface) | Yes | Describe the parameter. Provide the value range and recommended value. If there is a fixed format, provide a format example, especially for the URI.
Provide a link for each custom parameter type.| +| callback | Callback\> | No | Describe the parameter. For an optional parameter, describe the consequences if it is not specified.
Example: If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.
For details about how to write callback methods, see item 14 in "General Writing Instructions."| **Return value** (This part is optional. Delete it if there is no return value.) | Type | Description | | ------------------------------------------ | ----------------------------------------------- | | string | Describe the return value, for example, what can be done after the return value is obtained.| -| Promise\> | Describe the return value. For details about how to write promise methods, see item 14 in "General Writing Instructions."| +| Promise\> | Describe the return value. For details about how to write promise methods, see item 14 in "General Writing Instructions."| **Error codes** (This part is optional. Delete it if no error code is thrown.) @@ -220,7 +220,7 @@ Describe the method. For details, see the fourth and fifth points in "Writing In | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Describe the event and when or how it will be triggered. If a method involves multiple events, describe them separately.
**Example 1 (single event):**
Type of the event. The **'play'** event is triggered when the **play()** API is called and audio playback starts.
Example 2 (multiple events):
Type of the event. The following events are supported:
- **'play'**: triggered when the **play()** API is called and audio playback starts.
- **'dataLoad'**: triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- **'finish'**: triggered when the audio playback is finished. | -| callback | Callback\<[CustomType](#customtype)> | No | Describe the parameter. The instructions are the same as those provided under [Methods](#methods). | +| callback | Callback\<[CustomType](#classinterface)> | No | Describe the parameter. The instructions are the same as those provided under [Methods](#methods). | **Return value** (This part is optional. Delete it if there is no return value.) @@ -254,7 +254,7 @@ Describe the method. For details, see the fourth and fifth points in "Writing In > 2. Use the actual class or interface name as the level-2 heading. > > 3. If the class or interface contains both attributes and methods, write the attributes above the methods. Write their actual names in separate level-3 headings. -> If the class or interface contains only attributes, you do not need to create a level-3 heading. Instead, use a table to display the attributes. For details, see [CustomType](#customtype). +> If the API contains only attributes, you do not need to create a level-3 heading. Instead, use a table to display the attributes. Describe the class or interface. If there are usage restrictions, describe them as well, for example, whether there is a prerequisite and whether an instance needs to be created by using any method. @@ -262,7 +262,7 @@ Describe the class or interface. If there are usage restrictions, describe them > *Writing Instructions* > -> Except that a level-3 heading is used for attributes in classes/interfaces, other instructions are the same as those provided under [Attributes](#attributes). +> Except that level-3 headings are used, other requirements are the same as those in [Attribute](#Attribute). ### Methods in Classes/Interfaces @@ -289,43 +289,29 @@ Provide a brief description of the enum type. Example: Enumerates the charger ty | ---- | ---- | -------------------------- | | NONE | 1 | Unknown type.| -## CustomType - -> *Writing Instructions* -> -> This section is optional. Delete it if there is no custom type. It corresponds to **Interface** in the .d.ts file. - -The following is an example of the custom type of a key-value pair. - -**System capability**: SystemCapability.*A.B* (This part is mandatory.) - -| Name | Type | Mandatory | Description | -| ------------ | ------------------- | ---- | ------------------------------------------------------------ | -| parameterUrl | string | Yes | Media output URI. Supported:
1. Relative path whose protocol type is **internal**. Example:
Temporary directory: internal://cache/test.mp4
2. Absolute path. Example:
file:///data/data/ohos.xxx.xxx/files/test.mp4| -| parameterOne | [CustomEnum](#enums)| No | Describe the attributes. The requirements are similar to those for the parameter description. | - -## Type +## Types > *Writing Instructions* > > 1. This section is optional. Delete it if there is no type. It corresponds to **type** in the .d.ts file. > -> 2. By default, use **Type** as the heading of the first column. If all the values are specific strings, change the heading of the first column to **Value**. +> 2. If the value range is of a specific value, such as a fixed string or enumerated value, describe the data type and specified value. If the value range is of a specified type, describe whether any value of the type or a value range is used. > -> 3. If a type is of a custom type, create a link to the corresponding interface or enum. +> 3. If the type is of a custom type, create a link to the corresponding interface or enum. Provide a brief description of the union type. Example: Enumerates the value types. **System capability**: SystemCapability.*A.B* (This part is mandatory.) -| Type | Description | +| Value Range | Description | | -----------| ---------------------------- | -| number | The value is a number. | -| string | The value is a string. | +| number | The value can be any number. | +| string | The value can be any string. | ## Change History | Change Description | Date | | ----------------------------------------------------------------------- | ------------ | +| 1. Changed the template for **Attributes** from **Read**, **Write**, and **Mandatory** to **Read Only** and **Mandatory**.
2. Changed the template for **Types** by using **Value Range** and **Description**, and provided the related description.
3. Deleted the custom type, and incorporated the related description under **Classes/Interfaces**.| 2023/02/01 | | 1. Provided the general writing instructions in a table.
2. Added the description about how to reference an image in "Upload path".
3. Added the "Document structure" item to describe the sequence of nodes in the API reference document.
4. Added the description for multiple permissions in "Permission description".
5. Added the description of @FAModelOnly and @StageModelOnly in the API reference document.
6. Added the description of asynchronous methods (callback and promise).
7. Added the standards and specifications for the sample code programming language.
8. Added the standard format for links used in the API reference document.
9. Added examples for "Module description".
10. Added the description of on and off subscription methods.
11. Updated the description of @syscap.
12. Updated the description of @systemapi. Now only the sentence "This is a system API." is used.
13. Deleted the MR version description. | 2022/6/24 | | Added the error code description. | 2022/10/11 | | 1. Added the template for **constant** and **type**.
2. Modified the table of the custom type **interface** by deleting the **Readable** and **Writable** columns and adding the **Mandatory** column, for consistency with the content of the .d.ts file.
3. Added the deprecated description for APIs with both the initial version and deprecated version. |2022/11/22 | diff --git a/en/device-dev/driver/driver-hdf-development.md b/en/device-dev/driver/driver-hdf-development.md index e251299eb09c9b7f04fa1592af095775ed972320..824829d3cd3e3b043bc56f4a502806693fb44135 100644 --- a/en/device-dev/driver/driver-hdf-development.md +++ b/en/device-dev/driver/driver-hdf-development.md @@ -211,7 +211,7 @@ The HDF-based driver development involves driver implementation, write of the dr > > - If you need to set **uid** and **gid** to **system** or **root** due to service requirements, contact security experts for review. > - > - The process UIDs are configured in **base/startup/init_lite/services/etc/passwd**, and the process GIDs are configured in **base/startup/init_lite/services/etc/group**. For details, see [Adding a System Service User Group]( https://gitee.com/openharmony/startup_init_lite/wikis). + > - The process UIDs are configured in **base/startup/init/services/etc/passwd**, and the process GIDs are configured in **base/startup/init/services/etc/group**. For details, see [Adding a System Service User Group]( https://gitee.com/openharmony/startup_init_lite/wikis). > > - The **caps** value is in the caps = ["xxx"] format. To configure **CAP_DAC_OVERRIDE**, set this parameter to **caps = ["DAC_OVERRIDE"]**. Do not set it to **caps = ["CAP_DAC_OVERRIDE"]**. > diff --git a/en/device-dev/faqs/faqs-startup.md b/en/device-dev/faqs/faqs-startup.md index a9a319ce0f683f784a2951e491c50a089e399ce4..f5f132c11e233dba0f5b8f7a6e63efa7d934f34c 100644 --- a/en/device-dev/faqs/faqs-startup.md +++ b/en/device-dev/faqs/faqs-startup.md @@ -161,7 +161,7 @@ OpenHarmony-3.0-LTS **Solution** 1. For case 1, leave **caps** unspecified. -2. For case 2, correctly configure **caps** by referring to the definition of the **capStrCapNum** data structure in **base/startup/init_lite/services/init/init_capability.c**. +2. For case 2, correctly configure **caps** by referring to the definition of the **capStrCapNum** data structure in **base/startup/init/services/init/init_capability.c**. ### Sandbox Not Enabled @@ -175,7 +175,7 @@ None. **Solution** -Set **const.sandbox** to **enable** in **base/startup/init_lite/services/etc/param/ohos.para**. For details, see [Sandbox Management](../subsystems/subsys-boot-init-sandbox.md). +Set **const.sandbox** to **enable** in **base/startup/init/services/etc/param/ohos.para**. For details, see [Sandbox Management](../subsystems/subsys-boot-init-sandbox.md). ### How to Check the Sandbox Mounting Status diff --git a/en/device-dev/porting/porting-smallchip-kernel-linux.md b/en/device-dev/porting/porting-smallchip-kernel-linux.md index b5b3882de258ef9f9cb02957cc174a02899e24ed..5b9e57546e2b61296728c2ffb33806cf86181aca 100644 --- a/en/device-dev/porting/porting-smallchip-kernel-linux.md +++ b/en/device-dev/porting/porting-smallchip-kernel-linux.md @@ -69,7 +69,7 @@ Based on the preceding process, the recommended verification procedure is as fol Create a root file system image **rootfs.img** by following instructions in [Building Procedures](../subsystems/subsys-build-all.md). As shown in the preceding figure, the startup process is closely related to the product configuration. You need to complete the following configuration when creating **rootfs.img**: - Component configuration - In the product component configuration file ***vendor*/{*company*}/{*product*}/config.json**, configure the **init_lite** component of the startup subsystem and the **linux_4_1_9** component of the kernel subsystem. + In the product component configuration file ***vendor*/{*company*}/{*product*}/config.json**, configure the **init** component of the startup subsystem and the **linux_4_1_9** component of the kernel subsystem. - System service configuration Modify the system service configuration file ***vendor*/{*company*}/{*product*}/init_configs/init_xxx.cfg** to start the shell service. - File system configuration diff --git a/en/device-dev/porting/standard-system-porting-guide.md b/en/device-dev/porting/standard-system-porting-guide.md index c9310380bb8034e02114258edc5416b4ef1ac0e4..6deec486cb12d358d87800db6615f061f7ba24eb 100644 --- a/en/device-dev/porting/standard-system-porting-guide.md +++ b/en/device-dev/porting/standard-system-porting-guide.md @@ -158,7 +158,7 @@ Now start build, and check whether the kernel image is generated as expected. When porting a new chip platform, you need to add the **/vendor/etc/init/init.{hardware}.cfg** file that contains the platform-level initialization configuration. This file is used to implement platform-level initialization, for example, installing the ko driver and configuring information on the related **/proc** nodes. - The code of the init process is stored in the **//base/startup/init_lite** directory. This process is the first process in the system and does not depend on other processes. + The code of the init process is stored in the **//base/startup/init** directory. This process is the first process in the system and does not depend on other processes. For details about how to develop the initialization configuration file, see [Startup](../subsystems/subsys-boot-overview.md). diff --git a/en/device-dev/subsystems/subsys-boot-init-cfg.md b/en/device-dev/subsystems/subsys-boot-init-cfg.md index 2f3133495f58def0daa7301b58e03b2743fac8c9..13f7fb5e13ee3ea1d9b778c7b48e8ea431807ec8 100644 --- a/en/device-dev/subsystems/subsys-boot-init-cfg.md +++ b/en/device-dev/subsystems/subsys-boot-init-cfg.md @@ -39,7 +39,7 @@ If you need to add a configuration file, define its content as you want and copy For the standard system: ``` ohos_prebuilt_etc("misc.cfg") { - source = "//base/startup/init_lite/services/etc/misc.cfg" + source = "//base/startup/init/services/etc/misc.cfg" relative_install_dir = "init" part_name = "init" } diff --git a/en/device-dev/subsystems/subsys-boot-init-jobs.md b/en/device-dev/subsystems/subsys-boot-init-jobs.md index 31e52aa9bb74cb28168744a9427a88df47279460..0a9bc5be6ee4270204bc0899dc825fce38a1617e 100644 --- a/en/device-dev/subsystems/subsys-boot-init-jobs.md +++ b/en/device-dev/subsystems/subsys-boot-init-jobs.md @@ -98,7 +98,7 @@ A job is a command set, where you can manage the commands to be executed. A maxi mount fileSystemType src dst flags data
Example:
mount vfat /dev/mmcblk0 /sdc rw,umask=000
mount jffs2 /dev/mtdblock3 /storage nosuid - Mounts devices. Every two parameters must be separated by only one space.
For details about flags, see the mountFlagMap[] array of the mountFlagMap function in base/startup/init_lite/services/init/init_common_cmds.c. The data field is optional. + Mounts devices. Every two parameters must be separated by only one space.
For details about flags, see the mountFlagMap[] array of the mountFlagMap function in base/startup/init/services/init/init_common_cmds.c. The data field is optional. Small and standard systems @@ -294,7 +294,7 @@ A job is a command set, where you can manage the commands to be executed. A maxi setrlimit resource curValue maxValue
Example:
setrlimit RLIMIT_CPU 10 100 - Sets resource usage restrictions.
For details, see the resource[] array of the DoSetrlimit function in base/startup/init_lite/services/init/init_common_cmds.c. + Sets resource usage restrictions.
For details, see the resource[] array of the DoSetrlimit function in base/startup/init/services/init/init_common_cmds.c. Small and standard systems diff --git a/en/device-dev/subsystems/subsys-boot-init-sandbox.md b/en/device-dev/subsystems/subsys-boot-init-sandbox.md index 6580b9a99475109289ccaea62593c098a2b47022..7aadd30b8cfa8338c29869759d68ae1f8eb93321 100644 --- a/en/device-dev/subsystems/subsys-boot-init-sandbox.md +++ b/en/device-dev/subsystems/subsys-boot-init-sandbox.md @@ -65,7 +65,7 @@ typedef struct { 2. Modify the JSON file configuration of the sandbox. - Go to the **/system/etc/sandbox/** directory, and run **cat system-sandbox.json** and **cat chipset-sandbox.json**. If you are using a 64-bit system, run **cat system-sandbox64.json** and **cat chipset-sandbox64.json** instead. - - Modify the sandbox configuration files in the **base/startup/init_lite/interfaces/innerkits/sandbox** directory. After that, restart the system. + - Modify the sandbox configuration files in the **base/startup/init/interfaces/innerkits/sandbox** directory. After that, restart the system. ### Development Example Sandbox JSON File Configuration diff --git a/en/device-dev/subsystems/subsys-boot-init-sysparam.md b/en/device-dev/subsystems/subsys-boot-init-sysparam.md index 6f575f67aa430a22913be3b7164682626e79f050..f3032d36d7bc5893bfaadff1b3fe6b9863021bbf 100644 --- a/en/device-dev/subsystems/subsys-boot-init-sysparam.md +++ b/en/device-dev/subsystems/subsys-boot-init-sysparam.md @@ -247,16 +247,16 @@ You can set specific system parameters as needed to meet your service demand. ​ On a standard system, use the ohos_prebuilt_para template to install the configuration file to the /etc/param/ directory. The following is an example of the GN script: ```go - import("//base/startup/init_lite/services/etc/param/param_fixer.gni") + import("//base/startup/init/services/etc/param/param_fixer.gni") ohos_prebuilt_para("ohos.para") { - source = "//base/startup/init_lite/services/etc/ohos.para" + source = "//base/startup/init/services/etc/ohos.para" part_name = "init" module_install_dir = "etc/param" } ohos_prebuilt_para("ohos.para.dac") { - source = "//base/startup/init_lite/services/etc/ohos.para.dac" + source = "//base/startup/init/services/etc/ohos.para.dac" part_name = "init" module_install_dir = "etc/param" } @@ -265,24 +265,24 @@ You can set specific system parameters as needed to meet your service demand. On a small system, run the copy command to copy the corresponding system parameter definition file to the system/etc/param directory. ```go copy("ohos.para") { - sources = [ "//base/startup/init_lite/services/etc/param/ohos.para" ] + sources = [ "//base/startup/init/services/etc/param/ohos.para" ] outputs = [ "$root_out_dir/system/etc/param/ohos.para" ] } copy("ohos.para.dac") { - sources = [ "//base/startup/init_lite/services/etc/param/ohos.para.dac" ] + sources = [ "//base/startup/init/services/etc/param/ohos.para.dac" ] outputs = [ "$root_out_dir/system/etc/param/ohos.para.dac" ] } ``` On a mini system, convert all defined default system parameters into header files through **action** and compile them into the system. ```go action("lite_const_param_to") { - script = "//base/startup/init_lite/scripts/param_cfg_to_code.py" + script = "//base/startup/init/scripts/param_cfg_to_code.py" args = [ "--source", rebase_path( - "//base/startup/init_lite/services/etc_lite/param/ohos_const/ohospara"), + "//base/startup/init/services/etc_lite/param/ohos_const/ohospara"), "--dest_dir", - rebase_path("$root_out_dir/gen/init_lite/"), + rebase_path("$root_out_dir/gen/init/"), "--priority", "0", ] diff --git a/en/device-dev/subsystems/subsys-boot-overview.md b/en/device-dev/subsystems/subsys-boot-overview.md index 1d2f8a1ae7354f4535479315f956f9b3c097a0df..7cd6f438d0e5b29d2a541263459bf1cb281d5104 100644 --- a/en/device-dev/subsystems/subsys-boot-overview.md +++ b/en/device-dev/subsystems/subsys-boot-overview.md @@ -53,7 +53,7 @@ The Startup subsystem consists of the following modules: | -------- | -------- | | base/startup/appspawn_lite | Small-system devices (reference memory ≥ 1 MiB), for example, Hi3516D V300 and Hi3518E V300| | base/startup/bootstrap_lite | Mini-system devices (reference memory ≥ 128 KiB), for example, Hi3861 V100| -| base/startup/init_lite | Small-system devices (reference memory ≥ 1 MiB), for example, Hi3516D V300 and Hi3518E V300| +| base/startup/init | Small-system devices (reference memory ≥ 1 MiB), for example, Hi3516D V300 and Hi3518E V300| | base/startup/syspara_lite | - Mini-system devices (reference memory ≥ 128 KiB), for example, Hi3861 V100
- Small-system devices (reference memory ≥ 1 MiB), for example, Hi3516D V300 and Hi3518E V300| - init module diff --git a/en/device-dev/subsystems/subsys-build-module.md b/en/device-dev/subsystems/subsys-build-module.md index a442e71902232f76d75196b97b06d4b898c865e3..24766cba3df0dd1e179111e874ddb33819ebfa3a 100644 --- a/en/device-dev/subsystems/subsys-build-module.md +++ b/en/device-dev/subsystems/subsys-build-module.md @@ -1,7 +1,7 @@ # Module ## Configuration Rules -The Compilation and Building subsystem implements compilation and packaging by module, component, and product. A module is an target to build. It can be a dynamic library, static library, configuration file, or prebuilt module. A module must belong to a component and can belong to only one component. OpenHarmony uses customized GN templates to configure modules. For details about the GN basics, see https://gn.googlesource.com/gn/+/main/docs/reference.md. +The Compilation and Building subsystem implements compilation and packaging by module, component, and product. A module is a target to build. It can be a dynamic library, static library, configuration file, or prebuilt module. A module must belong to a component and can belong to only one component. OpenHarmony provides customized GN templates to configure modules. For details about the GN basics, see [GN Reference](https://gn.googlesource.com/gn/+/main/docs/reference.md). The common templates for module configuration are as follows: @@ -25,15 +25,15 @@ ohos_resources # Other templates # Configuration file -ohos_prebuild_etc +ohos_prebuilt_etc # SA profile ohos_sa_profile ``` -You are recommended to use the OpenHarmony customized templates. +You are advised to use the OpenHarmony customized templates. -### C/C++ Template Example +### C/C++ Template Examples The .gni file corresponding to the templates starting with **ohos** is located in **openharmony/build/templates/cxx/cxx.gni**. @@ -62,19 +62,25 @@ ohos_shared_library("helloworld") { part_name = [string] # (Mandatory) Component name. output_dir - - # Sanitizer variables - cfi = [boolean] - cfi_cross_dso = [boolean] # CFI: shared library support. - scs = [boolean] - scudo = [] - ubsan = [] - boundary_sanitize = [] - integer_overflow_sanitize = [] - + + # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. + sanitize = { + # Sanitizer settings + cfi = [boolean] # Whether to enable the control-flow integrity (CFI) check. + cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. + integer_overflow = [boolean] # Whether to enable the integer overflow check. + boundary_sanitize = [boolean] # Whether to enable the bounds check. + ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. + all_ubsan = [boolean] # Whether to enable all UBSAN options. + ... + + debug = [boolean] # Whether to enable the debug mode. + blocklist = [string] # Path of the blocklist. + } + testonly = [boolean] license_as_sources = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. remove_configs = [] no_default_deps = [] install_images = [] @@ -104,19 +110,25 @@ ohos_static_library("helloworld") { lib_dirs = [] public_configs = [] - - # Sanitizer variables - cfi = [boolean] - cfi_cross_dso = [boolean] # CFI: shared library support. - scs = [boolean] - scudo = [] - ubsan = [] - boundary_sanitize = [] - integer_overflow_sanitize = [] - + + # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. + sanitize = { + # Sanitizer settings + cfi = [boolean] # Whether to enable the CFI check. + cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. + integer_overflow = [boolean] # Whether to enable the integer overflow check. + boundary_sanitize = [boolean] # Whether to enable the bounds check. + ubsan = [boolean] # Whether to enable some UBSAN options. + all_ubsan = [boolean] # Whether to enable all UBSAN options. + ... + + debug = [boolean] # Whether to enable the debug mode. + blocklist = [string] # Path of the blocklist. + } + remove_configs = [] no_default_deps = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. license_as_sources = [] use_exceptions = [] } @@ -137,26 +149,32 @@ ohos_executable("helloworld") { ] # The dependent modules must be declared in inner_kits by the dependent component. ohos_test = [] test_output_dir = [] - - # Sanitizer variables - cfi = [boolean] - cfi_cross_dso = [boolean] # CFI: shared library support. - scs = [boolean] - scudo = [] - ubsan = [] - boundary_sanitize = [] - integer_overflow_sanitize = [] - + + # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. + sanitize = { + # Sanitizer settings + cfi = [boolean] # Whether to enable the CFI check. + cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. + integer_overflow = [boolean] # Whether to enable the integer overflow check. + boundary_sanitize = [boolean] # Whether to enable the bounds check. + ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. + all_ubsan = [boolean] # Whether to enable all UBSAN options. + ... + + debug = [boolean] # Whether to enable the debug mode. + blocklist = [string] # Path of the blocklist. + } + testonly = [boolean] license_as_sources = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. remove_configs = [] static_link = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. relative_install_dir = [] symlink_target_name = [] - output_dir = [directory] # Directory in which output files are located. + output_dir = [directory] # Directory in which output files are located. install_enable = [boolean] version_script = [] use_exceptions = [] @@ -168,43 +186,52 @@ ohos_executable("helloworld") { ```shell import("//build/ohos.gni") ohos_source_set("helloworld") { - sources = ["file"] # Source code in .c format. - include_dirs = [] # Directories to be included. - configs = [] # Configuration. - public = [] # Header files. + sources = ["file"] # Source code in .c format. + include_dirs = [] # Directories to be included. + configs = [] # Configuration. + public = [] # Header files. defines = [] public_configs = [] - part_name = [string] # Component name. - subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. deps = [] # Define dependent modules that belong to the same component. - external_deps = [ # Define dependent modules that belong to different components. - "part_name:module_name", # The value is in the Component_name:Module_name format. - ] # The dependent modules must be declared in inner_kits by the dependent component. - - # Sanitizer variables - cfi = [boolean] - cfi_cross_dso = [boolean] # CFI: shared library support. - scs = [boolean] - scudo = [] - ubsan = [] - boundary_sanitize = [] - integer_overflow_sanitize = [] - + external_deps = [ # Define dependent modules that belong to different components. + "part_name:module_name", # The value is in the Component_name:Module_name format. + ] # The dependent modules must be declared in inner_kits by the dependent component. + + # Sanitizer configuration. Each item is optional, and set to false or left unspecified by default. + sanitize = { + # Sanitizer settings + cfi = [boolean] # Whether to enable the CFI check. + cfi_cross_dso = [boolean] # Whether to enable the cross-DSO CFI check. + integer_overflow = [boolean] # Whether to enable the integer overflow check. + boundary_sanitize = [boolean] # Whether to enable the bounds check. + ubsan = [boolean] # Whether to enable some Undefined Behavior Sanitizer (UBSAN) options. + all_ubsan = [boolean] # Whether to enable all UBSAN options. + ... + + debug = [boolean] # Whether to enable the debug mode. + blocklist = [string] # Path of the blocklist. + } + testonly = [boolean] license_as_sources = [] license_file = [] remove_configs = [] no_default_deps = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. license_as_sources = [] use_exceptions = [] } ``` ->**NOTE**
Only **sources** and **part_name** are mandatory. +> **NOTE** +> +> - Only **sources** and **part_name** are mandatory. +> - For details about the Sanitizer configuration, see [Using Sanitizer](subsys-build-reference.md#using-sanitizer). -### Prebuilt Template Example +### Prebuilt Template Examples The .gni file of the prebuilt templates is located in **openharmony/build/templates/cxx/prebuilt.gni**. @@ -213,25 +240,25 @@ The .gni file of the prebuilt templates is located in **openharmony/build/templa ```shell import("//build/ohos.gni") ohos_prebuilt_executable("helloworld") { - sources = ["file"] # Source. + sources = ["file"] # Source. output = [] install_enable = [boolean] - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. public_configs = [] - subsystem_name = [string] # Subsystem name. - part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. testonly = [boolean] visibility = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. symlink_target_name = [] - license_file = [] # A .txt file. + license_file = [] # A .txt file. license_as_sources = [] } ``` @@ -241,25 +268,25 @@ ohos_prebuilt_executable("helloworld") { ```shell import("//build/ohos.gni") ohos_prebuilt_shared_library("helloworld") { - sources = ["file"] # .so files. + sources = ["file"] # .so files. output = [] install_enable = [boolean] - deps = [] # Define dependent modules that belong to the same component. + deps = [] # Define dependent modules that belong to the same component. public_configs = [] - subsystem_name = [string] # Subsystem name. - part_name = [string] # Component name. + subsystem_name = [string] # Subsystem name. + part_name = [string] # Component name. testonly = [boolean] visibility = [] install_images = [] - module_install_dir = [] # Module installation directory, starting from system/ or vendor/. - relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. + module_install_dir = [] # Module installation directory, starting from system/ or vendor/. + relative_install_dir = [] # Relative module installation directory (relative to system/etc). If module_install_dir is configured, the parameter does not take effect. symlink_target_name = [string] - license_file = [string] # A .txt file. + license_file = [string] # A .txt file. license_as_sources = [] } ``` @@ -289,7 +316,7 @@ ohos_prebuilt_static_library("helloworld") { ### HAP Templates -See [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md). +For details, see [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md). @@ -330,11 +357,11 @@ ohos_sa_profile("helloworld") { } ``` ->**NOTE**: Only **sources** and **part_name** are mandatory. +> **NOTE**
Only **sources** and **part_name** are mandatory. ## Adding and Building a Module -The figure below illustrates the process for adding a module. A module belongs to a component, which belongs to a subsystem. Please note that the chipset solution, as a special component, does not have a subsystem. You may need to: +The following figure shows the logic for adding a module. Generally, you need to add a module to a component of a subsystem. If there is no subsystem or component, you must add the subsystem and component first. Note that the chip solution is a special component and does not have a subsystem. - Add a module to an existing component. @@ -352,47 +379,47 @@ The figure below illustrates the process for adding a module. A module belongs t ```shell { - "name": "@ohos/, # HPM component name, in the "@Organization/Component_name" format. - "description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions. - "version": "3.1", # Version, which must be the same as the version of OpenHarmony. - "license": "MIT", # Component license. - "publishAs": "code-segment", # HPM package release mode. The default value is code-segment. + "name": "@ohos/, # HPM component name, in the "@Organization/Component_name" format. + "description": "xxxxxxxxxxxxxxxxxxx", # Description of the component functions. + "version": "3.1", # Version, which must be the same as the version of OpenHarmony. + "license": "MIT", # Component license. + "publishAs": "code-segment", # HPM package release mode. The default value is code-segment. "segment": { "destPath": "third_party/nghttp2" - }, # Code restoration path (source code path) set when publishAs is code-segment. - "dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty. - "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. + }, # Code restoration path (source code path) set when publishAs is code-segment. + "dirs": {}, # Directory structure of the HPM package. This field is mandatory and can be left empty. + "scripts": {}, # Scripts to be executed. This field is mandatory and can be left empty. "licensePath": "COPYING", "readmePath": { "en": "README.rst" }, - "component": { # Component attributes. - "name": "", # Component name. - "subsystem": "", # Subsystem to which the component belongs. - "syscap": [], # System capabilities provided by the component for applications. - "features": [], # List of configurable features of the component. Generally, this parameter corresponds to sub_component in build. - "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, standard, or their combinations. - "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. - "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. + "component": { # Component attributes. + "name": "", # Component name. + "subsystem": "", # Subsystem to which the component belongs. + "syscap": [], # System capabilities provided by the component for applications. + "features": [], # List of configurable features of the component. Generally, this parameter corresponds to sub_component in build. + "adapted_system_type": [], # Types of adapted systems. The value can be mini, small, standard, or their combinations. + "rom": "xxxKB" # ROM baseline. If there is no baseline, enter the current value. + "ram": "xxxKB", # RAM baseline. If there is no baseline, enter the current value. "deps": { - "components": [ # Other components on which this component depends. - "third_party": [ # Third-party open-source software on which this component depends. + "components": [ # Other components on which this component depends. + "third_party": [ # Third-party open-source software on which this component depends. }, - "build": { # Build-related configuration. + "build": { # Build-related configuration. "sub_component": [ - "//foundation/arkui/napi:napi_packages", # Existing module 1. - "//foundation/arkui/napi:napi_packages_ndk" # Existing module 2. - "//foundation/arkui/napi:new" # Module to add. - ], # Component build entry. Configure the module here. - "inner_kits": [], # APIs between components. - "test": [] # Entry for building the component's test cases. + "//foundation/arkui/napi:napi_packages", # Existing module 1. + "//foundation/arkui/napi:napi_packages_ndk"# Existing module 2. + "//foundation/arkui/napi:new" # Module to add. + ], # Component build entry. Configure the module here. + "inner_kits": [], # APIs between components. + "test": [] # Entry for building the component's test cases. } } } ``` - >**NOTE**
The **bundle.json** file must be in the folder of the corresponding subsystem. + > **NOTE**
The **bundle.json** file must be in the folder of the corresponding subsystem. 3. Start the build and check whether a .so file or binary file is generated. @@ -471,7 +498,7 @@ The figure below illustrates the process for adding a module. A module belongs t ] }, { - "subsystem": "subsystem_new", # Name of the new subsystem to add + "subsystem": "subsystem_new", # Name of the new subsystem to add. "components": [ { "component": "component_new2", # Name of the component to be added to the new subsystem @@ -485,25 +512,25 @@ The figure below illustrates the process for adding a module. A module belongs t 4. Start the build and check whether a .so file or binary file is generated. + **Building a Module** You can start the build by using the [CLI or hb tool](subsys-build-all.md#build-commands). The following uses the CLI as an example: You can run the **--build-target** *Module_name* command to build a module separately. -```shell -./build.sh --build-target Module_name -``` + ```shell + ./build.sh --build-target Module_name + ``` You can also build a product. For example, to build hispark_taurus_standard, run the following command: -```shell -./build.sh --product-name hispark_taurus_standard --build-target Module_name --ccache -``` + ```shell + ./build.sh --product-name hispark_taurus_standard --build-target Module_name --ccache + ``` You can also build the component to which the module belongs. -```shell -./build.sh --product-name hispark_taurus_standard --build-target musl --build-target Module_name --ccache -``` - + ```shell + ./build.sh --product-name hispark_taurus_standard --build-target musl --build-target Module_name --ccache + ``` diff --git a/en/device-dev/subsystems/subsys-build-reference.md b/en/device-dev/subsystems/subsys-build-reference.md index b18b9123625402ced8d64219b56aff6ca0019b9e..0ac5679c3afa3f2530733555a26e8ad5c99dddf7 100644 --- a/en/device-dev/subsystems/subsys-build-reference.md +++ b/en/device-dev/subsystems/subsys-build-reference.md @@ -55,8 +55,8 @@ The dependency between modules can be classified into **deps** (left in the figu external_deps = [ "part1:module1", ... - ] # Inter-component dependency. The dependent module must be declared in inner_kits by the dependent component. - part_name = "part2" # (Mandatory) Name of the component to which the module belongs. + ] # Inter-component dependency. The dependent module must be declared in inner_kits by the dependent component. + part_name = "part2" # (Mandatory) Name of the component to which the module belongs. } ``` @@ -64,18 +64,21 @@ The dependency between modules can be classified into **deps** (left in the figu ## Using Sanitizer -When adding a module, you can enable the Sanitizer, such as the integer overflow check and control-flow integrity (CFI), provided by the compiler as required. You can also enable the debug or release mode and configure a blocklist. Each configuration item is optional. It is **false** by default. You can also leave it empty. +When adding a module, you can enable the Sanitizer, such as the integer overflow check and control-flow integrity (CFI), provided by the compiler as required. You can also enable the debug or release mode and configure a blocklist. Each configuration item is optional and **false** by default. You can also leave it empty. Sanitizer configuration example: ``` shell ohos_shared_library("example") { sanitize = { - cfi = true - cfi_cross_dso = true # CFI: shared library support. - integer_overflow = true - debug = true # Optional. The debug mode is disabled by default. - blocklist = "./blocklist.txt" # Optional. Enter the path of the blocklist. + cfi = true # Enable the CFI check. + cfi_cross_dso = true # Enable the cross-DSO CFI check. + integer_overflow = true # Enable the integer overflow check. + boundary_sanitize = true # Enable the bounds check. + ubsan = true # Enable some UBSAN options. + all_ubsan = true # Enable all UBSAN options. + debug = true # Enable the debug mode, which is disabled by default. + blocklist = "./blocklist.txt" # Path of the blocklist. } ... } @@ -83,10 +86,13 @@ Sanitizer configuration example: **Supported Sanitizer Types** -Currently, the following two types of Sanitizers are supported: +Currently, Sanitizers provides the following functions: -- Integer overflow check: provides check of unsigned integer overflow (unsigned_integer_overflow), check of signed integer overflow (signed_integer_overflow), or both (integer_overflow). -- CFI: prevents malware attacks from redirecting the control flow of a program. +- **integer_overflow**: provides check of unsigned integer overflow (unsigned_integer_overflow), check of signed integer overflow (signed_integer_overflow), or both (integer_overflow). +- CFI: provides CFI and cross-DSO CFI checks. +- **boundary_sanitize**: provides the bounds check. +- **ubsan**: checks some Undefined Behavior Sanitizer (UBSAN) options, including **bool**, **integer-divide-by-zero**, **return**, **returns-nonnull-attribute**, **shift-exponent**, **unreachable**, and **vla-bound**. +- **all_ubsan**: checks all UBSAN options. **Release and Debug Modes** @@ -96,6 +102,7 @@ Currently, the following two types of Sanitizers are supported: - Release mode: If release mode is enabled, the application will be directly interrupted when an error occurs. This can protect the system against errors or maliciously attacks. + **Blocklist** The blocklist specifies the functions or source programs that are not affected by Sanitizer in the module. It prevents benign behavior from being identified as errors or prevents hotspot functions from generating unreasonable and unacceptable overheads. Exercise caution when using this function. diff --git a/en/readme/ability.md b/en/readme/ability.md new file mode 100644 index 0000000000000000000000000000000000000000..3219acba7084fadc68464d3a9ed9db7b7fd54040 --- /dev/null +++ b/en/readme/ability.md @@ -0,0 +1,135 @@ +# Ability Framework + +## Overview + +The **ability framework** (also called the ability management framework) is used to centrally schedule and manage the running and lifecycle of abilities. An application process can support multiple abilities, and an ability can be called either within a process or across processes. The Ability Manager Service provided in the framework schedules and manages abilities in an application and manages the lifecycle changes of these abilities. + +![](figures/aafwk.png) + +**Architecture Description** + +- **Ability Kit** provides basic running environment for an ability to run. **Ability** is the minimum unit for the system to schedule an application. It is a component that can implement an independent functionality. An application can contain one or more **Ability** instances. There are two types of abilities: Feature Ability (FA) and Particle Ability (PA). FAs use the Page template, and PAs use the Service and Data templates. (The abilities implemented using the Page, Service, or Data template are referred to as the Page, Service, or Data abilities for short, respectively.) + +- **AbilityManagerService** is a system service used to coordinate the running relationships and lifecycle states of **Ability** instances. + - The AbilityStackManager sub-module maintains the presentation sequence of abilities in the stack. + - The AbilityConnectManager sub-module manages connections to Service abilities. + - The DataAbilityManager sub-module manages Data abilities. + - The AppScheduler sub-module schedules and manages the App Manager Service. + - The AbilityScheduler sub-module schedules and manages abilities. + - The LifecycleDeal sub-module schedules and manages ability lifecycle events. + +The **ability lifecycle** is a general term for all states of an ability (either a Page or a Service ability), such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**. + + - The following figure shows the transitions between different states in a Page ability's lifecycle. + +![PageAbility-Lifecycle](figures/page-ability-lifecycle.png) + + + + - The following figure shows the transitions between different states in a Service ability's lifecycle. + +![ServiceAbility-Lifecycle](figures/service-ability-lifecycle.png) + +**Description of ability lifecycle states:** + + - **UNINITIALIZED**: The ability is not initialized. This state is a temporary state. An ability changes directly to the **INITIAL** state upon its creation. + + - **INITIAL**: This state refers to the initial or stopped state. The ability in this state is not running. The ability enters the **INACTIVE** state after it is started. + + - **INACTIVE**: The ability is visible but does not gain focus. This state is the same as the **ACTIVE** state because the concept of window focus is not supported currently. + + - **ACTIVE**: The ability is in the foreground and has focus. The ability changes from the **ACTIVE** state to the **INACTIVE** state before returning to the background. + + - **BACKGROUND**: The ability returns to the background. After being re-activated, the ability enters the **ACTIVE** state. After being destroyed, the ability enters the **INITIAL** state. + +The following figure shows the callbacks to be invoked during the transitions between different lifecycle states of a Page ability. + +![PageAbility-Lifecycle-Callbacks](figures/page-ability-lifecycle-callbacks.png) + + + +The following figure shows the callbacks to be invoked during the transitions between different lifecycle states of a Service ability. + +![Service-Ability-Lifecycle-Callbacks](figures/service-ability-lifecycle-callbacks.jpg) + + + +## Directory Structure + +``` +foundation/ +└──foundation/aafwk/standard + ├── frameworks + │ └── kits + │ └── ability # Core code for AbilityKit + ├── interfaces + │ └── innerkits + │ └── want # External APIs of the information carrier used for interaction between abilities + └── services + ├── abilitymgr # Framework code of the Ability Manager Service + ├── common # Log component + ├── test # Testing + └── tools # aa command code +``` + +## Usage Guidelines + +The application framework does not have the permission management capability. + +In the current version, the JavaScript APIs of the following modules are provided only for the system applications Launcher, Settings, and SystemUI. Significant changes may be provided in later versions. + +- @ohos.feature_ability.d.ts + +- @ohos.napi_ability_manager.d.ts + +- abilityinfo.d.ts + +- abilitymissioninfo.d.ts + +- applicationinfo.d.ts + +- appprocessstate.ts + +- common.d.ts + +- elementname.d.ts + +- moduleinfo.d.ts + +- processinfo.d.ts + +- want.d.ts + +## **aa Commands** + +**aa help** + +| Command | Description | +| ------- | ------------------ | +| aa help | Displays the command help information.| + +**aa start** + +| Command | Description | +| --------------------------------------------------------- | ------------------------ | +| aa start [-d ] -a -b | Starts an ability. The device ID can be empty.| + +Example: +``` +aa start -d 12345 -a com.ohos.app.MainAbility -b com.ohos.app +``` + +**aa dump** + +| Command | Description | +| ---------- | --------------------- | +| aa dump -a | Displays the ability information in the stack.| + +## Repositories Involved +Ability framework + +[ability_base](https://gitee.com/openharmony/ability_ability_base) + +[ability_runtime](https://gitee.com/openharmony/ability_ability_runtime) + +[form_fwk](https://gitee.com/openharmony/ability_form_fwk) diff --git a/en/readme/figures/aafwk.png b/en/readme/figures/aafwk.png new file mode 100644 index 0000000000000000000000000000000000000000..9c984fd666ab4ff18cdfb5e2035f06342249fd4a Binary files /dev/null and b/en/readme/figures/aafwk.png differ diff --git a/en/readme/figures/page-ability-lifecycle-callbacks.png b/en/readme/figures/page-ability-lifecycle-callbacks.png new file mode 100644 index 0000000000000000000000000000000000000000..42cbde8b3f2216141b68a8d12b84889b154af58e Binary files /dev/null and b/en/readme/figures/page-ability-lifecycle-callbacks.png differ diff --git a/en/readme/figures/page-ability-lifecycle.png b/en/readme/figures/page-ability-lifecycle.png new file mode 100644 index 0000000000000000000000000000000000000000..d4fff2a49bf103cb5d8763f271c847fc1b711723 Binary files /dev/null and b/en/readme/figures/page-ability-lifecycle.png differ diff --git a/en/readme/figures/service-ability-lifecycle-callbacks.jpg b/en/readme/figures/service-ability-lifecycle-callbacks.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d24e65e9a1695fe80da4f64e734969ae0e08139a Binary files /dev/null and b/en/readme/figures/service-ability-lifecycle-callbacks.jpg differ diff --git a/en/readme/figures/service-ability-lifecycle.png b/en/readme/figures/service-ability-lifecycle.png new file mode 100644 index 0000000000000000000000000000000000000000..66c11ca4db7900696c064461cb7f774bfcd48d49 Binary files /dev/null and b/en/readme/figures/service-ability-lifecycle.png differ diff --git a/en/readme/startup.md b/en/readme/startup.md index 5f12643fffc97c3a896d8fe918dde75a4e9c91a6..e97bf7d8888610ffd98f4e6cb38c93bf3563680a 100644 --- a/en/readme/startup.md +++ b/en/readme/startup.md @@ -39,7 +39,7 @@ The startup subsystem is responsible for starting key system processes and servi | base/startup/appspawn_lite | appspawn module of the Lite edition for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them. | Platforms using the LiteOS Cortex-A kernel | | base/startup/appspawn_standard | appspawn module of the Standard version for spawning application processes. It receives Ability Manager Service (AMS) messages via IPC, parses the messages, starts application processes based on the parsing result, and grants permissions to them. | Platforms using the Linux kernel | | base/startup/bootstrap_lite | bootstrap module for starting all services except core system services. | Platforms using the LiteOS Cortex-M kernel | -| base/startup/init_lite | init_lite module for implementing the init process, which is the first user-space process loaded after the kernel is initialized. Upon startup, the process parses the configuration file in **/etc/init.cfg**. Based on the parsing result, the process then starts other key system processes and grants required permissions to them. | Platforms using the LiteOS Cortex-A or Linux kernel | +| base/startup/init | init module for implementing the init process, which is the first user-space process loaded after the kernel is initialized. Upon startup, the process parses the configuration file in **/etc/init.cfg**. Based on the parsing result, the process then starts other key system processes and grants required permissions to them. | Platforms using the LiteOS Cortex-A or Linux kernel | | base/startup/syspara_lite | syspara module that provides APIs to obtain device information, including the product name, brand name, category name, and manufacturer name. | All platforms | @@ -60,7 +60,7 @@ base/startup/ ├── bootstrap_lite # bootstrap module │ └── services │ └── source # Source files -├── init_lite # init module +├── init # init module │ ├── initsync # Source files │ ├── interfaces # External APIs │ └── services diff --git a/en/readme/test.md b/en/readme/test.md index d4410e5ab091974940eace2baa5d58bc8a6be406..d5c6a903b42583ac46192752071b8174bd09b819 100644 --- a/en/readme/test.md +++ b/en/readme/test.md @@ -58,7 +58,9 @@ subsystem # Subsystem │ ... ``` -> **NOTE**
Test cases are classified into common test cases and device-specific test cases. You are advised to place common test cases in the **common** directory and device-specific test cases in the directories of the related devices. +> **NOTE** +> +> Test cases are classified into common test cases and device-specific test cases. You are advised to place common test cases in the **common** directory and device-specific test cases in the directories of the related devices. ### Writing Test Cases This test framework supports test cases written in multiple programming languages and provides different templates for different languages. @@ -68,7 +70,8 @@ This test framework supports test cases written in multiple programming language - Naming rules for source files The source file name of test cases must be the same as that of the test suite. The file names must use lowercase letters and in the [Function]\_[Sub-function]\_**test** format. More specific sub-functions can be added as required. -Example: + Example: + ``` calculator_sub_test.cpp ``` @@ -127,7 +130,7 @@ Example: The procedure is as follows: 1. Add comment information to the test case file header. - Enter the header comment in the standard format. For details, see [Code Specifications] (https://gitee.com/openharmony/docs/blob/master/en/contribute/code-contribution.md). + Enter the header comment in the standard format. For details, see [Code Specifications](https://gitee.com/openharmony/docs/blob/master/en/contribute/code-contribution.md). 2. Add the test framework header file and namespace. ``` @@ -135,14 +138,12 @@ Example: using namespace testing::ext; ``` - - 3. Add the header file of the test class. - ``` + 3. Add the header file of the test class. + ``` #include "calculator.h" ``` - 4. Define the test suite (test class). - ``` + ``` class CalculatorSubTest : public testing::Test { public: static void SetUpTestCase(void); @@ -169,60 +170,55 @@ Example: void CalculatorSubTest::TearDown(void) { // Set a teardown function, which will be called after each test case. - } - ``` - > **NOTE**
When defining a test suite, ensure that the test suite name is the same as the target to build and uses the upper camel case style. + } + ``` + > **NOTE** + > + > When defining a test suite, ensure that the test suite name is the same as the target to build and uses the upper camel case style. 5. Add implementation of the test cases, including test case comments and logic. - - ``` - /** - - * @tc.name: integer_sub_001 - - * @tc.desc: Verify the sub function. - - * @tc.type: FUNC - - * @tc.require: Issue Number - */ - HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) - { - // Step 1 Call the function to obtain the test result. - int actual = Sub(4, 0); - - // Step 2 Use an assertion to compare the obtained result with the expected result. - EXPECT_EQ(4, actual); - } - ``` + ``` + /** + * @tc.name: integer_sub_001 + * @tc.desc: Verify the sub function. + * @tc.type: FUNC + * @tc.require: Issue Number + */ + HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) + { + // Step 1 Call the function to obtain the test result. + int actual = Sub(4,0); + + // Step 2 Use an assertion to compare the obtained result with the expected result. + EXPECT_EQ(4, actual); + } + ``` The following test case templates are provided for your reference. - | Template | Description | + | Template | Description | | --------------- | ------------------------------------------------------------ | - | HWTEST(A,B,C) | Use this template if the test case execution does not depend on setup or teardown. | + | HWTEST(A,B,C) | Use this template if the test case execution does not depend on setup or teardown. | | HWTEST_F(A,B,C) | Use this template if the test case execution (excluding parameters) depends on setup and teardown. | | HWTEST_P(A,B,C) | Use this template if the test case execution (including parameters) depends on setup and teardown. | - In the template names: + In the template names: - *A* indicates the test suite name. - + - *B* indicates the test case name, which is in the *Function*\_*No.* format. The *No.* is a three-digit number starting from **001**. - *C* indicates the test case level. There are five test case levels: guard-control level 0 and non-guard-control level 1 to level 4. Of levels 1 to 4, a smaller value indicates a more important function verified by the test case. - - > **NOTE** > > - The expected result of each test case must have an assertion. - >- The test case level must be specified. + > - The test case level must be specified. > - It is recommended that the test be implemented step by step according to the template. - >- The comment must contain the test case name, description, type, and requirement number, which are in the @tc.*xxx*: *value* format. The test case description must be in the @tc.xxx format. The test case type @tc.type can be any of the following: - + > - The comment must contain the test case name, description, type, and requirement number, which are in the @tc.*xxx*: *value* format. The test case description must be in the @tc.xxx format. The test case type @tc.type can be any of the following: + | Test Case Type | Code | - | ---------------- | ---- | + | ---------------- | ---- | | Function test | FUNC | | Performance test | PERF | | Reliability test | RELI | @@ -339,7 +335,7 @@ When a test case is executed, the test framework searches for the build file of The following provides templates for different languages for your reference. - **Test case build file example (C++)** - ``` + ```c++ import("//build/test.gni") @@ -386,8 +382,10 @@ The following provides templates for different languages for your reference. ``` module_output_path = "subsystem_examples/calculator" ``` - > **NOTE**
The output path is ***Part name*/*Module name***. - + > **NOTE** + > + > The output path is ***Part name*/*Module name***. + 4. Configure the directories for dependencies. ``` @@ -397,7 +395,9 @@ The following provides templates for different languages for your reference. include_dirs = [ "../../../include" ] } ``` - > **NOTE**
Generally, the dependency directories are configured here and directly referenced in the build script of the test case. + > **NOTE** + > + > Generally, the dependency directories are configured here and directly referenced in the build script of the test case. 5. Set the output build file for the test cases. @@ -418,8 +418,8 @@ The following provides templates for different languages for your reference. ] sources += [ "calculator_sub_test.cpp" ] configs = [ ":module_private_config" ] - deps = [ "//third_party/googletest:gtest_main" ] - } + deps = [ "//third_party/googletest:gtest_main" ] + } ``` > **NOTE** @@ -429,27 +429,25 @@ The following provides templates for different languages for your reference. > - **ohos_systemtest**: system test > - **ohos_performancetest**: performance test > - **ohos_securitytest**: security test - > - **ohos_reliabilitytest**: reliability test + > - **ohos_reliabilitytest**: reliability test > - **ohos_distributedtest**: distributed test - + 7. Group the test case files by test type. - - ``` - group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] - } - ``` + + ``` + group("unittest") { + testonly = true + deps = [":CalculatorSubTest"] + } + ``` > **NOTE** > > Grouping test cses by test type allows you to execute a specific type of test cases when required. - ​ - -- **Test case build file example (JavaScript)** +- **Test case build file example (JavaScript)** ​ - ``` + ```javascript import("//build/test.gni") @@ -484,7 +482,9 @@ The following provides templates for different languages for your reference. ``` module_output_path = "subsystem_examples/app_info" ``` - > **NOTE**
The output path is ***Part name*/*Module name***. + > **NOTE** + > + > The output path is ***Part name*/*Module name***. 4. Set the output build file for the test cases. @@ -492,9 +492,10 @@ The following provides templates for different languages for your reference. ohos_js_unittest("GetAppInfoJsTest") { } ``` - > **NOTE**
- >- Use the **ohos\_js\_unittest** template to define the JavaScript test suite. Pay attention to the difference between JavaScript and C++. - >- The file generated for the JavaScript test suite must be in .hap format and named after the test suite name defined here. The test suite name must end with **JsTest**. + > **NOTE** + > + > - Use the **ohos\_js\_unittest** template to define the JavaScript test suite. Pay attention to the difference between JavaScript and C++. + > - The file generated for the JavaScript test suite must be in .hap format and named after the test suite name defined here. The test suite name must end with **JsTest**. 5. Configure the **config.json** file and signature file, which are mandatory. @@ -576,7 +577,9 @@ The following provides templates for different languages for your reference. deps = [ ":GetAppInfoJsTest" ] } ``` - > **NOTE**
Grouping test cases by test type allows you to execute a specific type of test cases when required. + > **NOTE** + > + > Grouping test cases by test type allows you to execute a specific type of test cases when required. #### Configuring ohos.build @@ -597,7 +600,9 @@ Configure the part build file to associate with specific test cases. ] } ``` -> **NOTE**
**test_list** contains the test cases of the corresponding module. +> **NOTE** +> +> **test_list** contains the test cases of the corresponding module. ### Configuring Test Case Resources Test case resources include external file resources, such as image files, video files, and third-party libraries, required for test case execution. @@ -623,7 +628,8 @@ Perform the following steps: resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" } ``` - >**NOTE**
+ >**NOTE** + > >- **target_name** indicates the test suite name defined in the **BUILD.gn** file in the **test** directory. >- **preparer** indicates the action to perform before the test suite is executed. >- **src="res"** indicates that the test resources are in the **resource** directory under the **test** directory. @@ -678,7 +684,9 @@ Before executing test cases, you need to modify the configuration based on the d ``` ->**NOTE**
If HDC is connected to the device before the test cases are executed, you only need to configure the device IP address and port number, and retain the default settings for other parameters. +>**NOTE** +> +>If HDC is connected to the device before the test cases are executed, you only need to configure the device IP address and port number, and retain the default settings for other parameters. ### Executing Test Cases on Windows #### Building Test Cases @@ -689,16 +697,19 @@ Test cases cannot be built on Windows. You need to run the following command to ``` When the build is complete, the test cases are automatically saved in **out/hispark_taurus/packages/phone/images/tests**. ->**NOTE**
In the command, **hispark_taurus_standard** indicates the product supported by the current version, and **make_test** indicates all test cases. You can set the build options based on requirements:
-> - --**product-name**: specifies the name of the product to build. It is mandatory. -> - --**build-target**: specifies the target to build. It is optional. +>**NOTE** +> +>In the command, **hispark_taurus_standard** indicates the product supported by the current version, and **make_test** indicates all test cases. You can set the build options based on requirements:
+> +>- --**product-name**: specifies the name of the product to build. It is mandatory. +>- --**build-target**: specifies the target to build. It is optional. #### Setting Up the Execution Environment 1. On Windows, create the **Test** directory in the test framework and then create the **testcase** directory in the **Test** directory. 2. Copy **developertest** and **xdevice** from the Linux environment to the **Test** directory on Windows, and copy the test cases to the **testcase** directory. - > **NOTE**
+ > **NOTE** > > Port the test framework and test cases from the Linux environment to the Windows environment for subsequent execution. 3. Modify the **user_config.xml** file. @@ -712,7 +723,9 @@ When the build is complete, the test cases are automatically saved in **out/hisp D:\Test\testcase\tests ``` - >**NOTE**
`` indicates whether to build test cases. `` indicates the path for searching for test cases. + >**NOTE** + > + >`` indicates whether to build test cases. `` indicates the path for searching for test cases. #### Executing Test Cases 1. Start the test framework. @@ -746,13 +759,17 @@ To enable test cases to be executed on a remote Linux server or a Linux VM, map hdc_std kill hdc_std -m -s 0.0.0.0:8710 ``` - >**NOTE**
The IP address and port number are default values. + >**NOTE** + > + >The IP address and port number are default values. 2. On the HDC client, run the following command: ``` hdc_std -s xx.xx.xx.xx:8710 list targets ``` - >**NOTE**
Enter the IP address of the device to test. + >**NOTE** + > + >Enter the IP address of the device to test. #### Executing Test Cases 1. Start the test framework. @@ -787,7 +804,9 @@ You can obtain the test result in the following directory: ``` test/developertest/reports/xxxx_xx_xx_xx_xx_xx ``` ->**NOTE**
The folder for test reports is automatically generated. +>**NOTE** +> +>The folder for test reports is automatically generated. The folder contains the following files: | Type| Description| diff --git a/en/release-notes/OpenHarmony-v3.2-beta1.md b/en/release-notes/OpenHarmony-v3.2-beta1.md index 55b353757fd8ea063d99eae61469785f506f8ec8..985ec8a61782ef253cda113dbfd2988da683317b 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta1.md +++ b/en/release-notes/OpenHarmony-v3.2-beta1.md @@ -186,26 +186,26 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | Subsystem| Sample| Introduction| Programming Language| | -------- | -------- | -------- | -------- | | ArkUI | [MouseEvent](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) | This sample simulates a minesweeper game that calls mouse event-related APIs.| eTS | -| ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Vibrator) | This sample simulates the countdown scenario to show the use of the vibrator APIs.| eTS | -| DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/FaultLogger) | This sample illustrates how to obtain fault information of an application in eTS.| eTS | +| ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator) | This sample simulates the countdown scenario to show the use of the vibrator APIs.| eTS | +| DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DFX/FaultLogger) | This sample illustrates how to obtain fault information of an application in eTS.| eTS | | ArkUI | [Gallery](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) | This sample demonstrates the functions of different components such as universal events, universal attributes, and gestures.| eTS | | Graphics| [JsWebGL](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL) | This sample shows how to use WebGL APIs to draw pentagrams and rectangles by invoking GPU resources.| JS | -| ArkUI | [Clock](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) | This sample exemplifies how to implement a simple clock application using the eTS UI capability.| eTS | -| Network management| [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Http) | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| eTS | +| ArkUI | [Clock](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock) | This sample exemplifies how to implement a simple clock application using the eTS UI capability.| eTS | +| Network management| [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| eTS | | Network management| [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| eTS | -| Distributed data management| [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedRdb) | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with eTS.| eTS | -| Ability| [BackgroundTaskManager](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) | This sample simulates the download function. Being processed by the background task management, a download task can continue after the application exits. It stops until the download is complete.| eTS | -| Ability| [BringApp](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BringApp) | This sample uses the **FeatureAbility** APIs to start a system application based on the application's bundle name and ability name.| eTS | -| Media| [VideoPlayer](https://gitee.com/openharmony/applications_app_samples/tree/master/media/VideoPlayer) | This sample shows how to play a video using the **VideoPlayer** APIs in eTS. It also provides an ability that can be invoked by other applications to play the video.| eTS | -| Ability| [DistributeCalc](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc) | This sample implements a simple calculator application using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator FA to perform collaborative calculation.| eTS | -| Web | [Browser](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Browser) | This sample uses the stage model and related APIs to show a simple browser.| eTS | -| Ability| [DeviceUsageStatistics](https://gitee.com/openharmony/applications_app_samples/tree/master/device/DeviceUsageStatistics) | This sample shows the device usage statistics.| eTS | -| ArkUI | [AdaptiveCapabilities](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS | -| ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Game2048) | This sample shows how to develop a 2048 game using the **\** component.| eTS | -| Window Manager| [Window](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Window) | This sample shows how to create a window, display an application over another application in the form of a floating window, and display an application on split screens.| eTS | -| Distributed data management| [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Preferences) | This sample shows the theme switching function of preferences.| eTS | +| Distributed data management| [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with eTS.| eTS | +| Ability| [BackgroundTaskManager](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) | This sample simulates the download function. Being processed by the background task management, a download task can continue after the application exits. It stops until the download is complete.| eTS | +| Ability| [BringApp](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/AbilityStartMode) | This sample uses the **FeatureAbility** APIs to start a system application based on the application's bundle name and ability name.| eTS | +| Media| [VideoPlayer](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) | This sample shows how to play a video using the **VideoPlayer** APIs in eTS. It also provides an ability that can be invoked by other applications to play the video.| eTS | +| Ability| [DistributeCalc](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/ArkTSDistributedCalc) | This sample implements a simple calculator application using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator FA to perform collaborative calculation.| eTS | +| Web | [Browser](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser) | This sample uses the stage model and related APIs to show a simple browser.| eTS | +| Ability| [DeviceUsageStatistics](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceUsageStatistics/DeviceUsageStatistics) | This sample shows the device usage statistics.| eTS | +| ArkUI | [AdaptiveCapabilities](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AdaptiveCapabilities) | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS | +| ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Game2048) | This sample shows how to develop a 2048 game using the **\** component.| eTS | +| Window Manager| [Window](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Settings) | This sample shows how to create a window, display an application over another application in the form of a floating window, and display an application on split screens.| eTS | +| Distributed data management| [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DataManagement/Preferences) | This sample shows the theme switching function of preferences.| eTS | | ArkUI | [NativeAPI](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) | This sample shows how to call C++ APIs in eTS and how C++ APIs call back JS APIs to play the Gomoku game. The native APIs implement the calculation logic, and eTS implements UI rendering and re-rendering.| eTS/C++ | -| Globalization| [International](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) | This sample shows how to use APIs related to i18n, intl, and resourceManager in eTS to set the system language, region, time, and time zone. It also provides locale setting examples.| eTS | +| Globalization| [International](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International) | This sample shows how to use APIs related to i18n, intl, and resourceManager in eTS to set the system language, region, time, and time zone. It also provides locale setting examples.| eTS | For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). diff --git a/en/release-notes/OpenHarmony-v3.2-beta2.md b/en/release-notes/OpenHarmony-v3.2-beta2.md index 44357fe88ab308a83010b5504e86b030c5afaa42..2b4a17c9cae653f5bbeb2e0ee24599d6a48d224b 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta2.md +++ b/en/release-notes/OpenHarmony-v3.2-beta2.md @@ -191,7 +191,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | ArkUI | AdaptiveCapabilities | This sample shows multi-device adaptation in eTS, including resource qualifiers, atomic layouts, and responsive layouts.| eTS | | ArkUI | JsAdaptiveCapabilities | This sample shows multi-device adaptation in JS, including resource qualifiers, atomic layouts, and responsive layouts.| JS | -For more information, visit [Samples](https://gitee.com/openharmony/app_samples). +For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). ## Resolved Issues diff --git a/en/release-notes/OpenHarmony-v3.2-beta3.md b/en/release-notes/OpenHarmony-v3.2-beta3.md index 506724c24b4a915053f0e7733157e398642e7a01..92ea36158f8854102c3053fc71f31449b158081a 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta3.md +++ b/en/release-notes/OpenHarmony-v3.2-beta3.md @@ -190,15 +190,15 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op | Subsystem| Name| Introduction| Programming Language| | -------- | -------- | -------- | -------- | -| ArkUI development framework| [HealthyDiet](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/HealthyDiet)| This sample app helps you keep food records and view food information. After you add food records, including the food type, weight, and meal time, the app can calculate nutrition data (calories, proteins, fats, and carbon water) for the meals and display the data in a bar chart.| eTS | -| ArkUI development framework| [MusicAlbum](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum)| This sample shows the home page of a music album app. The adaptive layout and responsive layout are used to ensure that the app can be properly displayed on devices irrespective of screen sizes.| eTS | -| Ability framework and file management subsystem| [Share](https://gitee.com/openharmony/applications_app_samples/tree/master/Share/CustomShare)| Using this sample app, you can share texts, links, and images with third-party applications and display them in these applications.| eTS | +| ArkUI development framework| [HealthyDiet](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/HealthyDiet)| This sample app helps you keep food records and view food information. After you add food records, including the food type, weight, and meal time, the app can calculate nutrition data (calories, proteins, fats, and carbon water) for the meals and display the data in a bar chart.| eTS | +| ArkUI development framework| [MusicAlbum](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/MusicAlbum)| This sample shows the home page of a music album app. The adaptive layout and responsive layout are used to ensure that the app can be properly displayed on devices irrespective of screen sizes.| eTS | +| Ability framework and file management subsystem| [Share](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/CustomShare)| Using this sample app, you can share texts, links, and images with third-party applications and display them in these applications.| eTS | | Ability framework| [GalleryForm](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm)| This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| eTS | -| ArkUI development framework| [AppMarket](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket)| This sample shows the home page of an application market, which contains the tab bar, banner, featured apps, and featured games.| eTS | -| ArkUI development framework| [Weather](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather)| This sample demonstrates one-time development for multi-device deployment by showing how to develop a weather app and deploy it across different devices. The demo app includes the following: home page, **Manage City** page, **Add City** page, and **Update Time** page.| eTS | -| Multimedia subsystem| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/media/MediaCollections)| This sample shows the capabilities of online streaming, audio and video playback control, and volume adjustment.| eTS | +| ArkUI development framework| [AppMarket](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AppMarket)| This sample shows the home page of an application market, which contains the tab bar, banner, featured apps, and featured games.| eTS | +| ArkUI development framework| [Weather](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather)| This sample demonstrates one-time development for multi-device deployment by showing how to develop a weather app and deploy it across different devices. The demo app includes the following: home page, **Manage City** page, **Add City** page, and **Update Time** page.| eTS | +| Multimedia subsystem| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections)| This sample shows the capabilities of online streaming, audio and video playback control, and volume adjustment.| eTS | -For more information, visit [Samples](https://gitee.com/openharmony/app_samples). +For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). ## Resolved Issues diff --git a/en/release-notes/OpenHarmony-v3.2-beta4.md b/en/release-notes/OpenHarmony-v3.2-beta4.md index c92fa7205174bab896b300e5641f368c70918ffd..ffe9ff98386cd4de0a38a793582077354a3f57d8 100644 --- a/en/release-notes/OpenHarmony-v3.2-beta4.md +++ b/en/release-notes/OpenHarmony-v3.2-beta4.md @@ -203,17 +203,16 @@ The following samples written in ArkTS are added. | Subsystem
| Name| Introduction| | -------- | -------- | -------- | -| Common event and notification subsystem| [Event Notification](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/CustomEmitter)| This sample shows the in-process event notification. After a user selects an offering and submits an order, the selected offering is displayed in the order list.| -| Data management subsystem| [Cross-Application Data Sharing](https://gitee.com/openharmony/applications_app_samples/tree/master/data/CrossAppDataShare)| This sample implements cross-application data sharing. It provides contacts (data provider) and contacts assistant (data user). Contacts support functionalities such as adding, deleting, modifying, and querying contacts data. Contacts assistant supports contacts data synchronization and merging of duplicate data.| -| Multimedia subsystem| [Background Music Playback](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/PlayMusicBackground)| This sample implements the request for a continuous task to continue music playback in the background. It is based on the stage model.| -| Resource scheduler subsystem| [Agent-Powered Scheduled Reminder](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/ReminderAgentManager)| This sample uses agent-powered scheduled reminder to create three types of scheduled reminders: alarm clocks, calendar events, and countdown timers. Agent-powered scheduled reminder ensures that the timing and pop-up notification functions will be performed by the system service agent in the background when the application is frozen or exits.| -| File management subsystem| [Storage Space Statistics](https://gitee.com/openharmony/applications_app_samples/tree/master/FileManager/StorageStatistic)| This sample uses the application package management, application space statistics, and volume management modules to implement the viewing of storage space information of the current device, all installed applications, and all available volumes.| -| Window manager| [Screenshot](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Screenshot)| This sample uses the screenshot, window, and display modules to take screenshots, switch the privacy window, and query the privacy window, in sequence.| -| Bundle management framework| [Multi-HAP](https://gitee.com/openharmony/applications_app_samples/tree/master/bundle/MultiHap)| This sample shows the development of multi-HAP. The sample app includes one entry HAP and two feature HAPs. The two feature HAPs provide audio and video playback components, respectively. The two components are also used in the entry component.| -| Ability framework| [Ability Launch Mode](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/AbilityStartMode)| This sample shows how to implement the standard, singleton, and specified ability launch modes in the stage model.| -| Resource management| [Application Theme Switch](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/ApplicationThemeSwitch)| This sample creates the **dark** and **light** folders at the same level as the **base** folder to configure resources related to the dark and light themes. The custom theme file is configured in the **ThemeConst** file to implement multi-theme switching by controlling variables.| - -For more information, visit [Samples](https://gitee.com/openharmony/app_samples). +| Common event and notification subsystem| [Event Notification](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Notification/CustomEmitter)| This sample shows the in-process event notification. After a user selects an offering and submits an order, the selected offering is displayed in the order list.| +| Data management subsystem| [Cross-Application Data Sharing](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/DataManagement/CrossAppDataShare)| This sample implements cross-application data sharing. It provides contacts (data provider) and contacts assistant (data user). Contacts support functionalities such as adding, deleting, modifying, and querying contacts data. Contacts assistant supports contacts data synchronization and merging of duplicate data.| +| Resource scheduler subsystem| [Agent-Powered Scheduled Reminder](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/ReminderAgentManager)| This sample uses agent-powered scheduled reminder to create three types of scheduled reminders: alarm clocks, calendar events, and countdown timers. Agent-powered scheduled reminder ensures that the timing and pop-up notification functions will be performed by the system service agent in the background when the application is frozen or exits.| +| File management subsystem| [Storage Space Statistics](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/DeviceManagement/StorageStatistic)| This sample uses the application package management, application space statistics, and volume management modules to implement the viewing of storage space information of the current device, all installed applications, and all available volumes.| +| Window manager| [Screenshot](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Media/Screenshot)| This sample uses the screenshot, window, and display modules to take screenshots, switch the privacy window, and query the privacy window, in sequence.| +| Bundle management framework| [Multi-HAP](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Project/ApplicationHap/MultiHap)| This sample shows the development of multi-HAP. The sample app includes one entry HAP and two feature HAPs. The two feature HAPs provide audio and video playback components, respectively. The two components are also used in the entry component.| +| Ability framework| [Ability Launch Mode](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/AbilityStartMode)| This sample shows how to implement the standard, singleton, and specified ability launch modes in the stage model.| +| Resource management| [Application Theme Switch](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Project/ResourceAllocation/ApplicationThemeSwitch)| This sample creates the **dark** and **light** folders at the same level as the **base** folder to configure resources related to the dark and light themes. The custom theme file is configured in the **ThemeConst** file to implement multi-theme switching by controlling variables.| + +For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples). diff --git a/en/release-notes/OpenHarmony-v3.2-beta5.md b/en/release-notes/OpenHarmony-v3.2-beta5.md new file mode 100644 index 0000000000000000000000000000000000000000..e7e5e09a3e2e6b31c4f739dcde007bb192fff3a9 --- /dev/null +++ b/en/release-notes/OpenHarmony-v3.2-beta5.md @@ -0,0 +1,214 @@ +# OpenHarmony 3.2 Beta5 + + +## Version Description + +OpenHarmony 3.2 Beta5 provides the following enhancements over OpenHarmony 3.2 Beta4: + +**Enhanced basic capabilities for the standard system** + +The startup performance of the WebView component is optimized. Configuration management and input event support capabilities are enhanced. JSON files can be imported and loaded in modular mode. + +The task pool and the TS2AOT-tool of the host version are provided. The dynamic library of the HAP package can be loaded without being compressed. The compiler runtime supports shared packages in the same application. + +The dynamic shared library can be installed, updated, uninstalled, packed, and unpacked. For an application that is not configured with an entry icon, a default icon is displayed on the home screen. The runtime capability of the HAR shared package can be verified. + +The local database is changed for widgets. Protection against frequent restart is provided for applications. The ServiceExtensionAbility component supports the asynchronous **onConnected** lifecycle. + +Binding and authentication between local accounts and domain accounts are supported. A basic framework is provided for domain account management services. Direct creation of local users is forbidden. + +The capabilities for controlling power indicators and lights are provided. + +The HDI driver display layer supports horizontal mirroring and vertical mirroring. + +**Enhanced application development framework for the standard system** + +The process of compiling the shared package is added to the toolchain. + +ArkUI supports obtaining of resources by resource name. + +The component supports multi-level menus and group menus. + +The process of compiling the HAR package is added. + +The HAP compilation process is adapted so that .d.ets declaration files can be identified during HAP compilation. + +**Enhanced distributed capabilities for the standard system** + +BLE connection parameters can be configured, and the connection process is optimized. + + +## Version Mapping + +**Table 1** Version mapping of software and tools + +| Software/Tool| Version| Remarks| +| -------- | -------- | -------- | +| OpenHarmony | 3.2 Beta5 | NA | +| Public SDK | Ohos_sdk_public 3.2.10.6 (API Version 9 Beta5) | This toolkit is intended for application developers and does not contain system APIs that require system permissions. It is provided as standard in DevEco Studio.| +| (Optional) HUAWEI DevEco Studio| *To be released*| Recommended for developing OpenHarmony applications| +| (Optional) HUAWEI DevEco Device Tool| *To be released*| Recommended for developing OpenHarmony smart devices| + + +## Source Code Acquisition + + +### Prerequisites + +1. Register your account with Gitee. + +2. Register an SSH public key for access to Gitee. + +3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure user information. + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. Run the following commands to install the **repo** tool: + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo # If you do not have the permission, download the tool to another directory and configure it as an environment variable by running the chmod a+x /usr/local/bin/repo command. + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### Acquiring Source Code Using the repo Tool + +**Method 1 (recommended)** + +Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.) + +- Obtain the source code from the version branch. You can obtain the latest source code of the version branch, which includes the code that has been incorporated into the branch up until the time you run the following commands: + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- Obtain the source code from the version tag, which is the same as that released with the version. + ``` + repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +**Method 2** + +Use the **repo** tool to download the source code over HTTPS. + +- Obtain the source code from the version branch. You can obtain the latest source code of the version branch, which includes the code that has been incorporated into the branch up until the time you run the following commands: + ``` + repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony-3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + +- Obtain the source code from the version tag, which is the same as that released with the version. + ``` + repo init -u https://gitee.com/openharmony/manifest -b refs/tags/OpenHarmony-v3.2-Beta5 --no-repo-verify + repo sync -c + repo forall -c 'git lfs pull' + ``` + + +### Acquiring Source Code from Mirrors + +**Table 2** Mirrors for acquiring source code + +| Source Code | Version| Mirror | SHA-256 Checksum | Software Package Size| +| --------------------------------------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -------- | +| Full code base (for mini, small, and standard systems) | 3.2 Beta5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/code-v3.2-Beta5.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/code-v3.2-Beta5.tar.gz.sha256) | 21.3 GB | +| Hi3861 solution (binary) | 3.2 Beta5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/hispark_pegasus.tar.gz.sha256) | 22.9 MB | +| Hi3516 solution-LiteOS (binary)| 3.2 Beta5 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_LiteOS.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_LiteOS.tar.gz.sha256) | 293.6 MB | +| Hi3516 solution-Linux (binary) | 3.2 Beta5 | [Download](hispark_taurus_Linux.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta5/hispark_taurus_Linux.tar.gz.sha256) | 174.3 MB | +| RK3568 standard system solution (binary) | 3.2 Beta5 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/dayu200_standard_arm32_20230201.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/dayu200_standard_arm32_20230201.tar.gz.sha256) | 3.9 GB | +| Public SDK package for the standard system (macOS) | 3.2.10.6 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-mac-public.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-mac-public.tar.gz.sha256) | 674.5 MB | +| Public SDK package for the standard system (macOS-M1) | 3.2.10.6 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/L2-SDK-MAC-M1-PUBLIC.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/L2-SDK-MAC-M1-PUBLIC.tar.gz.sha256)| 634.5 MB | +| Public SDK package for the standard system (Windows\Linux) | 3.2.10.6 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-windows_linux-public.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta5/ohos-sdk-windows_linux-public.tar.gz.sha256) | 1.6 GB | + + + +## **What's New** + +This version has the following updates to OpenHarmony 3.2 Beta4. + +### SDK Updates + +From this version, only the public SDK is released. It can also be downloaded through DevEco Studio. + +To use the full SDK, you must download the source code, build the source code, and switch to the full SDK. For details, see [Guide to Building Full SDK](../application-dev/quick-start/full-sdk-compile-guide.md). + + +### Feature Updates + +**Table 3** New and enhanced features + +| Subsystem| Standard System| Mini and Small Systems| +| -------- | -------- | -------- | +| ArkUI | - Resources can be obtained by resource name.
- The component supports multi-level menus and group menus.
- The compilation capability is enhanced.
The following requirements are involved:
I683Z1 [New function] Adaptation to resource name–based resource retrieval
I68DBH [Basic capability] Providing multi-level menus and group menus
I68DRY [New function] Adding the HAR package compilation process
I68DRY [New function] Adapting to the HAP compilation process so that .d.ets declaration files can be identified during HAP compilation
I68DRY [New function] Adding the shared package compilation process to the toolchain| NA | +| Web subsystem| The WebView component supports the following new capabilities:
- Web pages can be loaded and displayed, including historical records, forward, and backward. Events can be reported during page loading. The webmessage supports the arraybuffer type. The fetch supports custom protocols.
- The following capabilities are added to configuration management: scroll bar and scroll position, network loading interception configuration, determining whether a page contains images, obtaining the source URL, request method, and website icon, and font management.
- The web context menu can obtain the selected content on the page.
- Interaction normalization is available for input events, and original input events are supported.
- Several W3C interfaces are supported.
The following requirements are involved:
I6BFPR [Function enhancement] [WebView component] Web page loading and display (supporting historical records and forward and backward list management)
I6BFRC [Function enhancement] [WebView component] W3C interface support (HTML-partial test cases)
I6BFS6 [Function enhancement] [WebView component] W3C interface support (CSS-partial test cases)
I6BFSK [Function enhancement] [WebView component] Web page loading and display (1. arraybuffer type support by webmessage)
I6BFTS [Function enhancement] [WebView component] W3C interface support (1. appmanifest)
I6BFUD [Function enhancement] [WebView component] Web page loading and display (1. custom protocols for fetch)
I6BFUM [Function enhancement] [WebView component] Status callback for web pages (1. page loading events)
I6BFV4 [Function enhancement] [WebView component] WebView configuration management (1. scroll bar and scroll position)
I6BFXF [Function enhancement] [WebView component] WebView configuration management (1. network loading interception configuration 2. Determining whether a page contains images 3. Obtaining the source URL, request method, and website icon)
I6BFXT [Function enhancement] [WebView component] WebView configuration management (1. font management)
I6BFY9 [Function enhancement] [WebView component] Input event support (1. interaction normalization)
I6BG4H [Function enhancement] [WebView component] Input event support (1. original input events)
I6BG59 [Function enhancement] [WebView component] Selecting and copying content on web pages (1. obtaining selected content from the web context menu)| NA | +| Security| - Mini system devices support authentication session cancellation.
- HUKS supports RSA signature enhancement.
The following requirements are involved:
I65VLX [Function enhancement] Authentication session cancellation for mini system devices
I611S5 [New specifications] RSA signature enhancement by HUKS| NA | +| Bundle management framework| - Implicit query is enhanced.
- Creation of a TS code optimization directory is supported.
- **bundleName** in **provision** can be verified during signature verification.
- A default icon is displayed on the home screen for an application for which no entry icon is configured.
- The following basic capabilities are added: packaging, unpacking, installing, updating, and uninstalling the dynamic shared library, and verifying the runtime capability of the HAR shared package.
The following requirements are involved:
I6BD9G [Basic capability] Enhancement to implicit query
I6BD9E [Basic capability] Creating a TS code optimization directory
I6BD99 [Basic capability] Verifying **bundleName** in **provision** during signature verification
I6BD8Z [Basic capability] Displaying a default icon on the home screen for an application for which no entry icon is configured
I6BD92 [New function] Packaging and unpacking the dynamic shared library
I6BD96 [New specifications] Installing, updating, and uninstalling the dynamic shared library
I6BD9I Verifying the runtime capability of the HAR shared package| NA | +| Building and runtime| - **taskpool**, a TS/JS task pool concurrency API, is added.
- The TSAOT function on the host side is supported. The TSC supports the export and import of .d.ts and .d.ets declaration files.
The following requirements are involved:
I65G6O [Basic capability] [Closed-source HAR package] Export and import of .d.ts and .d.ets declaration files
I64QIR [taskpool] TS/JS task pool concurrency APIs
I65HID [Function enhancement] TS2AOT-tool of the host version| NA | +| Pan-sensor service| The control of a single logical light is supported.
The following requirements are involved:
I63TFA [New specifications] Single logical light control| NA | +| Media| The APIs for playing and recording audio and video are reconstructed.
The following requirements are involved:
I63GTA [Reconstruction] Integration of audio and video playback APIs
I66VL5 [Reconstruction] Integration of audio and video recording APIs| NA | +| Startup subsystem| Symbols are hidden for the NAPI module, and the dependency on the static library module is changed to the dependency on the dynamic library module.
The following requirements are involved:
I698CV [Symbol optimization] Symbols hidden for the NAPI module; changing from the dependency on the static library module to the dependency on the dynamic library module| NA | +| Common event and notification subsystem| The local notification database is changed.
The following requirement is involved:
I67E9A [Basic capability] Local notification database switchover| NA | +| Graphics subsystem| Camera preview image is supported.
The following requirements are involved:
I6BDOH [RenderService] [New function] Camera preview image| NA | +| Location service| The network location framework is supported.
The following requirements are involved:
I5X4S9 [New feature] Network location framework| NA | +| File storage| - Unified URI processing is added for application files.
- Temporary authorization and unified open entry are added for user data.
The following requirements are involved:
I687C8 [New capability] Unified URI processing for application files
I64U8W [Basic capability] Temporary authorization and unified open entry for user data| NA | +| Ability framework| - The restart of resident processes is optimized.
- The widget database can be switched.
- The asynchronous **onConnected** lifecycle is provided.
The following requirements are involved:
I65M3F [Basic capability] ShellCommand execution control
I65V83 [Basic capability] ServiceExtensionAbility support for asynchronous **onConnected** lifecycle
I61H21 [Basic capability] Change of the local widget database
I63UJ5 [Ability] [ability_runtime] Exception handling in API version 8 and earlier versions
I6BDCW [Basic capability] Forbidden to load code in the **data** directory during application loading
I6BDDU [Basic capability] Default ability launch mode of the FA model: Standard
I6BDE2 [Basic capability] Protection against frequent restart of resident applications| NA | + + +### Chip and Development Board Adaptation + +For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md). + + +### Samples + +**Table 4** New samples + +| Subsystem| Name| Introduction| Programming Language| +| -------- | -------- | -------- | -------- | +| Web subsystem| [JS Injection and Execution](https://gitee.com/openharmony/applications_app_samples/tree/master/Web/RunJsInWeb)| This sample is based on HTML5 games. It uses the ArkUI component **\