diff --git a/CODEOWNERS b/CODEOWNERS
index 9649864bf815709ace883f9d330f96e4cec7ee59..b3a89aecb5c1bf1907db23aabcb7d61adecc8ab3 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -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
@@ -435,6 +435,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong
zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @gaoyong @zengyawen @niejiteng @jumozhanjiang
zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @Buda-Liu @ningningW @budda-wang @tomatodevboy
+zh-cn/application-dev/reference/apis/js-apis-system-date-time.md @feng-aiwen @ningningW @illybyy @murphy1984
zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawen @handyohos @nan-xiansen
zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw
@@ -520,16 +521,21 @@ zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @shuaytao @RayShih
zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @shuaytao @RayShih @wangzhen107 @inter515
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-configPolicy.md @liuzuming @ningningW @yangqing3
+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
zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
-zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @Buda-Liu @ningningW @budda-wang @yangqing3
-zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @Buda-Liu @ningningW @budda-wang @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-accountManager.md @liuzuming @ningningW @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-adminManager.md @liuzuming @ningningW @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @liuzuming @ningningW @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceControl.md @liuzuming @ningningW @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @liuzuming @ningningW @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-networkManager.md @liuzuming @ningningW @yangqing3
+zh-cn/application-dev/reference/apis/js-apis-enterprise-wifiManager.md @liuzuming @ningningW @yangqing3
zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @shuaytao @RayShih @wangzhen107 @inter515
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..b7ffad31601a940e3025dc7c01a45bb1a8202d42 100644
--- a/en/application-dev/application-models/Readme-EN.md
+++ b/en/application-dev/application-models/Readme-EN.md
@@ -17,8 +17,11 @@
- ExtensionAbility Component
- [ExtensionAbility Component Overview](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md)
- - [DataShareExtensionAbility](datashareextensionability.md)
+ - [DataShareExtensionAbility (System Applications Only)](datashareextensionability.md)
- [FormExtensionAbility (Widget)](widget-development-stage.md)
+ - [StaticSubscriberExtensionAbility](static-subscriber-extension-ability.md)
+ - [AccessibilityExtensionAbility](accessibilityextensionability.md)
+ - [WindowExtensionAbility](windowextensionability.md)
- [AbilityStage Component Container](abilitystage.md)
- [Context](application-context-stage.md)
- Want
@@ -31,8 +34,8 @@
- [Component Startup Rules](component-startup-rules.md)
- Inter-Device Application Component Interaction (Continuation)
- [Continuation Overview](inter-device-interaction-hop-overview.md)
- - [Cross-Device Migration](hop-cross-device-migration.md)
- - [Multi-device Collaboration](hop-multi-device-collaboration.md)
+ - [Cross-Device Migration (System Applications Only)](hop-cross-device-migration.md)
+ - [Multi-device Collaboration (System Applications Only)](hop-multi-device-collaboration.md)
- IPC
- [Process Model](process-model-stage.md)
- Common Events
@@ -62,7 +65,7 @@
- [Creating a PageAbility](create-pageability.md)
- [Starting a Local PageAbility](start-local-pageability.md)
- [Stopping a PageAbility](stop-pageability.md)
- - [Starting a Remote PageAbility](start-remote-pageability.md)
+ - [Starting a Remote PageAbility (System Applications Only)](start-remote-pageability.md)
- [Starting a Specified Page](start-page.md)
- [Window Properties](window-properties.md)
- [Requesting Permissions](request-permissions.md)
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

@@ -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 @@

- The figure below illustrates the holding relationship of contexts.
-
+

- 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/application-model-description.md b/en/application-dev/application-models/application-model-description.md
index de7e3045d79eff2c681291f8d4de55129d361245..0cdfa7323c6ef367a47a44e2c30104d3201ca159 100644
--- a/en/application-dev/application-models/application-model-description.md
+++ b/en/application-dev/application-models/application-model-description.md
@@ -14,7 +14,7 @@ The stage model is designed based on the following considerations, which make it
1. **Designed for complex applications**
- In the stage model, multiple application components share an ArkTS engine (VM running the programming language ArkTS) instance, making it easy for application components to share objects and status while requiring less memory.
-- The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale.
+ - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale.
2. **Native support for [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md) at the application component level**
@@ -48,13 +48,12 @@ In the stage model, multiple application components share the same ArkTS engine
The table below describes their differences in detail.
- **Table 1** Differences between the FA model and stage model
+**Table 1** Differences between the FA model and stage model
| Item| FA model| Stage model|
| -------- | -------- | -------- |
-| **Application component**| 1. Component classification - PageAbility: has the UI and supports user interaction. For details, see [PageAbility Component Overview](pageability-overview.md). - ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md). - DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md). 2. Development mode Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification - UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md). - ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md). 2. Development mode The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.|
-| **Process model**| There are two types of processes: 1. Main process 2. Rendering process For details, see [Process Model (FA Model)](process-model-fa.md). | There are three types of processes: 1. Main process 2. ExtensionAbility process 3. Rendering process For details, see [Process Model (Stage Model)](process-model-stage.md). |
-| **Thread model**| 1. ArkTS engine instance creation A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance. 2. Thread model Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance. 3. Intra-process object sharing: not supported. For details, see [Thread Model (FA Model)](thread-model-fa.md). | 1. ArkTS engine instance creation A process can run multiple application component instances, and all application component instances share one ArkTS engine instance. 2. Thread model The ArkTS engine instance is created on the main thread. 3. Intra-process object sharing: supported. For details, see [Thread Model (Stage Model)](thread-model-stage.md). |
+| **Application component**| 1. Component classification  - PageAbility: has the UI and supports user interaction For details, see [PageAbility Component Overview](pageability-overview.md). - ServiceAbility: provides background services and has no UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md). - DataAbility: provides the data sharing capability and has no UI. For details, see [DataAbility Component Overview](dataability-overview.md). 2. Development mode Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion. | 1. Component classification  - UIAbility: has the UI and supports user interaction. For details, see [UIAbility Component Overview](uiability-overview.md). - ExtensionAbility: provides extension capabilities (such as widget and input methods) for specific scenarios. For details, see [ExtensionAbility Component Overview](extensionability-overview.md). 2. Development mode The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion. |
+| **Process model**| There are two types of processes: 1. Main process 2. Rendering process For details, see [Process Model (FA Model)](process-model-fa.md).| There are three types of processes: 1. Main process 2. ExtensionAbility process 3. Rendering process For details, see [Process Model (Stage Model)](process-model-stage.md).|
+| **Thread model**| 1. ArkTS engine instance creation A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance. 2. Thread model Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance. 3. Intra-process object sharing: not supported. For details, see [Thread Model (FA Model)](thread-model-fa.md).| 1. ArkTS engine instance creation A process can run multiple application component instances, and all application component instances share one ArkTS engine instance. 2. Thread model The ArkTS engine instance is created on the main thread. 3. Intra-process object sharing: supported. For details, see [Thread Model (Stage Model)](thread-model-stage.md).|
| **Mission management model**| - A mission is created for each PageAbility component instance. - Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions. - PageAbility components do not form a stack structure. For details, see [Mission Management Scenarios](mission-management-overview.md).| - A mission is created for each UIAbility component instance. - Missions are stored persistently until the number of missions exceeds the maximum (customized based on the product configuration) or users delete missions. - UIAbility components do not form a stack structure. For details, see [Mission Management Scenarios](mission-management-overview.md).|
| **Application configuration file**| The **config.json** file is used to describe the application, HAP, and application component information. For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file is used to describe the application information, and the **module.json5** file is used to describe the HAP and application component information. For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).|
-
diff --git a/en/application-dev/application-models/datashareextensionability.md b/en/application-dev/application-models/datashareextensionability.md
index 5b07ba68180fbcc2a51047d37ca9a82addd89cd8..1f968abfa743d7fb917fb7db3e0e41342e41c848 100644
--- a/en/application-dev/application-models/datashareextensionability.md
+++ b/en/application-dev/application-models/datashareextensionability.md
@@ -1,4 +1,4 @@
-# DataShareExtensionAbility
+# DataShareExtensionAbility (System Applications Only)
-DataShareExtensionAbility is available only for system application. It provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md).
+DataShareExtensionAbility provides the data sharing capability. System applications can implement a DataShareExtensionAbility or access an existing DataShareExtensionAbility in the system. Third-party applications can only access an existing DataShareExtensionAbility. For details, see [DataShare Development](../database/database-datashare-guidelines.md).
diff --git a/en/application-dev/application-models/enterprise-extensionAbility.md b/en/application-dev/application-models/enterprise-extensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..514e254f77981977c7c425a4ea2ddbebbcff9ca8
--- /dev/null
+++ b/en/application-dev/application-models/enterprise-extensionAbility.md
@@ -0,0 +1,111 @@
+# EnterpriseAdminExtensionAbility Development
+
+## Introduction
+
+**EnterpriseAdminExtensionAbility** is essential to a mobile device management (MDM) application. When developing an MDM application for an enterprise, you must inherit the **EnterpriseAdminExtensionAbility** class and have the MDM service logic implemented in an **EnterpriseAdminExtensionAbility** instance. The **EnterpriseAdminExtensionAbility** class provides callbacks for the enable, disable, install, and uninstall events of a device administrator application, implementing notification of system administrator status changes.
+
+## Constraints
+
+- ***Function constraints***
+
+ The APIs provided can be used only by device administrator applications.
+
+
+## Scenarios: Listening for the Enable, Disable, Install, and Uninstall Events of a Device Administrator Application
+
+### Overview
+
+**onAdminEnabled**: called when the enterprise administrator or employee deploys an MDM application and enables the DeviceAdmin permission for the application. The MDM application can set the initialization policy in the **onAdminEnabled** callback.
+
+**onAdminDisabled**: called when the system or employee disables the DeviceAdmin permission to notify the enterprise administrator that the device is no longer managed.
+
+**onBundleAdded**: called to notify the enterprise administrator that the specified MDM application is installed on the device. In enterprise application administration settings, after the enterprise administrator subscribes to application installation and uninstallation events, the MDM application reports the events through the callbacks.
+
+**onBundleRemoved**: called to notify the enterprise administrator that the specified MDM application is uninstalled on the device.
+
+### Available APIs
+
+| Class | API | Description |
+| :------------------------------ | ----------------------------------------- | ---------------------------- |
+| EnterpriseAdminExtensionAbility | onAdminDisabled(): void | Called when the device administrator application is enabled.|
+| EnterpriseAdminExtensionAbility | onBundleAdded(bundleName: string): void | Called when the MDM application is installed. |
+| EnterpriseAdminExtensionAbility | onAdminEnabled(): void | Called when the device administrator application is disabled. |
+| EnterpriseAdminExtensionAbility | onBundleRemoved(bundleName: string): void | Called when the MDM application is uninstalled. |
+
+### How to Develop
+
+To implement **EnterpriseAdminExtensionAbility**, enable the device administrator application and create an **ExtensionAbility** instance from the code directory of the device administrator application. The procedure is as follows:
+
+1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named **EnterpriseExtAbility**.
+2. Right-click the **EnterpriseExtAbility** directory and choose **New > TypeScript File** to create a file named **EnterpriseExtAbility.ts**.
+3. Open the **EnterpriseExtAbility.ts** file and import the **EnterpriseAdminExtensionAbility** module. Customize a class that inherits from **EnterpriseAdminExtensionAbility** and add the required callbacks, such as **onAdminEnabled()** and **onAdminDisabled()**, through which the enterprise administrator can receive notification when the device administrator application is enabled or disabled.
+
+ ```ts
+ import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility';
+
+ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
+
+ onAdminEnabled() {
+ console.info("onAdminEnabled");
+ }
+
+ onAdminDisabled() {
+ console.info("onAdminDisabled");
+ }
+
+ onBundleAdded(bundleName: string) {
+ console.info("EnterpriseAdminAbility onBundleAdded bundleName:" + bundleName)
+ }
+
+ onBundleRemoved(bundleName: string) {
+ console.info("EnterpriseAdminAbility onBundleRemoved bundleName" + bundleName)
+ }
+ };
+ ```
+
+4. Register **ServiceExtensionAbility** in the [module.json5](../quick-start/module-configuration-file.md) file of the target module. Among the parameters, set **type** to **enterpriseAdmin** and **srcEntrance** to the code path of the current ExtensionAbility.
+
+ ```ts
+ "extensionAbilities": [
+ {
+ "name": "ohos.samples.enterprise_admin_ext_ability",
+ "type": "enterpriseAdmin",
+ "visible": true,
+ "srcEntrance": "./ets/enterpriseextability/EnterpriseAdminAbility.ts"
+ }
+ ]
+ ```
+
+## Example
+
+Use the **subscribeManagedEvent** and **unsubscribeManagedEvent** APIs in the **@ohos.enterprise.adminManager** module to subscribe to and unsubscribe from the application installation and uninstallation event, respectively. After the subscription is successful, the MDM application notifies the enterprise administrator when it is installed or uninstalled on the device.
+
+```ts
+ @State managedEvents: Array = [0,1]
+ @State subscribeManagedEventMsg: string = ""
+ @State unsubscribeManagedEventMsg: string = ""
+
+ async subscribeManagedEventCallback() {
+ await adminManager.subscribeManagedEvent(this.admin,
+ [adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED,
+ adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED], (error) => {
+ if (error) {
+ this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::errorCode: ' + error.code + ' errorMessage: ' + error.message
+ } else {
+ this.subscribeManagedEventMsg = 'subscribeManagedEvent Callback::success'
+ }
+ })
+ }
+
+ async unsubscribeManagedEventPromise() {
+ await adminManager.unsubscribeManagedEvent(this.admin,
+ [adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_ADDED,
+ adminManager.ManagedEvent.MANAGED_EVENT_BUNDLE_REMOVED]).then(() => {
+ this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::success'
+ }).catch((error) => {
+ this.unsubscribeManagedEventMsg = 'unsubscribeManagedEvent Promise::errorCode: ' + error.code + ' errorMessage: ' + error.message
+ })
+ }
+```
+
+
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
- 
+ 
### 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
-
+
### Matching Rules of uri
diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md
index 8b3197383e17810cfee7c044611cf2286f4a987d..809e4e8f70ed31ad361e18dd8cb7e079ddf93086 100644
--- a/en/application-dev/application-models/extensionability-overview.md
+++ b/en/application-dev/application-models/extensionability-overview.md
@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets.
-- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks.
+- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks.
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
@@ -21,7 +21,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md): ExtensionAbility component of the static_subscriber type, which provides APIs for static broadcast.
-- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows system applications to display UIs of other applications.
+- [WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md): ExtensionAbility component of the window type, which allows a system application to be embedded in and displayed over another application.
- [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.
diff --git a/en/application-dev/application-models/figures/fa-model-component.png b/en/application-dev/application-models/figures/fa-model-component.png
new file mode 100644
index 0000000000000000000000000000000000000000..0c28038326c5475abb3f897c5f7cbe9eb50aec00
Binary files /dev/null and b/en/application-dev/application-models/figures/fa-model-component.png differ
diff --git a/en/application-dev/application-models/figures/mission-chain3.png b/en/application-dev/application-models/figures/mission-chain3.png
index e02c135ad4a90f99bb65bdccd821d29990b9536e..0357874ea633a490da800ef5baa2e70d53ce6a2d 100644
Binary files a/en/application-dev/application-models/figures/mission-chain3.png and b/en/application-dev/application-models/figures/mission-chain3.png differ
diff --git a/en/application-dev/application-models/figures/stage-model-component.png b/en/application-dev/application-models/figures/stage-model-component.png
new file mode 100644
index 0000000000000000000000000000000000000000..6de8c778aff28cc9c7353270ce8ab4ad0c10fb02
Binary files /dev/null and b/en/application-dev/application-models/figures/stage-model-component.png differ
diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md
index 6d30435a819da49855cf9ae818bac419a1c0b614..a482ae26ced4987d0b0c02382ac132c42ea932c0 100644
--- a/en/application-dev/application-models/hop-cross-device-migration.md
+++ b/en/application-dev/application-models/hop-cross-device-migration.md
@@ -1,9 +1,9 @@
-# Cross-Device Migration
+# Cross-Device Migration (System Applications Only)]
## When to Use
-Cross-device migration is available only for system applications. The main task is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities:
+The main task of cross-device migration is to migrate the current task (including the page control status) of an application to the target device so that the task can continue on it. Cross-device migration supports the following functionalities:
- Storage and restoration of custom data
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..49ef26a7a11ca28273a92786eac230f5801d05cd 100644
--- a/en/application-dev/application-models/hop-multi-device-collaboration.md
+++ b/en/application-dev/application-models/hop-multi-device-collaboration.md
@@ -1,9 +1,9 @@
-# Multi-device Collaboration
+# Multi-device Collaboration (System Applications Only)
## When to Use
-Multi-device coordination is available only for system applications. It involves the following scenarios:
+Multi-device coordination involves the following scenarios:
- [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned)
@@ -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 = {
@@ -305,7 +305,7 @@ A system application can connect to a service on another device by calling [conn
## Using Cross-Device Ability Call
-The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction).
+The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call.
@@ -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

-- **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

@@ -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..edccb0b736c9ad81f5ae316e7310b6cc35ae34e0 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.
@@ -17,9 +18,9 @@ Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [
This topic describes how to use ServiceExtensionAbility in the following scenarios:
-- [Implementing a Background Service](#implementing-a-background-service)
+- [Implementing a Background Service (System Applications Only)](#implementing-a-background-service-system-applications-only)
-- [Starting a Background Service](#starting-a-background-service)
+- [Starting a Background Service (System Applications Only)](#starting-a-background-service-system-applications-only)
- [Connecting to a Background Service](#connecting-to-a-background-service)
@@ -32,36 +33,32 @@ This topic describes how to use ServiceExtensionAbility in the following scenari
> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground.
-## Implementing a Background Service
+## Implementing a Background Service (System Applications Only)
-This feature applies only to system applications. [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility.
+[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md) provides the callbacks **onCreate()**, **onRequest()**, **onConnect()**, **onDisconnect()**, and **onDestory()**. Override them as required. The following figure shows the lifecycle of ServiceExtensionAbility.
**Figure 1** ServiceExtensionAbility lifecycle

- **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**
@@ -167,9 +164,9 @@ To implement a background service, manually create a ServiceExtensionAbility com
```
-## Starting a Background Service
+## Starting a Background Service (System Applications Only)
-This feature applies only to system applications. A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service.
+A system application uses the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) callback is invoked, and the **Want** object passed by the caller is received through the callback. After the background service is started, its lifecycle is independent of that of the client. In other words, even if the client is destroyed, the background service can still run. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) to stop the background service.
> **NOTE**
>
diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md
index 4e998a15d23d298bfdb402bd18ea0db2a9f819eb..7d270a68058448025def436e71ace635b4a1297c 100644
--- a/en/application-dev/application-models/start-remote-pageability.md
+++ b/en/application-dev/application-models/start-remote-pageability.md
@@ -1,7 +1,7 @@
-# Starting a Remote PageAbility
+# Starting a Remote PageAbility (System Applications Only)
-This feature applies only to system applications. The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility.
+The **startAbility()** method in the **featureAbility** class is used to start a remote PageAbility.
In addition to **'\@ohos.ability.featureAbility'**, you must import **'\@ohos.distributedHardware.deviceManager'**, which provides account-independent distributed device networking capabilities. Then you can use **getTrustedDeviceListSync** of the **DeviceManager** module to obtain the remote device ID and pass the remote device ID in the **want** parameter for starting the remote PageAbility.
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

@@ -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
- 
+
-- 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..84942ca0d94c3ee8d5f6d2d00fe05b14fefcc8b3 100644
--- a/en/application-dev/application-models/uiability-intra-device-interaction.md
+++ b/en/application-dev/application-models/uiability-intra-device-interaction.md
@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
-- [Using Ability Call to Implement UIAbility Interaction](#using-ability-call-to-implement-uiability-interaction)
+- [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only)
## Starting UIAbility in the Same Application
@@ -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.
-
+

-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;
@@ -416,9 +422,9 @@ In summary, when a UIAbility instance of application A has been created and the
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
-## Using Ability Call to Implement UIAbility Interaction
+## Using Ability Call to Implement UIAbility Interaction (System Applications Only)
-This feature applies only to system applications. Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC.
+Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC.
The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways:
@@ -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

@@ -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/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md
index 14cb5c4652749c97dd6e50c4232b6f65fb6feaab..7e31ab130df2ba9eaf959d1bfb3ddccfb7172480 100644
--- a/en/application-dev/application-models/uiability-overview.md
+++ b/en/application-dev/application-models/uiability-overview.md
@@ -3,9 +3,11 @@
## Overview
-UIAbility has the UI and is mainly used for user interaction.
+UIAbility is a type of application component that provides the UI for user interaction.
-UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. A UIAbility component can implement a functional module through multiple pages. Each UIAbility component instance corresponds to a mission in **Recents**.
+UIAbility is the basic unit scheduled by the system and provides a window for applications to draw UIs. An application can contain one or more UIAbility components. For example, for a payment application, you can use two UIAbility components to carry the entry and payment functionalities. You are advised to use one UIAbility component to carry the same functional module, with multiple pages (if necessary).
+
+Each UIAbility component instance is displayed as a mission in Recents.
## Privacy Statement Configuration
@@ -32,8 +34,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb
}
}
```
-
-> **NOTE**
->
-> For the ability composition, see [Adding an Ability to a Module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-ability-0000001218280664-V3).
-
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
-
-
+
## 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/application-models/windowextensionability.md b/en/application-dev/application-models/windowextensionability.md
new file mode 100644
index 0000000000000000000000000000000000000000..cf2ce01947412e479d29516601c45aebc2b55b17
--- /dev/null
+++ b/en/application-dev/application-models/windowextensionability.md
@@ -0,0 +1,112 @@
+# WindowExtensionAbility
+
+[WindowExtensionAbility](../reference/apis/js-apis-application-windowExtensionAbility.md) is a type of ExtensionAbility component that allows a system application to be embedded in and displayed over another application.
+
+
+The WindowExtensionAbility component must be used together with the [AbilityComponent](../reference/arkui-ts/ts-container-ability-component.md) to process services of the started application. WindowExtensionAbility is run in connection mode. A system application must use the AbilityComponent to start the WindowExtensionAbility component.
+
+Each ExtensionAbility has its own context. For WindowExtensionAbility,
+the context is [WindowExtensionContext](../reference/apis/js-apis-inner-application-windowExtensionContext.md).
+
+> **NOTE**
+>
+> **WindowExtensionAbility** is a system API. To embed a third-party application in another application and display it over the application, switch to the full SDK by following the instructions provided in [Guide to Switching to Full SDK](../../application-dev/quick-start/full-sdk-switch-guide.md).
+>
+
+
+## Setting an Embedded Ability (System Applications Only)
+
+The **WindowExtensionAbility** class provides **onConnect()**, **onDisconnect()**, and **onWindowReady()** lifecycle callbacks, which can be overridden.
+
+- The **onWindowReady()** callback is invoked when a window is created for the ability.
+
+- The **onConnect()** callback is invoked when the AbilityComponent corresponding to the window connects to the ability.
+
+- The **onDisconnect()** callback is invoked when the AbilityComponent disconnects from the ability.
+
+
+**How to Develop**
+
+To implement an embedded application, manually create a WindowExtensionAbility in DevEco Studio as follows:
+
+1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **WindowExtAbility**.
+
+2. Right-click the **WindowExtAbility** directory, and choose **New > TypeScript File** to create a file named **WindowExtAbility.ts**.
+
+3. Open the **WindowExtAbility.ts** file and import the dependency package of **WindowExtensionAbility**. Customize a class that inherits from **WindowExtensionAbility** and implement the **onWindowReady()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks.
+
+ ```ts
+ import Extension from '@ohos.application.WindowExtensionAbility'
+
+ export default class WindowExtAbility extends Extension {
+ onWindowReady(window) {
+ window.loadContent('WindowExtAbility/pages/index1').then(() => {
+ window.getProperties().then((pro) => {
+ console.log("WindowExtension " + JSON.stringify(pro));
+ })
+ window.show();
+ })
+ }
+
+ onConnect(want) {
+ console.info('JSWindowExtension onConnect ' + want.abilityName);
+ }
+
+ onDisconnect(want) {
+ console.info('JSWindowExtension onDisconnect ' + want.abilityName);
+ }
+ }
+ ```
+
+4. Register the WindowExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"window"** and **srcEntrance** to the code path of the ExtensionAbility component.
+
+ ```json
+ {
+ "module": {
+ "extensionAbilities": [
+ {
+ "name": "WindowExtAbility",
+ "srcEntrance": "./ets/WindowExtAbility/WindowExtAbility.ts",
+ "icon": "$media:icon",
+ "description": "WindowExtension",
+ "type": "window",
+ "visible": true,
+ }
+ ],
+ }
+ }
+ ```
+
+
+## Starting an Embedded Ability (System Applications Only)
+
+System applications can load the created WindowExtensionAbility through the AbilityComponent.
+
+**How to Develop**
+
+1. To connect to an embedded application, add the AbilityComponent to the corresponding pages in the DevEco Studio project.
+
+2. Set **bundleName** and **abilityName** in the AbilityComponent.
+
+3. Set the width and height. The sample code is as follows:
+
+```ts
+@Entry
+@Component
+struct Index {
+ @State message: string = 'Hello World'
+
+ build() {
+ Row() {
+ Column() {
+ AbilityComponent({ abilityName: "WindowExtAbility", bundleName: "com.example.WindowExtAbility"})
+ .width(500)
+ .height(500)
+ }
+ .width('100%')
+ }
+ .height('100%')
+ .backgroundColor(0x64BB5c)
+ }
+}
+```
diff --git a/en/application-dev/application-test/arkxtest-guidelines.md b/en/application-dev/application-test/arkxtest-guidelines.md
index bd82cae45fb4c673f014bcc13cfc02beb3853a2e..64edba5e9f4d4ebbd6b7bfbff44c4b01c8a67d4d 100644
--- a/en/application-dev/application-test/arkxtest-guidelines.md
+++ b/en/application-dev/application-test/arkxtest-guidelines.md
@@ -108,7 +108,7 @@ You write a UI test script based on the unit test framework, adding the invoking
In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below:
```js
-import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest'
+import {Driver,ON,Component,MatchPattern} from '@ohos.uitest'
```
Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases.
@@ -131,16 +131,16 @@ export default function abilityTest() {
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
//ui test code
- //init uidriver
- var driver = await UiDriver.create();
+ //init driver
+ var driver = await Driver.create();
await driver.delayMs(1000);
- //find button by text 'Next'
- var button = await driver.findComponent(BY.text('Next'));
+ //find button on text 'Next'
+ var button = await driver.findComponent(ON.text('Next'));
//click button
await button.click();
await driver.delayMs(1000);
//check text
- await driver.assertComponentExist(BY.text('after click'));
+ await driver.assertComponentExist(ON.text('after click'));
await driver.pressBack();
done();
})
@@ -195,14 +195,15 @@ The framework supports multiple test case execution modes, which are triggered b
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
+| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
-| size | Size of the test case to be executed. | small, medium, large | -s size small |
+| size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands**
-> Configure hdc-related environment variables, and then perform the following:
+> Before running commands in the CLI, make sure hdc-related environment variables have been configured.
- Open the CLI.
- Run the **aa test** commands.
diff --git a/en/application-dev/application-test/figures/Execute.PNG b/en/application-dev/application-test/figures/Execute.PNG
index ba96bdfdaf430249f3506153a45c6fe439eda5cc..0260b7983a13851dc1ef8e45928f952eb509a7d8 100644
Binary files a/en/application-dev/application-test/figures/Execute.PNG and b/en/application-dev/application-test/figures/Execute.PNG differ
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-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md
index b72874536b968593cbb7a3c8d5fd865eb1720b35..70c0ee209975ff3322210041e123afbeec3b5e6f 100644
--- a/en/application-dev/database/database-mdds-guidelines.md
+++ b/en/application-dev/database/database-mdds-guidelines.md
@@ -13,7 +13,7 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
-| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KvManager** object for database management. |
+| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** object for database management. |
| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback<void>): void delete(key: string): Promise<void> | Deletes data. |
@@ -117,16 +117,10 @@ The following uses a single KV store as an example to describe the development p
bundleName: 'com.example.datamanagertest',
context:context,
}
- distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
- if (err) {
- console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`);
- return;
- }
- console.log('Created KVManager successfully');
- kvManager = manager;
- });
+ kvManager = distributedKVStore.createKVManager(kvManagerConfig);
+ console.log("Created KVManager successfully");
} catch (e) {
- console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
+ console.error(`Failed to create KVManager. Code is ${e.code}, message is ${e.message}`);
}
```
@@ -150,14 +144,14 @@ The following uses a single KV store as an example to describe the development p
};
kvManager.getKVStore('storeId', options, function (err, store) {
if (err) {
- console.error(`Failed to get KVStore: code is ${err.code},message is ${err.message}`);
+ console.error(`Failed to get KVStore: code is ${err.code}, message is ${err.message}`);
return;
}
console.log('Obtained KVStore successfully');
kvStore = store;
});
} catch (e) {
- console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
+ console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
}
```
@@ -175,7 +169,7 @@ The following uses a single KV store as an example to describe the development p
console.log(`dataChange callback call data: ${data}`);
});
}catch(e){
- console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`);
+ console.error(`An unexpected error occured. Code is ${e.code}, message is ${e.message}`);
}
```
@@ -192,13 +186,13 @@ The following uses a single KV store as an example to describe the development p
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) {
- console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
+ console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`);
return;
}
- console.log('Put data successfully');
+ console.log("Put data successfully");
});
}catch (e) {
- console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
+ console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
}
```
@@ -215,20 +209,20 @@ The following uses a single KV store as an example to describe the development p
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) {
- console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
+ console.error(`Failed to put data. Code is ${err.code}, message is ${err.message}`);
return;
}
- console.log('Put data successfully');
+ console.log("Put data successfully");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) {
if (err != undefined) {
- console.error(`Failed to get data.code is ${err.code},message is ${err.message}`);
+ console.error(`Failed to obtain data. Code is ${err.code}, message is ${err.message}`);
return;
}
console.log(`Obtained data successfully:${data}`);
});
});
}catch (e) {
- console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
+ console.error(`Failed to obtain data. Code is ${e.code}, message is ${e.message}`);
}
```
@@ -262,7 +256,7 @@ The following uses a single KV store as an example to describe the development p
// 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedKVStore.SyncMode.PUSH_ONLY, 1000);
} catch (e) {
- console.error(`An unexpected error occurred. code is ${e.code},message is ${e.message}`);
+ console.error(`An unexpected error occurred. Code is ${e.code}, message is ${e.message}`);
}
}
});
diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md
index e5c9faa1477565541a94076e2fb568e69b2f5cf6..724e273675061c4b6969fb3fcd6f6cbdd984a15f 100644
--- a/en/application-dev/database/database-preference-guidelines.md
+++ b/en/application-dev/database/database-preference-guidelines.md
@@ -114,21 +114,19 @@ You can use the following APIs to delete a **Preferences** instance or data file
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
- let context = null;
let preferences = null;
export default class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
+ onWindowStageCreate(windowStage) {
+ let promise = data_preferences.getPreferences(this.context, 'mystore');
+ promise.then((pref) => {
+ preferences = pref;
+ }).catch((err) => {
+ console.info("Failed to get the preferences.");
+ })
}
}
- let promise = data_preferences.getPreferences(context, 'mystore');
- promise.then((pref) => {
- preferences = pref;
- }).catch((err) => {
- console.info("Failed to get the preferences.");
- })
```
3. Write data.
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..6ce8d1b16951d5fb739d97c102cb8d3be3f628d7 100644
--- a/en/application-dev/device/Readme-EN.md
+++ b/en/application-dev/device/Readme-EN.md
@@ -1,4 +1,4 @@
-# Device
+# Device Management
- USB Service
- [USB Service Overview](usb-overview.md)
@@ -17,3 +17,5 @@
- Update Service
- [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md)
+- Stationary
+ - [Stationary Development](stationary-guidelines.md)
diff --git a/en/application-dev/device/stationary-guidelines.md b/en/application-dev/device/stationary-guidelines.md
new file mode 100644
index 0000000000000000000000000000000000000000..9f6693027a29f48c2c434b842df74beb5209f319
--- /dev/null
+++ b/en/application-dev/device/stationary-guidelines.md
@@ -0,0 +1,84 @@
+# Stationary Development
+
+
+## When to Use
+
+An application can call the **Stationary** module to obtain the device status, for example, whether the device is absolutely or relatively still.
+
+For details about the APIs, see [Stationary](../reference/apis/js-apis-stationary.md).
+
+## Device Status Type Parameters
+
+| Name| Description|
+| -------- | -------- |
+| still | Absolutely still.|
+| relativeStill | Relatively still.|
+
+## Parameters for Subscribing to Device Status events
+
+| Name | Value | Description |
+| ------------------------------ | ---- | ---------------------------------------- |
+| ENTER | 1 | Event indicating entering device status. |
+| EXIT | 2 | Event indicating exiting device status.|
+| ENTER_EXIT | 3 | Event indicating entering and exiting device status.|
+
+## Returned Device Status Parameters
+
+| Name | Value | Description |
+| ------------------------------ | ---- | ---------------------------------------- |
+| ENTER | 1 | Entering device status. |
+| EXIT | 2 | Exiting device status.|
+
+## Available APIs
+
+| Module | Name | Description |
+| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
+| ohos.stationary | on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback<ActivityResponse>): void | Subscribes to the device status. This API uses an asynchronous callback to return the result.|
+| ohos.stationary | once(activity: ActivityType, callback: Callback<ActivityResponse>): void | Obtains the device status. This API uses an asynchronous callback to return the result.|
+| ohos.stationary | off(activity: ActivityType, event: ActivityEvent, callback?: Callback<ActivityResponse>): void | Unsubscribes from the device status. |
+
+## Constraints
+
+The device must support the acceleration sensor.
+
+## How to Develop
+
+1. Subscribe to the event indicating entering the absolute still state, and the event is reported every 1 second.
+
+ ```js
+ import stationary from '@ohos.stationary';
+ var reportLatencyNs = 1000000000;
+ try {
+ stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => {
+ console.log('data='+ JSON.stringify(data));
+ })
+ } catch (err) {
+ console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
+ }
+ ```
+
+2. Obtain the event indicating entering the absolute still state.
+
+ ```js
+ import stationary from '@ohos.stationary';
+ try {
+ stationary.once('still', (data) => {
+ console.log('data='+ JSON.stringify(data));
+ })
+ } catch (err) {
+ console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
+ }
+ ```
+
+3. Unsubscribe from the event indicating entering the absolute still state.
+
+ ```js
+ import stationary from '@ohos.stationary';
+ try {
+ stationary.off('still', stationary.ActivityEvent.ENTER, (data) => {
+ console.log('data='+ JSON.stringify(data));
+ })
+ } catch (err) {
+ console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
+ }
+ ```
diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md
index 667339c3b3dbaa101cfbda8eeacbc8f11c2fd03d..193a5fcaf3e26ccb728d5b2ea3287e8723f958f1 100644
--- a/en/application-dev/dfx/errormanager-guidelines.md
+++ b/en/application-dev/dfx/errormanager-guidelines.md
@@ -39,8 +39,8 @@ When an asynchronous callback is used, the return value can be processed directl
import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.app.ability.errorManager';
-var registerId = -1;
-var callback = {
+let registerId = -1;
+let callback = {
onUnhandledException: function (errMsg) {
console.log(errMsg);
}
@@ -48,13 +48,13 @@ var callback = {
export default class EntryAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] EntryAbility onCreate")
- registerId = errorManager.registerErrorObserver(callback);
+ registerId = errorManager.on("error", callback);
globalThis.abilityWant = want;
}
onDestroy() {
console.log("[Demo] EntryAbility onDestroy")
- errorManager.unregisterErrorObserver(registerId, (result) => {
+ errorManager.off("error", registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message)
});
}
diff --git a/en/application-dev/file-management/filepicker-guidelines.md b/en/application-dev/file-management/filepicker-guidelines.md
index f320f89d82ed0683b0057264430ee090fdd02974..ec813e256d3f4c1b3fe302aaf1653866a837a36a 100644
--- a/en/application-dev/file-management/filepicker-guidelines.md
+++ b/en/application-dev/file-management/filepicker-guidelines.md
@@ -9,11 +9,10 @@ FilePicker provides the following modes:
## Development Guidelines
> **NOTE**
->
> FilePicker supports only the applications developed based on the stage model.
> For details about the stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md).
-You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-ability-context.md##abilitycontextstartabilityforresult-1) with different parameters to start different FilePicker modes.
+You can use [AbilityContext.startAbilityForResult(want, options)](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult-1) with different parameters to start FilePicker in different modes.
You need to use [Want](../reference/apis/js-apis-application-want.md) to specify **bundleName** and **abilityName** to start FilePicker. For details, see the following sample code.
@@ -32,8 +31,7 @@ ArkTS sample code:
// Start FilePicker to select a file.
globalThis.context.startAbilityForResult(
{
- bundleName: "com.ohos.filepicker",
- abilityName: "MainAbility",
+ action: "ohos.want.action.OPEN_FILE",
parameters: {
'startMode': 'choose', //choose or save
}
@@ -44,8 +42,7 @@ globalThis.context.startAbilityForResult(
// Start FilePicker to save a file.
globalThis.context.startAbilityForResult(
{
- bundleName: "com.ohos.filepicker",
- abilityName: "MainAbility",
+ action: "ohos.want.action.CREATE_FILE",
parameters: {
'startMode': 'save', //choose or save
'saveFile': 'test.jpg',
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/Readme-EN.md b/en/application-dev/media/Readme-EN.md
index d65c0d9dbe51f963385afaac0b75deccc6b21d2b..926a2718a48dcefd217e503932f9d9f997d1275e 100755
--- a/en/application-dev/media/Readme-EN.md
+++ b/en/application-dev/media/Readme-EN.md
@@ -1,9 +1,7 @@
# Media
-- Audio
+- Audio and Video
- [Audio Overview](audio-overview.md)
- - [Audio Playback Development](audio-playback.md)
- - [Audio Recording Development](audio-recorder.md)
- [Audio Rendering Development](audio-renderer.md)
- [Audio Stream Management Development](audio-stream-manager.md)
- [Audio Capture Development](audio-capturer.md)
@@ -12,8 +10,10 @@
- [Audio Interruption Mode Development](audio-interruptmode.md)
- [Volume Management Development](audio-volume-manager.md)
- [Audio Routing and Device Management Development](audio-routing-manager.md)
-
-- Video
+ - [AVPlayer Development (Recommended)](avplayer-playback.md)
+ - [AVRecorder Development (Recommended)](avrecorder.md)
+ - [Audio Playback Development](audio-playback.md)
+ - [Audio Recording Development](audio-recorder.md)
- [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md)
diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md
index 4202b8ea4d78e9c38f43fc77bf7ea503712340d8..8371b6248d71f48e9088da849dc36c3edb2be3cf 100644
--- a/en/application-dev/media/audio-capturer.md
+++ b/en/application-dev/media/audio-capturer.md
@@ -72,7 +72,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
}
await audioCapturer.start();
- let state = audioCapturer.state;
+ state = audioCapturer.state;
if (state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
@@ -86,7 +86,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
The following example shows how to write recorded data into a file.
```js
- import fileio from '@ohos.fileio';
+ import fs from '@ohos.file.fs';
let state = audioCapturer.state;
// The read operation can be performed only when the state is STATE_RUNNING.
@@ -96,31 +96,36 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
}
const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
- let fd = fileio.openSync(path, 0o102, 0o777);
- if (fd !== null) {
- console.info('AudioRecLog: file fd created');
- }
- else{
- console.info('AudioRecLog: file fd create : FAILED');
+ let file = fs.openSync(filePath, 0o2);
+ let fd = file.fd;
+ if (file !== null) {
+ console.info('AudioRecLog: file created');
+ } else {
+ console.info('AudioRecLog: file create : FAILED');
return;
}
-
- fd = fileio.openSync(path, 0o2002, 0o666);
+
if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode');
}
let numBuffersToCapture = 150; // Write data for 150 times.
+ let count = 0;
while (numBuffersToCapture) {
+ let bufferSize = await audioCapturer.getBufferSize();
let buffer = await audioCapturer.read(bufferSize, true);
+ let options = {
+ offset: count * this.bufferSize,
+ length: this.bufferSize
+ }
if (typeof(buffer) == undefined) {
console.info('AudioRecLog: read buffer failed');
} else {
- let number = fileio.writeSync(fd, buffer);
+ let number = fs.writeSync(fd, buffer, options);
console.info(`AudioRecLog: data written: ${number}`);
- }
-
+ }
numBuffersToCapture--;
+ count++;
}
```
@@ -189,7 +194,7 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference
let audioTime : number = await audioCapturer.getAudioTime();
// Obtain a proper minimum buffer size.
- let bufferSize : number = await audioCapturer.getBuffersize();
+ let bufferSize : number = await audioCapturer.getBufferSize();
```
7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md
index bbdb993ecdb9a1289a939af43db0e670ec10f98f..1c7953d32b8ecee4c0ff34e82ab8d13947ac9271 100644
--- a/en/application-dev/media/audio-playback.md
+++ b/en/application-dev/media/audio-playback.md
@@ -38,7 +38,7 @@ For details about the **src** types supported by **AudioPlayer**, see the [src a
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
// Print the stream track information.
function printfDescription(obj) {
@@ -112,14 +112,8 @@ async function audioPlayerDemo() {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
```
@@ -128,7 +122,7 @@ async function audioPlayerDemo() {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class AudioDemo {
// Set the player callbacks.
@@ -154,14 +148,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
}
@@ -171,7 +159,7 @@ export class AudioDemo {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class AudioDemo {
// Set the player callbacks.
@@ -202,14 +190,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let nextpath = pathDir + '/02.mp3'
- await fileIO.open(nextpath).then((fdNumber) => {
- nextFdPath = nextFdPath + '' + fdNumber;
- console.info('open fd success fd is' + nextFdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let nextFile = await fs.open(nextpath);
+ nextFdPath = nextFdPath + '' + nextFile.fd;
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
@@ -220,14 +202,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
}
@@ -237,7 +213,7 @@ export class AudioDemo {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class AudioDemo {
// Set the player callbacks.
@@ -259,14 +235,8 @@ export class AudioDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
let path = pathDir + '/01.mp3'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
}
diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md
index 0b5b382d72fec98bfa18c3cfdee7bd61ef713da1..4a39544e7483b68d0bc15b00d643c8403dbded46 100644
--- a/en/application-dev/media/audio-renderer.md
+++ b/en/application-dev/media/audio-renderer.md
@@ -33,31 +33,30 @@ The following figure shows the audio renderer state transitions.
For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
-
-Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
+ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js
- import audio from '@ohos.multimedia.audio';
-
- let audioStreamInfo = {
- samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
- channels: audio.AudioChannel.CHANNEL_1,
- sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
- encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
- }
- let audioRendererInfo = {
- content: audio.ContentType.CONTENT_TYPE_SPEECH,
- usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
- rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
+ import audio from '@ohos.multimedia.audio';
+
+ let audioStreamInfo = {
+ samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
+ channels: audio.AudioChannel.CHANNEL_1,
+ sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
+ encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
+ }
+ let audioRendererInfo = {
+ content: audio.ContentType.CONTENT_TYPE_SPEECH,
+ usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
+ rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
+ }
+ let audioRendererOptions = {
+ streamInfo: audioStreamInfo,
+ rendererInfo: audioRendererInfo
}
- let audioRendererOptions = {
- streamInfo: audioStreamInfo,
- rendererInfo: audioRendererInfo
- }
- let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
- console.log("Create audio renderer success.");
+ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
+ console.log("Create audio renderer success.");
```
2. Use **start()** to start audio rendering.
@@ -90,7 +89,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js
- import fileio from '@ohos.fileio';
+ import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';
async function writeBuffer(buf) {
@@ -109,35 +108,33 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
// Set a proper buffer size for the audio renderer. You can also select a buffer of another size.
const bufferSize = await audioRenderer.getBufferSize();
let dir = globalThis.fileDir; // You must use the sandbox path.
- const path = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav
- console.info(`file path: ${ path}`);
- let ss = fileio.createStreamSync(path, 'r');
- const totalSize = fileio.statSync(path).size; // Size of the file to render.
- let discardHeader = new ArrayBuffer(bufferSize);
- ss.readSync(discardHeader);
- let rlen = 0;
- rlen += bufferSize;
-
- let id = setInterval(() => {
- if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
- ss.closeSync();
- await audioRenderer.stop();
- clearInterval(id);
- }
- if (audioRenderer.state == audio.AudioState.STATE_RUNNING) {
- if (rlen >= totalSize) { // The rendering stops if the file finishes reading.
- ss.closeSync();
- await audioRenderer.stop();
- clearInterval(id);
- }
- let buf = new ArrayBuffer(bufferSize);
- rlen += ss.readSync(buf);
- console.info(`Total bytes read from file: ${rlen}`);
- writeBuffer(buf);
- } else {
- console.info('check after next interval');
+ const filePath = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav
+ console.info(`file filePath: ${ filePath}`);
+
+ let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
+ let stat = await fs.stat(filePath); // Music file information.
+ let buf = new ArrayBuffer(bufferSize);
+ let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
+ for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * this.bufferSize,
+ length: this.bufferSize
}
- }, 30); // The timer interval is set based on the audio format. The unit is millisecond.
+ let readsize = await fs.read(file.fd, buf, options)
+ let writeSize = await new Promise((resolve,reject)=>{
+ this.audioRenderer.write(buf,(err,writeSize)=>{
+ if(err){
+ reject(err)
+ }else{
+ resolve(writeSize)
+ }
+ })
+ })
+ }
+
+ fs.close(file)
+ await audioRenderer.stop(); // Stop rendering.
+ await audioRenderer.release(); // Releases the resources.
```
4. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
@@ -192,7 +189,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
}
await audioRenderer.drain();
-
state = audioRenderer.state;
}
```
@@ -209,7 +205,6 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
console.info('Renderer already released');
return;
}
-
await audioRenderer.release();
state = audioRenderer.state;
@@ -242,7 +237,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let audioTime : number = await audioRenderer.getAudioTime();
// Obtain a proper minimum buffer size.
- let bufferSize : number = await audioRenderer.getBuffersize();
+ let bufferSize : number = await audioRenderer.getBufferSize();
// Obtain the audio renderer rate.
let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate();
@@ -424,35 +419,31 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
let dir = globalThis.fileDir; // You must use the sandbox path.
const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav
console.info(`audioRender1 file path: ${ path1}`);
- let ss1 = await fileio.createStream(path1,'r');
- const totalSize1 = fileio.statSync(path1).size; // Size of the file to render.
- console.info(`totalSize1 -------: ${totalSize1}`);
- let discardHeader = new ArrayBuffer(bufferSize);
- ss1.readSync(discardHeader);
- let rlen = 0;
- rlen += bufferSize;
-
+ let file1 = fs.openSync(path1, fs.OpenMode.READ_ONLY);
+ let stat = await fs.stat(path1); // Music file information.
+ let buf = new ArrayBuffer(bufferSize);
+ let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
+
// 1.7 Render the original audio data in the buffer by using audioRender.
- let id = setInterval(async () => {
- if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
- ss1.closeSync();
- audioRenderer1.stop();
- clearInterval(id);
+ for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * this.bufferSize,
+ length: this.bufferSize
}
- if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) {
- if (rlen >= totalSize1) { // The rendering stops if the file finishes reading.
- ss1.closeSync();
- await audioRenderer1.stop();
- clearInterval(id);
- }
- let buf = new ArrayBuffer(bufferSize);
- rlen += ss1.readSync(buf);
- console.info(`Total bytes read from file: ${rlen}`);
- await writeBuffer(buf, that.audioRenderer1);
- } else {
- console.info('check after next interval');
- }
- }, 30); // The timer interval is set based on the audio format. The unit is millisecond.
+ let readsize = await fs.read(file.fd, buf, options)
+ let writeSize = await new Promise((resolve,reject)=>{
+ this.audioRenderer1.write(buf,(err,writeSize)=>{
+ if(err){
+ reject(err)
+ }else{
+ resolve(writeSize)
+ }
+ })
+ })
+ }
+ fs.close(file1)
+ await audioRenderer1.stop(); // Stop rendering.
+ await audioRenderer1.release(); Releases the resources.
}
async runningAudioRender2(){
@@ -499,36 +490,32 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th
// 2.6 Read the original audio data file.
let dir = globalThis.fileDir; // You must use the sandbox path.
const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav
- console.error(`audioRender1 file path: ${ path2}`);
- let ss2 = await fileio.createStream(path2,'r');
- const totalSize2 = fileio.statSync(path2).size; // Size of the file to render.
- console.error(`totalSize2 -------: ${totalSize2}`);
- let discardHeader2 = new ArrayBuffer(bufferSize);
- ss2.readSync(discardHeader2);
- let rlen = 0;
- rlen += bufferSize;
-
+ console.info(`audioRender2 file path: ${ path2}`);
+ let file2 = fs.openSync(path2, fs.OpenMode.READ_ONLY);
+ let stat = await fs.stat(path2); // Music file information.
+ let buf = new ArrayBuffer(bufferSize);
+ let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
+
// 2.7 Render the original audio data in the buffer by using audioRender.
- let id = setInterval(async () => {
- if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
- ss2.closeSync();
- that.audioRenderer2.stop();
- clearInterval(id);
- }
- if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) {
- if (rlen >= totalSize2) { // The rendering stops if the file finishes reading.
- ss2.closeSync();
- await audioRenderer2.stop();
- clearInterval(id);
- }
- let buf = new ArrayBuffer(bufferSize);
- rlen += ss2.readSync(buf);
- console.info(`Total bytes read from file: ${rlen}`);
- await writeBuffer(buf, that.audioRenderer2);
- } else {
- console.info('check after next interval');
+ for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * this.bufferSize,
+ length: this.bufferSize
}
- }, 30); // The timer interval is set based on the audio format. The unit is millisecond.
+ let readsize = await fs.read(file.fd, buf, options)
+ let writeSize = await new Promise((resolve,reject)=>{
+ this.audioRenderer2.write(buf,(err,writeSize)=>{
+ if(err){
+ reject(err)
+ }else{
+ resolve(writeSize)
+ }
+ })
+ })
+ }
+ fs.close(file2)
+ await audioRenderer2.stop(); // Stop rendering.
+ await audioRenderer2.release(); // Releases the resources.
}
async writeBuffer(buf, audioRender) {
diff --git a/en/application-dev/media/avplayer-playback.md b/en/application-dev/media/avplayer-playback.md
index 270081373fb500877ca4352366982b66f72bc09a..324dd43e6f73d46e5f0d264ae81ba36802ee6021 100644
--- a/en/application-dev/media/avplayer-playback.md
+++ b/en/application-dev/media/avplayer-playback.md
@@ -104,7 +104,7 @@ The full playback process includes creating an instance, setting resources, sett
```js
import media from '@ohos.multimedia.media'
import audio from '@ohos.multimedia.audio';
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo {
@@ -223,14 +223,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber
- console.info('open fd success fd is' + fdPath)
- }, (err) => {
- console.info('open fd failed err is' + err)
- }).catch((err) => {
- console.info('open fd failed err is' + err)
- });
+ let file = await fs.open(path)
+ fdPath = fdPath + '' + file.fd
this.avPlayer.url = fdPath
}
}
@@ -240,7 +234,7 @@ export class AVPlayerDemo {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo {
@@ -280,7 +274,7 @@ export class AVPlayerDemo {
break;
case 'stopped': // This state is reported upon a successful callback of stop().
console.info(TAG + 'state stopped called')
- this.avPlayer.reset() // Call reset() to initialize the AVPlayer state.
+ this.avPlayer.release() // Call reset() to initialize the AVPlayer state.
break;
case 'released':
console.info(TAG + 'state released called')
@@ -302,24 +296,18 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber
- console.info('open fd success fd is' + fdPath)
- }, (err) => {
- console.info('open fd failed err is' + err)
- }).catch((err) => {
- console.info('open fd failed err is' + err)
- });
+ let file = await fs.open(path)
+ fdPath = fdPath + '' + file.fd
this.avPlayer.url = fdPath
}
}
```
-### Switching to the Next Video Clip
+### Looping a Song
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo {
@@ -362,7 +350,7 @@ export class AVPlayerDemo {
break;
case 'stopped': // This state is reported upon a successful callback of stop().
console.info(TAG + 'state stopped called')
- this.avPlayer.reset() // Call reset() to initialize the AVPlayer state.
+ this.avPlayer.release() // Call reset() to initialize the AVPlayer state.
break;
case 'released':
console.info(TAG + 'state released called')
@@ -393,23 +381,17 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber
- console.info('open fd success fd is' + fdPath)
- }, (err) => {
- console.info('open fd failed err is' + err)
- }).catch((err) => {
- console.info('open fd failed err is' + err)
- });
+ let file = await fs.open(path)
+ fdPath = fdPath + '' + file.fd
this.avPlayer.url = fdPath
}
}
```
-### Looping a Song
+### Switching to the Next Video Clip
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
const TAG = 'AVPlayerDemo:'
export class AVPlayerDemo {
@@ -422,14 +404,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_MP3.mp4'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber
- console.info('open fd success fd is' + fdPath)
- }, (err) => {
- console.info('open fd failed err is' + err)
- }).catch((err) => {
- console.info('open fd failed err is' + err)
- });
+ let file = await fs.open(path)
+ fdPath = fdPath + '' + file.fd
this.avPlayer.url = fdPath // The initialized state is reported again.
}
@@ -493,14 +469,8 @@ export class AVPlayerDemo {
let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
let path = pathDir + '/H264_AAC.mp4'
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber
- console.info('open fd success fd is' + fdPath)
- }, (err) => {
- console.info('open fd failed err is' + err)
- }).catch((err) => {
- console.info('open fd failed err is' + err)
- });
+ let file = await fs.open(path)
+ fdPath = fdPath + '' + file.fd
this.avPlayer.url = fdPath
}
}
diff --git a/en/application-dev/media/avrecorder.md b/en/application-dev/media/avrecorder.md
index b897c68a657f2891800e2f4d67fc60a1aec8eacf..9214df032d7d060cabe9900e8a0d5ab6e7aa12f9 100644
--- a/en/application-dev/media/avrecorder.md
+++ b/en/application-dev/media/avrecorder.md
@@ -69,14 +69,14 @@ export class AVRecorderDemo {
let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
await this.getFd('01.mp4');
- // Configure the parameters related to audio and video recording.
+ // Configure the parameters related to audio and video recording based on those supported by the hardware device.
let avProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : media.CodecMimeType.AUDIO_AAC,
audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4,
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640,
videoFrameHeight : 480,
@@ -365,10 +365,10 @@ export class VideoRecorderDemo {
let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
await this.getFd('01.mp4');
- // Configure the parameters related to video recording.
+ // Configure the parameters related to pure video recording based on those supported by the hardware device.
let videoProfile = {
fileFormat : media.ContainerFormatType.CFT_MPEG_4,
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640,
videoFrameHeight : 480,
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/media/video-playback.md b/en/application-dev/media/video-playback.md
index b324f19b3cf0f3621bd74809c4f1a2d0b57d0abd..d4c895b452aa31b28690bd96bd9ef0fac64c4eb4 100644
--- a/en/application-dev/media/video-playback.md
+++ b/en/application-dev/media/video-playback.md
@@ -51,7 +51,7 @@ For details about how to create an XComponent, see [XComponent](../reference/ark
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure.
failureCallback(error) {
@@ -82,14 +82,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
// Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
@@ -180,7 +174,7 @@ export class VideoPlayerDemo {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure.
failureCallback(error) {
@@ -211,14 +205,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
// Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
@@ -267,7 +255,7 @@ export class VideoPlayerDemo {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure.
failureCallback(error) {
@@ -299,14 +287,8 @@ export class VideoPlayerDemo {
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
let nextPath = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/MP4_AAC.mp4';
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
// Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
@@ -341,14 +323,8 @@ export class VideoPlayerDemo {
// Obtain the next video FD address.
fdPath = 'fd://'
- await fileIO.open(nextPath).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let nextFile = await fs.open(nextPath);
+ fdPath = fdPath + '' + nextFile.fd;
// Set the second video playback source.
videoPlayer.url = fdPath;
@@ -378,7 +354,7 @@ export class VideoPlayerDemo {
```js
import media from '@ohos.multimedia.media'
-import fileIO from '@ohos.fileio'
+import fs from '@ohos.file.fs'
export class VideoPlayerDemo {
// Report an error in the case of a function invocation failure.
failureCallback(error) {
@@ -409,14 +385,8 @@ export class VideoPlayerDemo {
let fdPath = 'fd://'
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile" command.
let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.video.videoplayer/ohos.acts.multimedia.video.videoplayer/assets/entry/resources/rawfile/H264_AAC.mp4';
- await fileIO.open(path).then((fdNumber) => {
- fdPath = fdPath + '' + fdNumber;
- console.info('open fd success fd is' + fdPath);
- }, (err) => {
- console.info('open fd failed err is' + err);
- }).catch((err) => {
- console.info('open fd failed err is' + err);
- });
+ let file = await fs.open(path);
+ fdPath = fdPath + '' + file.fd;
// Call createVideoPlayer to create a VideoPlayer instance.
await media.createVideoPlayer().then((video) => {
if (typeof (video) != 'undefined') {
diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md
index bef55899bcb51359a6b6d68ef6d7894d70e435ae..fd9de91b4bae0591e2a5dc4869455bdd4055943e 100644
--- a/en/application-dev/media/video-recorder.md
+++ b/en/application-dev/media/video-recorder.md
@@ -76,14 +76,14 @@ export class VideoRecorderDemo {
let surfaceID = null; // Used to save the surface ID returned by getInputSurface.
// Obtain the FD address of the video to be recorded.
await this.getFd('01.mp4');
- // Recording-related parameter settings
+ // Configure the parameters related to video recording based on those supported by the hardware device.
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
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/quick-start/app-structure.md b/en/application-dev/quick-start/app-structure.md
index 78d727f2df95b3bdacc025f4159e88b47abf804e..0a35eefb6bb65070878beddb90715f033e8007d8 100644
--- a/en/application-dev/quick-start/app-structure.md
+++ b/en/application-dev/quick-start/app-structure.md
@@ -13,6 +13,7 @@ The **app** tag contains application-wide configuration. The internal structure
| apiVersion | OpenHarmony API version on which the application depends.| Object| Yes (initial value: left empty)|
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
+| 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**)|
## Internal Structure of the version Atttribute
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/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md
index 260d0cab1f9aa5b9365848e58bf070e1a70b4924..67361fccfd749495e2f5825d5ccac6efe1505ed9 100644
--- a/en/application-dev/quick-start/module-configuration-file.md
+++ b/en/application-dev/quick-start/module-configuration-file.md
@@ -22,19 +22,19 @@ This document gives an overview of the **module.json5** configuration file. To s
{
"name": "string",
"value": "string",
- "resource": "$profile:distrofilter_config"
+ "resource": "$profile:distributionFilter_config"
}
],
"abilities": [
{
"name": "EntryAbility",
- "srcEntrance": "./ets/entryability/EntryAbility.ts",
+ "srcEntry": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
- "visible": true,
+ "exported": true,
"skills": [
{
"entities": [
@@ -71,9 +71,9 @@ As shown above, the **module.json5** file contains several tags.
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
-| name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String| No|
+| name | Name of the module. The value is a string with a maximum of 31 bytes and must be unique in the entire application. Chinese characters are not allowed.| String| No|
| type | Type of the module. The value can be **entry** or **feature**. - **entry**: main module of the application. - **feature**: dynamic feature module of the application.| String| No|
-| srcEntrance | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)|
+| srcEntry | Code path corresponding to the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)|
| description | Description of the module. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)|
| process | Process name of the current module. The value is a string with a maximum of 31 bytes. If **process** is configured under **HAP**, all UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility components of the application run in the specified process. **NOTE** This tag applies only to system applications and does not take effect for third-party applications.| String| Yes (initial value: value of **bundleName** under **app** in the **app.json5** file)|
| mainElement | Name of the entry UIAbility or ExtensionAbility of the module. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)|
@@ -81,7 +81,6 @@ As shown above, the **module.json5** file contains several tags.
| deliveryWithInstall | Whether the HAP file of the module will be installed when the user installs the application. - **true**: The HAP file will be installed when the user installs the application. - **false**: The HAP file will not be installed when the user installs the application.| Boolean| No|
| installationFree | Whether the module supports the installation-free feature. - **true**: The module supports the installation-free feature and meets installation-free constraints. - **false**: The module does not support the installation-free feature. **NOTE** - If this tag is set to **true** for an entry-type module, it must also be set to **true** for feature-type modules of the same application. - If this tag is set to **false** for an entry-type module, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No|
| virtualMachine | Type of the target virtual machine (VM) where the module runs. It is used for cloud distribution, such as distribution by the application market and distribution center. If the target VM type is ArkTS engine, the value is **ark**+*version number*.| String| Yes (initial value: automatically inserted when DevEco Studio builds the HAP file)|
-| uiSyntax (deprecated)| Syntax type of the component defined by the module syntax. This tag is deprecated since API version 9. - **"hml"**: The component is developed using HML, CSS, or JS. - **"ets"**: The component is developed using ArkTS.| String| Yes (initial value: **"hml"**)|
| [pages](#pages)| Profile that represents information about each page in the current module. The value can contain a maximum of 255 bytes.| String| No in the UIAbility scenario|
| [metadata](#metadata)| Custom metadata of the module. The setting is valid only for the current module, UIAbility, or ExtensionAbility.| Object array| Yes (initial value: left empty)|
| [abilities](#abilities) | UIAbility configuration of the module, which is valid only for the current UIAbility component.| Object| Yes (initial value: left empty)|
@@ -201,24 +200,85 @@ The **metadata** tag represents the custom metadata of the HAP file. The tag val
## abilities
-The **abilities** tag describes the UIAbility configuration of the component, which is valid only for the current UIAbility component. The tag value is an array.
+UIAbility configuration of the module, which is valid only for the current UIAbility component.
+
+**By default, application icons cannot be hidden from the home screen in OpenHarmony.**
+
+The OpenHarmony system imposes a strict rule on the presence of application icons. If no icon is configured in the HAP file of an application, the system uses the icon specified in the **app.json** file as the application icon and displays it on the home screen.
+
+Touching this icon will direct the user to the application details screen in **Settings**.
+
+To hide an application icon from the home screen, you must configure the **AllowAppDesktopIconHide** privilege. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md).
+
+**Setting the application icon to be displayed on the home screen**:
+
+Set **icon**, **label**, and **skills** under **abilities** in the **module.json5** file. In addition, the **skills** configuration must contain **ohos.want.action.home **and **entity.system.home**.
+
+```
+{
+ "module":{
+
+ ...
+
+ "abilities": [{
+ "icon": "$media:icon",
+ "label": "Login",
+ "skills": [{
+ "actions": ["ohos.want.action.home"],
+ "entities": ["entity.system.home"],
+ "uris": []
+ }]
+ }],
+ ...
+
+ }
+}
+```
+
+**Querying an application icon:**
+* The HAP file contains ability configuration.
+ * The application icon is set under **abilities** in the **module.json5** file.
+ * The application does not have the privilege to hide its icon from the home screen.
+ * The returned home screen icon is the icon configured for the ability.
+ * The returned home screen label is the label configured for the ability. If no label is configured, the bundle name is returned.
+ * The returned component name is the component name of the ability.
+ * When the user touches the home screen icon, the home screen of the ability is displayed.
+ * The application has the privilege to hide its icon from the home screen.
+ * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen.
+ * The application icon is not set under **abilities** in the **module.json5** file.
+ * The application does not have the privilege to hide its icon from the home screen.
+ * The returned home screen icon is the icon configured under **app**. (The **icon** parameter in the **app.json** file is mandatory.)
+ * The returned home screen label is the label configured under **app**. (The **label** parameter in the **app.json** file is mandatory.)
+ * The returned component name is the component name displayed on the application details screen (this component is built in the system).
+ * Touching the home screen icon will direct the user to the application details screen.
+ * The application has the privilege to hide its icon from the home screen.
+ * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen.
+* The HAP file does not contain ability configuration.
+ * The application does not have the privilege to hide its icon from the home screen.
+ * The returned home screen icon is the icon configured under **app**. (The **icon** parameter in the **app.json** file is mandatory.)
+ * The returned home screen label is the label configured under **app**. (The **label** parameter in the **app.json** file is mandatory.)
+ * The returned component name is the component name displayed on the application details screen (this component is built in the system).
+ * Touching the home screen icon will direct the user to the application details screen.
+ * The application has the privilege to hide its icon from the home screen.
+ * The information about the application is not returned during home screen information query, and the icon of the application is not displayed on the home screen.
+
**Table 4** abilities
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
-| name | Name of the UIAbility component, which must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String| No|
-| srcEntrance | Code path of the entry UIAbility component. The value is a string with a maximum of 127 bytes.| String| No|
-| [launchType](../application-models/uiability-launch-type.md) | Launch type of the UIAbility component. The options are as follows: - **standard**: A new UIAbility instance is created each time the UIAbility component is started. - **singleton**: A new UIAbility instance is created only when the UIAbility component is started for the first time. - **specified**: You can determine whether to create a new UIAbility instance when the application is running.| String| Yes (initial value: **"singleton"**)|
+| name | Name of the UIAbility component, which must be unique in the entire application. The value is a string with a maximum of 127 bytes. Chinese characters are not allowed.| String| No|
+| srcEntry | Code path of the entry UIAbility component. The value is a string with a maximum of 127 bytes.| String| No|
+| [launchType](../application-models/uiability-launch-type.md) | Launch type of the UIAbility component. The options are as follows: - **multiton**: A new UIAbility instance is created each time the UIAbility component is started. - **singleton**: A new UIAbility instance is created only when the UIAbility component is started for the first time. - **specified**: You can determine whether to create a new UIAbility instance when the application is running.| String| Yes (initial value: **"singleton"**)|
| description | Description of the UIAbility component. The value is a string with a maximum of 255 bytes or a resource index to the description in multiple languages.| String| Yes (initial value: left empty)|
-| icon | Icon of the UIAbility component. The value is an icon resource index. If **UIAbility** is set to **MainElement**, this attribute is mandatory. | String| Yes (initial value: left empty) |
+| icon | Icon of the UIAbility component. The value is an icon resource index.| String| Yes (initial value: left empty) If **UIAbility** is set to **MainElement**, this attribute is mandatory.|
| label | Name of the UIAbility component displayed to users. The value is a string resource index. If **UIAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No|
| permissions | Permissions required for another application to access the UIAbility component. The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)|
| [metadata](#metadata)| Metadata information of the UIAbility component.| Object array| Yes (initial value: left empty)|
-| visible | Whether the UIAbility component can be called by other applications. - **true**: The UIAbility component can be called by other applications. - **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
+| exported | Whether the UIAbility component can be called by other applications. - **true**: The UIAbility component can be called by other applications. - **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
| continuable | Whether the UIAbility component can be [migrated](../application-models/hop-cross-device-migration.md). - **true**: The UIAbility component can be migrated. - **false**: The UIAbility component cannot be migrated.| Boolean| Yes (initial value: **false**)|
| [skills](#skills) | Feature set of [wants](../application-models/want-overview.md) that can be received by the current UIAbility or ExtensionAbility component. Configuring rule: - For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an OpenHarmony application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) - For HAPs of the feature type, you can configure **skills** attributes with the entry capability for an OpenHarmony application, but not for an OpenHarmony service.| Object array| Yes (initial value: left empty)|
-| backgroundModes | Continuous tasks of the UIAbility component. Continuous tasks are classified into the following types: - **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices. - **audioPlayback**: audio playback service. - **audioRecording**: audio recording service. - **location**: location and navigation services. - **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables). - **multiDeviceConnection**: multi-device interconnection service. - **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features) - **voip**: voice/video call and VoIP services. - **taskKeeping**: computing service.| String array| Yes (initial value: left empty)|
+| backgroundModes | Continuous tasks of the UIAbility component. Continuous tasks are classified into the following types: - **dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices. - **audioPlayback**: audio playback service. - **audioRecording**: audio recording service. - **location**: location and navigation services. - **bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables). - **multiDeviceConnection**: multi-device interconnection service. - **wifiInteraction**: Wi-Fi scanning, connection, and transmission services (as used in the Multi-screen Collaboration and clone features) - **voip**: voice/video call and VoIP services. - **taskKeeping**: computing service.| String array| Yes (initial value: left empty)|
| startWindowIcon | Index to the icon file of the UIAbility component startup page. Example: **$media:icon**. The value is a string with a maximum of 255 bytes.| String| No|
| startWindowBackground | Index to the background color resource file of the UIAbility component startup page. Example: **$color:red**. The value is a string with a maximum of 255 bytes.| String| No|
| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the UIAbility component is destroyed. - **true**: Remove the relevant task from the task list after the UIAbility component is destroyed. - **false**: Do not remove the relevant task from the task list after the UIAbility component is destroyed.| Boolean| Yes (initial value: **false**)|
@@ -227,11 +287,12 @@ The **abilities** tag describes the UIAbility configuration of the component, wh
| priority | Priority of the UIAbility component. This attribute applies only to system applications and does not take effect for third-party applications. In the case of [implicit query](../application-models/explicit-implicit-want-mappings.md), UIAbility components with a higher priority are at the higher place of the returned list. The value is an integer ranging from 0 to 10. The greater the value, the higher the priority.| Number| Yes (initial value: **0**)|
| maxWindowRatio | Maximum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: maximum aspect ratio supported by the platform)|
| minWindowRatio | Minimum aspect ratio supported by the UIAbility component. The minimum value is 0.| Number| Yes (initial value: minimum aspect ratio supported by the platform)|
-| maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: maximum window width supported by the platform)|
-| minWindowWidth | Minimum window width supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: minimum window width supported by the platform)|
-| maxWindowHeight | Maximum window height supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: maximum window height supported by the platform)|
-| minWindowHeight | Minimum window height supported by the UIAbility component, in vp. The minimum value is 0.| Number| Yes (initial value: minimum window height supported by the platform)|
+| maxWindowWidth | Maximum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowWidth** or greater than the maximum window width allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window width supported by the platform)|
+| minWindowWidth | Minimum window width supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the minimum window width allowed by the platform or greater than the value of **maxWindowWidth**. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: minimum window width supported by the platform)|
+| maxWindowHeight | Maximum window height supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the value of **minWindowHeight** or greater than the maximum window height allowed by the platform. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: maximum window height supported by the platform)|
+| minWindowHeight | Minimum window height supported by the UIAbility component, in vp. The minimum value is 0, and the value cannot be less than the minimum window height allowed by the platform or greater than the value of **maxWindowHeight**. For details about the window size, see [Constraints](../windowmanager/window-overview.md#constraints).| Number| Yes (initial value: minimum window height supported by the platform)|
| excludeFromMissions | Whether the UIAbility component is displayed in the recent task list. - **true**: displayed in the recent task list. - **false**: not displayed in the recent task list. **NOTE** This tag applies only to system applications and does not take effect for third-party applications.| Boolean| Yes (initial value: **false**)|
+| recoverable | Whether the application can be recovered to its previous state in case of a detected fault. - **true**: The application can be recovered to its previous state in case of a detected fault. - **false**: The application cannot be recovered to its previous state in case of a detected fault.| Boolean| Yes (initial value: **false**)|
Example of the **abilities** structure:
@@ -240,14 +301,14 @@ Example of the **abilities** structure:
{
"abilities": [{
"name": "EntryAbility",
- "srcEntrance": "./ets/entryability/EntryAbility.ts",
- "launchType":"standard",
+ "srcEntry": "./ets/entryability/EntryAbility.ts",
+ "launchType":"singleton",
"description": "$string:description_main_ability",
"icon": "$media:icon",
"label": "Login",
"permissions": [],
"metadata": [],
- "visible": true,
+ "exported": true,
"continuable": true,
"skills": [{
"actions": ["ohos.want.action.home"],
@@ -335,6 +396,40 @@ Example of the **skills** structure:
}
```
+**Enhance implicit query**
+
+URI-level prefix matching is supported.
+When only **scheme** or a combination of **scheme** and **host** or **scheme**, **host**, and **port** are configured in the configuration file, the configuration is successful if the URI prefixed with the configuration file is passed in.
+
+
+ * The query enhancement involves the following APIs:
+ [@ohos.bundle.bundleManager](../reference/apis/js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)
+ 1. function queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void;
+ 2. function queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void;
+ 3. function queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise>;
+ * Configuration requirements
+ abilities -> skills -> uris object
+ Configuration 1: only **scheme = 'http'**
+ Configuration 2: only **(scheme = 'http' ) + ( host = 'example.com')**
+ Configuration 3: only **(scheme = 'http' ) + ( host = 'example.com' ) + ( port = '8080')**
+ * Prefix match
+ If the value of **uri** under [want](../application-models/want-overview.md) is obtained by calling the **queryAbilityInfo** API:
+ 1. uri = 'https://': No matches
+ 2. uri = 'http://': Matches configuration 1
+ 3. uri = 'https://example.com': No matches
+ 4. uri = 'https://exa.com': No matches
+ 5. uri = 'http://exa.com': Matches configuration 1
+ 6. uri = 'http://example.com': Matches configuration 1 and configuration 2
+ 7. uri = 'https://example.com:8080': No matches
+ 8. uri = 'http://exampleaa.com:8080': Matches configuration 1
+ 9. uri = 'http://example.com:9180': Matches configuration 1 and configuration 2
+ 10. uri = 'http://example.com:8080': Matches configuration 1, configuration 2, and configuration 3
+ 11. uri = 'https://example.com:9180/path': No matches
+ 12. uri = 'http://exampleap.com:8080/path': Matches configuration 1
+ 13. uri = 'http://example.com:9180/path': Matches configuration 1 and configuration 2
+ 14. uri = 'http://example.com:8080/path': Matches configuration 1, configuration 2, and configuration 3
+
+
## extensionAbilities
@@ -345,16 +440,16 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| name | Name of the ExtensionAbility component. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String| No|
-| srcEntrance | Code path corresponding to the ExtensionAbility component. The value is a string with a maximum of 127 bytes.| String| No|
+| srcEntry | Code path corresponding to the ExtensionAbility component. The value is a string with a maximum of 127 bytes.| String| No|
| description | Description of the ExtensionAbility component. The value is a string with a maximum of 255 bytes or a resource index to the description.| String| Yes (initial value: left empty)|
| icon | Icon of the ExtensionAbility component. The value is an icon resource index. If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| Yes (initial value: left empty)|
| label | Name of the ExtensionAbility component displayed to users. The value is a string resource index. **NOTE** If **ExtensionAbility** is set to **MainElement** of the current module, this attribute is mandatory and its value must be unique in the application.| String| No|
-| type | Type of the ExtensionAbility component. The options are as follows: - **form**: ExtensionAbility of a widget. - **workScheduler**: ExtensionAbility of a Work Scheduler task. - **inputMethod**: ExtensionAbility of an input method. - **service**: service component running in the background. - **accessibility**: ExtensionAbility of an accessibility feature. - **dataShare**: ExtensionAbility for data sharing. - **fileShare**: ExtensionAbility for file sharing. - **staticSubscriber**: ExtensionAbility for static broadcast. - **wallpaper**: ExtensionAbility of the wallpaper. - **backup**: ExtensionAbility for data backup. - **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**. - **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types. - **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows. **NOTE** The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications. | String| No|
+| type | Type of the ExtensionAbility component. The options are as follows: - **form**: ExtensionAbility of a widget. - **workScheduler**: ExtensionAbility of a Work Scheduler task. - **inputMethod**: ExtensionAbility of an input method. - **service**: service component running in the background. - **accessibility**: ExtensionAbility of an accessibility feature. - **dataShare**: ExtensionAbility for data sharing. - **fileShare**: ExtensionAbility for file sharing. - **staticSubscriber**: ExtensionAbility for static broadcast. - **wallpaper**: ExtensionAbility of the wallpaper. - **backup**: ExtensionAbility for data backup. - **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**. - **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types. - **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows. - **print**: ExtensionAbility for the print framework. **NOTE** The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No|
| permissions | Permissions required for another application to access the ExtensionAbility component. The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)|
| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. **NOTE** This attribute is mandatory when **type** of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)|
-|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component. Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application. **NOTE** The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application, but not for an OpenHarmony service. | Array| Yes (initial value: left empty)|
+|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component. Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application. **NOTE** The **skills** attribute with the entry capability can be configured for the feature-type package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)|
| [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)|
-| visible | Whether the ExtensionAbility component can be called by other applications. - **true**: The ExtensionAbility component can be called by other applications. - **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
+| exported | Whether the ExtensionAbility component can be called by other applications. - **true**: The ExtensionAbility component can be called by other applications. - **false**: The UIAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
Example of the **extensionAbilities** structure:
@@ -364,7 +459,7 @@ Example of the **extensionAbilities** structure:
"extensionAbilities": [
{
"name": "FormName",
- "srcEntrance": "./form/MyForm.ts",
+ "srcEntry": "./form/MyForm.ts",
"icon": "$media:icon",
"label" : "$string:extension_name",
"description": "$string:form_description",
@@ -372,7 +467,7 @@ Example of the **extensionAbilities** structure:
"permissions": ["ohos.abilitydemo.permission.PROVIDER"],
"readPermission": "",
"writePermission": "",
- "visible": true,
+ "exported": true,
"uri":"scheme://authority/path/query",
"skills": [{
"actions": [],
@@ -395,12 +490,16 @@ Example of the **extensionAbilities** structure:
The **requestPermissions** tage represents a set of permissions that the application needs to request from the system for running correctly.
- **Table 8** requestPermissions
+> **NOTE**
+>
+> The permission settings configured in the **requestPermissions** tag apply to the entire application.
+
+**Table 8** requestPermissions
| Name| Description| Data Type| Value Range| Default Value|
| -------- | -------- | -------- | -------- | -------- |
| name | Permission name. This attribute is mandatory.| String| Custom| –|
-| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. **NOTE** If the permission to request is **user_grant**, this attribute is required for the application to be released to the application market, and multi-language adaptation is required. | String| Resource reference of the string type in $string: \*\*\* format| A null value|
+| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. **NOTE** If the permission to request is **user_grant**, this attribute is required for the application to be released to the application market, and multi-language adaptation is required.| String| Resource reference of the string type in $string: \*\*\* format| A null value|
| usedScene | Scene under which the permission is used. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured. **NOTE** This attribute is optional by default. If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional.| **abilities**: string array **when**: string| **abilities**: array of names of UIAbility or ExtensionAbility components **when**: **inuse** or **always**| **abilities**: null **when**: null|
Example of the **requestPermissions** structure:
@@ -473,7 +572,7 @@ The **shortcut** information is identified in **metadata**, where:
"abilities": [
{
"name": "EntryAbility",
- "srcEntrance": "./ets/entryability/EntryAbility.ts",
+ "srcEntry": "./ets/entryability/EntryAbility.ts",
// ...
"skills": [
{
@@ -498,49 +597,42 @@ The **shortcut** information is identified in **metadata**, where:
```
-## distroFilter
+## distributionFilter
-The **distroFilter** tag defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover five factors: API version, screen shape, screen size, screen resolution, and country code. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these five factors. This tag must be configured in the **/resource/profile resource** directory.
+The **distributionFilter** tag defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover five factors: API version, screen shape, screen size, screen resolution, and country code. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these five factors. This tag must be configured in the **/resource/profile resource** directory. Its sub-tags are optional.
- **Table 9** distroFilter
+ **Table 9** distributionFilter
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
-| apiVersion | Supported API versions.| Object array| Yes (initial value: left empty)|
| screenShape | Supported screen shapes.| Object array| Yes (initial value: left empty)|
| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)|
| screenDensity | Pixel density of the screen, in dots per inch (DPI). This attribute is optional. The value options are as follows: - **sdpi**: small-scale DPI. This value is applicable to devices with a DPI range of (0, 120]. - **mdpi**: medium-scale DPI. This value is applicable to devices with a DPI range of (120, 160]. - **ldpi**: large-scale DPI. This value is applicable to devices with a DPI range of (160, 240]. - **xldpi**: extra-large-scale DPI. This value is applicable to devices with a DPI range of (240, 320]. - **xxldpi**: extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (320, 480]. - **xxxldpi**: extra-extra-extra-large-scale DPI. This value is applicable to devices with a DPI range of (480, 640].| Object array| Yes (initial value: left empty)|
| countryCode | Code of the country or region to which the application is to be distributed. The value is subject to the ISO-3166-1 standard. Enumerated definitions of multiple countries and regions are supported.| Object array| Yes (initial value: left empty)|
- **Table 10** apiVersion
-| Name| Description| Data Type| Initial Value Allowed|
-| -------- | -------- | -------- | -------- |
-| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**. - **exclude**: Exclude the matches of the sub-attribute value. - **include**: Include the matches of the sub-attribute value.| String| No|
-| value | API versions, for example, 4, 5, or 6. Example: If an application comes with two versions developed using API version 5 and API version 6 for the same device model, two installation packages of the entry type can be released for the application.| Array| No|
-
- **Table 11** screenShape
+ **Table 10** screenShape
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**. - **exclude**: Exclude the matches of the sub-attribute value. - **include**: Include the matches of the sub-attribute value.| String| No|
| value | Screen shapes. The value can be **circle**, **rect**, or both. Example: Different HAP files can be provided for a smart watch with a circular face and that with a rectangular face.| String array| No|
- **Table 12** screenWindow
+ **Table 11** screenWindow
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**. - **exclude**: Exclude the matches of the sub-attribute value. - **include**: Include the matches of the sub-attribute value.| String| No|
| value | Screen width and height, in pixels. The value an array of supported width and height pairs, each in the "width * height" format, for example, **"454 * 454"**.| String array| No|
- **Table 13** screenDensity
+ **Table 12** screenDensity
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| policy | Rule for the sub-attribute value. Set this attribute to **exclude** or **include**. - **exclude**: Exclude the matches of the sub-attribute value. - **include**: Include the matches of the sub-attribute value.| String| No|
| value | Pixel density of the screen, in DPI.| String array| No|
- **Table 14** countryCode
+ **Table 13** countryCode
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
@@ -552,14 +644,7 @@ Configure the **distro_filter_config.json** file (this file name is customizable
```json
{
- "distroFilter": {
- "apiVersion": {
- "policy": "include",
- "value": [
- 3,
- 4
- ]
- },
+ "distributionFilter": {
"screenShape": {
"policy": "include",
"value": [
@@ -614,7 +699,7 @@ Configure **metadata** in the **module** tag in the **module.json5** file.
The **testRunner** tag represents the supported test runner.
- **Table 15** testRunner
+ **Table 14** testRunner
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
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

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

## 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/resource-categories-and-access.md b/en/application-dev/quick-start/resource-categories-and-access.md
index 56e8209a5c19e353a21b80ff8b34dd51885db310..aa5e53ae90c1794125f5b6ae8a8f7a5115128743 100644
--- a/en/application-dev/quick-start/resource-categories-and-access.md
+++ b/en/application-dev/quick-start/resource-categories-and-access.md
@@ -35,7 +35,7 @@ resources
| Category | base Subdirectory | Qualifiers Subdirectory | rawfile Subdirectory |
| ---- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
-| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced. Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories). Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories). | You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files. However, resource files in the **rawfile** subdirectory will not be matched based on the device status.|
+| Structure| The **base** subdirectory is a default directory. If no qualifiers subdirectories in the **resources** directory of the application match the device status, the resource file in the **base** subdirectory will be automatically referenced. Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You need to create qualifiers subdirectories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Subdirectories](#qualifiers-subdirectories). Resource group subdirectories are located at the second level of subdirectories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Subdirectories](#resource-group-subdirectories).| You can create multiple levels of subdirectories with custom directory names. They can be used to store various resource files. However, resource files in the **rawfile** subdirectory will not be matched based on the device status.|
| Compilation| Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are compiled into binary files, and each resource file is assigned an ID. | Resource files in the subdirectory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. |
| Reference| Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the resource type and resource name. | Resource files in the subdirectory are referenced based on the file path and file name. |
@@ -81,9 +81,9 @@ You can create resource group subdirectories (including element, media, and prof
| Resource Group Subdirectory | Description | Resource File |
| ------- | ---------------------------------------- | ---------------------------------------- |
-| element | Indicates element resources. Each type of data is represented by a JSON file. The options are as follows: - **boolean**: boolean data - **color**: color data - **float**: floating-point data - **intarray**: array of integers - **integer**: integer data - **pattern**: pattern data - **plural**: plural form data - **strarray**: array of strings - **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type: - boolean.json - color.json - float.json - intarray.json - integer.json - pattern.json - plural.json - strarray.json - string.json |
-| media | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. |
-| profile | Indicates a user-defined configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. | The file name can be customized, for example, **test_profile.json**. |
+| element | Indicates element resources. Each type of data is represented by a JSON file. (Only files are supported in this directory.) The options are as follows: - **boolean**: boolean data - **color**: color data - **float**: floating-point data - **intarray**: array of integers - **integer**: integer data - **pattern**: pattern data - **plural**: plural form data - **strarray**: array of strings - **string**: string data| It is recommended that files in the **element** subdirectory be named the same as the following files, each of which can contain only data of the same type: - boolean.json - color.json - float.json - intarray.json - integer.json - pattern.json - plural.json - strarray.json - string.json |
+| media | Indicates media resources, including non-text files such as images, audios, and videos. (Only files are supported in this directory.) | The file name can be customized, for example, **icon.png**. |
+| profile | Indicates a custom configuration file. You can obtain the file content by using the [getProfileByAbility](../reference/apis/js-apis-bundleManager.md#bundlemanagergetprofilebyability) API. (Only files are supported in this directory.) | The file name can be customized, for example, **test_profile.json**. |
| rawfile | Indicates other types of files, which are stored in their raw formats after the application is built as an HAP file. They will not be integrated into the **resources.index** file.| The file name can be customized. |
**Media Resource Types**
@@ -229,7 +229,7 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile(
>
> Resource descriptors accept only strings, such as **'app.type.name'**, and cannot be combined.
>
-> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md) API.
+> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md#getstringvalue9) API.
In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories):
@@ -252,7 +252,6 @@ Text($r('app.string.message_arrive', "five'o clock"))
Text($r('app.plural.eat_apple', 5, 5))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
-}
Image($r('app.media.my_background_image')) // Reference media resources.
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 589fe479fed206ae44c42e7cf1cfc9aacac08e8d..0de7d46e88f8a4d568593616b1bf73bf4c44b95e 100644
--- a/en/application-dev/reference/apis/Readme-EN.md
+++ b/en/application-dev/reference/apis/Readme-EN.md
@@ -19,8 +19,6 @@
- [@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.AbilityLifecycleCallback (AbilityLifecycleCallback)](js-apis-application-abilityLifecycleCallback.md)
- [@ohos.application.EnvironmentCallback (EnvironmentCallback)](js-apis-application-environmentCallback.md)
- FA Model
- [@ohos.ability.ability (Ability)](js-apis-ability-ability.md)
@@ -34,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)
@@ -53,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)
@@ -76,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)
@@ -107,6 +104,7 @@
- [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)
@@ -117,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
@@ -139,13 +139,13 @@
- [abilityInfo](js-apis-bundleManager-abilityInfo.md)
- [applicationInfo](js-apis-bundleManager-applicationInfo.md)
- [bundleInfo](js-apis-bundleManager-bundleInfo.md)
+ - [BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md)
- [dispatchInfo](js-apis-bundleManager-dispatchInfo.md)
- [elementName](js-apis-bundleManager-elementName.md)
- [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)
- [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,6 +185,7 @@
- [@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)
@@ -216,10 +217,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)
@@ -271,7 +273,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)
@@ -279,6 +281,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)
@@ -303,7 +308,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)
@@ -314,10 +319,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)
@@ -364,6 +370,7 @@
- [@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)
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/figures/en-us_image_0000001219864133.PNG b/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG
index 14f81499ff0b1b8ef46257bc35a79e94775cd2ba..54be7ed38fa40349036e18b962ee52deb579a033 100644
Binary files a/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG and b/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG differ
diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md
index 5908fc527c4d6f1c1a3391671a0ac9dcc4b41d6f..0051896a67f1dd2c9e662ed1ac503259ad6a7997 100644
--- a/en/application-dev/reference/apis/js-apis-Bundle.md
+++ b/en/application-dev/reference/apis/js-apis-Bundle.md
@@ -157,7 +157,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => {
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo) instead.
-getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise>
+getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise\\>
Obtains the information of all bundles of the specified user. This API uses a promise to return the result.
@@ -201,7 +201,7 @@ bundle.getAllBundleInfo(bundleFlag, userId)
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo) instead.
-getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void
+getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback\\>): void
Obtains the information of all bundles of the current user. This API uses an asynchronous callback to return the result.
@@ -238,7 +238,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => {
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo) instead.
-getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void
+getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback\\>): void
Obtains the information of all bundles of the specified user. This API uses an asynchronous callback to return the result.
@@ -823,7 +823,7 @@ bundle.getPermissionDef(permissionName).then((data) => {
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead.
-getAllApplicationInfo(bundleFlags: number, userId?: number): Promise>
+getAllApplicationInfo(bundleFlags: number, userId?: number): Promise\\>
Obtains the information about all applications of the specified user. This API uses a promise to return the result.
@@ -865,7 +865,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId)
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead.
-getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void
+getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback\\>): void
Obtains the information about all applications. This API uses an asynchronous callback to return the result.
@@ -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**
@@ -1320,7 +1320,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => {
> This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead.
-queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise>
+queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise\\>
Obtains the ability information based on given Want. This API uses a promise to return the result.
@@ -1371,7 +1371,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId)
> This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead.
-queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void
+queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback\\>): void
Obtains the ability information of the specified user based on given Want. This API uses an asynchronous callback to return the result.
@@ -1416,7 +1416,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => {
> This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead.
-queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void;
+queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback\\>): void;
Obtains the ability information based on given Want. This API uses an asynchronous callback to return the result.
@@ -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-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md
index a22f7b48a977066e085da4b9ddfcdeb24f21463f..33555ada83df3e20766793df3208f250ac612a00 100644
--- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md
+++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md
@@ -16,6 +16,14 @@ When developing an application, you can override the APIs of this module and add
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
```
+## Attributes
+
+**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
+
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| context | [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) | Yes| No| Context of the **WorkSchedulerExtension**. This context is inherited from **ExtensionContext**.|
+
## WorkSchedulerExtensionAbility.onWorkStart
onWorkStart(work: workScheduler.WorkInfo): 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..262899f64ed644007d28d1dce9b53c369a830f12 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,28 @@ 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));
+ (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('startAbility fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('startAbility success, data: ${JSON.stringify(data)}');
+ }
}
);
```
@@ -94,24 +98,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: 'ohos.want.action.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 +149,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 +158,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 +181,28 @@ 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: 'ohos.want.action.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));
+ (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('startAbilityForResult fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('startAbilityForResult success, data: ${JSON.stringify(data)}');
+ }
}
);
```
@@ -200,7 +211,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 +239,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: 'ohos.want.action.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 +290,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: 'ohos.want.action.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))
+ (error) => {
+ console.error('error: ${JSON.stringify(error)}');
}
);
```
@@ -333,35 +347,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: 'ohos.want.action.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=======================>');
});
```
@@ -383,8 +397,12 @@ 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));
+featureAbility.hasWindowFocus((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('hasWindowFocus fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('hasWindowFocus success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -407,7 +425,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)}');
});
```
@@ -429,8 +447,12 @@ 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));
+featureAbility.getWant((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getWant fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getWant success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -453,7 +475,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 +497,13 @@ Obtains the application context.
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext()
-context.getBundleName((err, data) => {
- console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getBundleName((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getBundleName fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getBundleName success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -500,8 +526,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re
```ts
import featureAbility from '@ohos.ability.featureAbility';
featureAbility.terminateSelf(
- (err) => {
- console.info("err: " + JSON.stringify(err))
+ (error) => {
+ console.error('error: ${JSON.stringify(error)}');
}
)
```
@@ -525,7 +551,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 +588,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.error('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 +631,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.error('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 +650,14 @@ var connectId = featureAbility.connectAbility(
onFailed: onFailedCallback,
},
);
-var result = featureAbility.disconnectAbility(connectId,
- (error) => {
- console.log('featureAbilityTest DisConnectJsSameBundleName result errCode : ' + error.code)
- },
-);
+
+featureAbility.disconnectAbility(connectId, (error) => {
+ if (error && error.code !== 0) {
+ console.error('disconnectAbility fail, connectId: ${connectId}, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('disconnectAbility success, connectId: ${connectId}');
+ }
+});
```
## featureAbility.disconnectAbility7+
@@ -657,18 +686,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.error('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 +707,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}');
});
```
@@ -702,8 +731,12 @@ Obtains the window corresponding to this ability. This API uses an asynchronous
**Example**
```ts
-featureAbility.getWindow((err, data) => {
- console.info("getWindow err: " + JSON.stringify(err) + "data: " + typeof(data));
+featureAbility.getWindow((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getWindow fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getWindow success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -725,7 +758,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 +778,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 +799,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
@@ -818,6 +851,6 @@ Enumerates the flags that specify how the Want will be handled.
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. |
-| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.|
+| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for [Want](js-apis-application-want.md) under the [parameter](js-apis-inner-ability-startAbilityParameter.md) object passed to the [startAbility](#featureabilitystartability) API in **FeatureAbility**. It must be used together with **flag_ABILITY_NEW_MISSION**.|
| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on an existing mission stack. |
| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.|
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..1afa116d859733011cd323f6eda58b7dea225d96 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,31 @@ 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: 'ohos.want.action.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)
+ (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('startAbility fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('startAbility success, data: ${JSON.stringify(data)}');
+ }
},
-)
+);
```
## particleAbility.startAbility
@@ -91,25 +95,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: 'ohos.want.action.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 +134,17 @@ 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)
+ (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('terminateSelf fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('terminateSelf success, data: ${JSON.stringify(data)}');
+ }
}
-)
+);
```
## particleAbility.terminateSelf
@@ -156,10 +164,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 +202,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);
```
@@ -226,19 +234,19 @@ import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
-function callback(err, data) {
- if (err) {
- console.error("Operation failed cause: " + JSON.stringify(err));
+function callback(error, data) {
+ if (error && error.code !== 0) {
+ console.error('Operation failed error: ${JSON.stringify(error)}');
} else {
- console.info("Operation succeeded");
+ console.info('Operation succeeded, data: ${data}');
}
}
let wantAgentInfo = {
wants: [
{
- bundleName: "com.example.myapplication",
- abilityName: "EntryAbility"
+ bundleName: 'com.example.myapplication',
+ abilityName: 'EntryAbility'
}
],
operationType: wantAgent.OperationType.START_ABILITY,
@@ -248,8 +256,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 +306,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 +317,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 +330,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)}');
});
});
@@ -349,11 +357,11 @@ Requests to cancel a continuous task from the system. This API uses an asynchron
```ts
import particleAbility from '@ohos.ability.particleAbility';
-function callback(err, data) {
- if (err) {
- console.error("Operation failed cause: " + JSON.stringify(err));
+function callback(error, data) {
+ if (error && error.code !== 0) {
+ console.error('Operation failed error: ${JSON.stringify(error)}');
} else {
- console.info("Operation succeeded");
+ console.info('Operation succeeded, data: ${data}');
}
}
@@ -381,9 +389,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 +421,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.error('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 +449,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.error('particleAbilityTest result errCode: ${error.code}');
});
```
@@ -468,21 +476,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.error('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 +500,7 @@ var connId = particleAbility.connectAbility(
);
particleAbility.disconnectAbility(connId, (err) => {
- console.log("particleAbilityTest disconnectAbility err====>"
- + ("json err=") + JSON.stringify(err));
+ console.error('particleAbilityTest disconnectAbility err: ${JSON.stringify(err)}');
});
```
@@ -519,21 +526,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.error('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 +550,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.error('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 62d38c714940a754e566bbdebadac2e3fcbccec2..027f3a0e0f338e89b0a4783a3367506c09973992 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
@@ -35,8 +35,8 @@ Enumerates the initial ability launch reasons. You can use it together with [onC
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason.|
-| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-ability-context.md#abilitycontextstartability).|
-| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-ability-context.md#abilitycontextstartabilitybycall).|
+| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).|
+| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall).|
| CONTINUATION | 3 | The ability is started by means of cross-device migration.|
| APP_RECOVERY | 4 | The ability is automatically started when the application is restored from a fault.|
@@ -135,7 +135,7 @@ let option = {
this.context.startAbility(want, option).then(()={
console.log('Succeed to start ability.');
}).catch((error)=>{
- console.log('Failed to start ability with error: ${JSON.stringify(error)}');
+ console.error('Failed to start ability with error: ${JSON.stringify(error)}');
});
```
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 fe6bec9f550bef9bdeb6a3c61c8a1c5adc810f10..76614085293fe0065dafea4a2e3a9d0d8559be0f 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
@@ -56,7 +56,7 @@ abilityDelegator.startAbility(want, (err) => {
if (!err || err.code === 0) {
console.log('Success start ability.');
} else {
- console.log('Failed start ability, error: ${JSON.stringify(err)}');
+ console.error('Failed start ability, error: ${JSON.stringify(err)}');
}
});
```
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 df7b07b2d0303bf9310cfdd354d50b1db9239ece..e2ed27300bc211a232eafb878ccc4ca38851ae50 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
@@ -277,7 +277,7 @@ export default class MyFirstAbility extends UIAbility {
globalThis.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
console.log('registerAbilityLifecycleCallback number: ${JSON.stringify(lifecycleId)}');
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
}
}
@@ -293,7 +293,7 @@ export default class MySecondAbility extends UIAbility {
// 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)}');
+ console.error('unregisterAbilityLifecycleCallback fail, error: ${JSON.stringify(error)}');
} else {
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 1752be21e6c0565bf1b8487fa1c447a758827929..3bfd14ef61cbd5995d4d5b8a0e93a08cfbeaaac5 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
@@ -64,7 +64,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.
};
@@ -72,13 +72,13 @@ const config = {
try {
abilityManager.updateConfiguration(config, (err) => {
if (err && err.code !== 0) {
- console.log('updateConfiguration fail, err: ${JSON.stringify(err)}');
+ console.error('updateConfiguration fail, err: ${JSON.stringify(err)}');
} else {
console.log('updateConfiguration success.');
}
- })
+ });
} catch (paramError) {
- console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
+ console.error('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,10 +130,10 @@ try {
abilityManager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success.');
}).catch((err) => {
- console.log('updateConfiguration fail, err: ${JSON.stringify(err)}');
- })
+ console.error('updateConfiguration fail, err: ${JSON.stringify(err)}');
+ });
} catch (paramError) {
- console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
+ console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
}
```
@@ -169,13 +169,13 @@ import abilityManager from '@ohos.app.ability.abilityManager';
try {
abilityManager.getAbilityRunningInfos((err, data) => {
if (err && err.code !== 0) {
- console.log('getAbilityRunningInfos fail, error: ${JSON.stringify(err)}');
+ console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(err)}');
} else {
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.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
}
```
@@ -212,10 +212,10 @@ try {
abilityManager.getAbilityRunningInfos().then((data) => {
console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}');
}).catch((err) => {
- console.log('getAbilityRunningInfos fail, err: ${JSON.stringify(err)}');
+ console.error('getAbilityRunningInfos fail, err: ${JSON.stringify(err)}');
});
} catch (paramError) {
- console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
+ console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
}
```
@@ -254,13 +254,13 @@ let upperLimit = 10;
try {
abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => {
if (err && err.code !== 0) {
- console.log('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}');
+ console.error('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}');
} else {
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.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
}
```
@@ -305,10 +305,10 @@ try {
abilityManager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log('getExtensionRunningInfos success, data: ${JSON.stringify(data)}');
}).catch((err) => {
- console.log('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}');
- })
+ console.error('getExtensionRunningInfos fail, err: ${JSON.stringify(err)}');
+ });
} catch (paramError) {
- console.log('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
+ console.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
}
```
@@ -341,7 +341,7 @@ import abilityManager from '@ohos.app.ability.abilityManager';
abilityManager.getTopAbility((err, data) => {
if (err && err.code !== 0) {
- console.log('getTopAbility fail, err: ${JSON.stringify(err)}');
+ console.error('getTopAbility fail, err: ${JSON.stringify(err)}');
} else {
console.log('getTopAbility success, data: ${JSON.stringify(data)}');
}
@@ -378,6 +378,6 @@ import abilityManager from '@ohos.app.ability.abilityManager';
abilityManager.getTopAbility().then((data) => {
console.log('getTopAbility success, data: ${JSON.stringify(data)}');
}).catch((err) => {
- console.log('getTopAbility fail, err: ${JSON.stringify(err)}');
-})
+ console.error('getTopAbility fail, err: ${JSON.stringify(err)}');
+});
```
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 3943d78d7f01799de177b8297013c7c26b1c6c64..c3d5a93c0f73f2b4e2e06caf8d1f45d9fd637f9f 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
@@ -41,11 +41,11 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest((err, flag) => {
if (err && err.code !== 0) {
- console.log('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}');
+ console.error('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}');
} else {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
}
-})
+});
```
@@ -79,7 +79,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest().then((flag) => {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -114,7 +114,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice().then((data) => {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -147,11 +147,11 @@ import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice((err, data) => {
if (err && err.code !== 0) {
- console.log('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}');
+ console.error('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}');
} else {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
}
-})
+});
```
## appManager.getAppMemorySize
@@ -184,7 +184,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize().then((data) => {
console.log('The size of app memory is: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -217,11 +217,11 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize((err, data) => {
if (err && err.code !== 0) {
- console.log('getAppMemorySize fail, err: ${JSON.stringify(err)}');
+ console.error('getAppMemorySize fail, err: ${JSON.stringify(err)}');
} else {
console.log('The size of app memory is: ${JSON.stringify(data)}');
}
-})
+});
```
## appManager.getRunningProcessInformation
@@ -256,7 +256,7 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation().then((data) => {
console.log('The running process information is: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -291,11 +291,11 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((err, data) => {
if (err && err.code !== 0) {
- console.log('getRunningProcessInformation fail, err: ${JSON.stringify(err)}');
+ console.error('getRunningProcessInformation fail, err: ${JSON.stringify(err)}');
} else {
console.log('The process running information is: ${JSON.stringify(data)}');
}
-})
+});
```
## appManager.on
@@ -352,12 +352,12 @@ let applicationStateObserver = {
onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
-}
+};
try {
const observerId = appManager.on('applicationState', applicationStateObserver);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
- console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
+ console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
```
@@ -416,13 +416,13 @@ let applicationStateObserver = {
onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
-}
+};
let bundleNameList = ['bundleName1', 'bundleName2'];
try {
const observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
- console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
+ console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
```
@@ -478,19 +478,19 @@ let applicationStateObserver = {
onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
-}
+};
let bundleNameList = ['bundleName1', 'bundleName2'];
try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
- console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
+ console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
// 2. Deregister the application state observer.
function unregisterApplicationStateObserverCallback(err) {
if (err && err.code !== 0) {
- console.log('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}');
+ console.error('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('unregisterApplicationStateObserverCallback success.');
}
@@ -498,7 +498,7 @@ function unregisterApplicationStateObserverCallback(err) {
try {
appManager.off('applicationState', observerId, unregisterApplicationStateObserverCallback);
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -559,13 +559,13 @@ let applicationStateObserver = {
onProcessStateChanged(processData) {
console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`);
}
-}
+};
let bundleNameList = ['bundleName1', 'bundleName2'];
try {
observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList);
console.log(`[appManager] observerCode: ${observerId}`);
} catch (paramError) {
- console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `);
+ console.error(`[appManager] error: ${paramError.code}, ${paramError.message} `);
}
// 2. Deregister the application state observer.
@@ -573,10 +573,10 @@ try {
appManager.off('applicationState', observerId).then((data) => {
console.log('unregisterApplicationStateObserver success, data: ${JSON.stringify(data)}');
}).catch((err) => {
- console.log('unregisterApplicationStateObserver fail, err: ${JSON.stringify(err)}');
- })
+ console.error('unregisterApplicationStateObserver fail, err: ${JSON.stringify(err)}');
+ });
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -613,7 +613,7 @@ import appManager from '@ohos.app.ability.appManager';
function getForegroundApplicationsCallback(err, data) {
if (err && err.code !== 0) {
- console.log('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}');
+ console.error('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}');
}
@@ -621,7 +621,7 @@ function getForegroundApplicationsCallback(err, data) {
try {
appManager.getForegroundApplications(getForegroundApplicationsCallback);
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -659,8 +659,8 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getForegroundApplications().then((data) => {
console.log('getForegroundApplications success, data: ${JSON.stringify(data)}');
}).catch((err) => {
- console.log('getForegroundApplications fail, err: ${JSON.stringify(err)}');
-})
+ console.error('getForegroundApplications fail, err: ${JSON.stringify(err)}');
+});
```
## appManager.killProcessWithAccount
@@ -702,7 +702,7 @@ try {
console.log('killProcessWithAccount success');
}).catch((err) => {
console.error('killProcessWithAccount fail, err: ${JSON.stringify(err)}');
- })
+ });
} catch (paramError) {
console.error('error: ${paramError.code}, ${paramError.message}');
}
@@ -746,7 +746,7 @@ let bundleName = 'bundleName';
let accountId = 0;
function killProcessWithAccountCallback(err, data) {
if (err && err.code !== 0) {
- console.log('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}');
+ console.error('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('killProcessWithAccountCallback success.');
}
@@ -789,7 +789,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err && err.code !== 0) {
- console.log('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}');
+ console.error('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('killProcessesByBundleNameCallback success.');
}
@@ -797,7 +797,7 @@ function killProcessesByBundleNameCallback(err, data) {
try {
appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback);
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -843,10 +843,10 @@ try {
appManager.killProcessesByBundleName(bundleName).then((data) => {
console.log('killProcessesByBundleName success.');
}).catch((err) => {
- console.log('killProcessesByBundleName fail, err: ${JSON.stringify(err)}');
- })
+ console.error('killProcessesByBundleName fail, err: ${JSON.stringify(err)}');
+ });
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -885,7 +885,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
if (err && err.code !== 0) {
- console.log('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}');
+ console.error('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('clearUpApplicationDataCallback success.');
}
@@ -893,7 +893,7 @@ function clearUpApplicationDataCallback(err, data) {
try {
appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback);
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -939,10 +939,10 @@ try {
appManager.clearUpApplicationData(bundleName).then((data) => {
console.log('clearUpApplicationData success.');
}).catch((err) => {
- console.log('clearUpApplicationData fail, err: ${JSON.stringify(err)}');
- })
+ console.error('clearUpApplicationData fail, err: ${JSON.stringify(err)}');
+ });
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('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 5a07867e6f5c28213e5cc48b07ef6a0958eb9426..b57ce848be1321026c5f408e21c7d892a1887bf1 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
@@ -105,7 +105,7 @@ let observer = {
try {
errorManager.on('error', observer);
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('error: ${paramError.code}, ${paramError.message}');
}
```
@@ -139,6 +139,6 @@ let observer = {
try {
errorManager.on('error', observer);
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('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..5021fffdc2722182651b84ee215b5ba3e71ee6cf 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.error('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-environmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md
index 0cb95a9abfd6b90f1efacc431070ef6b3397e1e6..96c67de7c5cc52b781f55add22b59859560ee9d5 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,55 @@ 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));
+ if (error && error.code !== 0) {
+ console.error('unregisterEnvironmentCallback fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}');
+ }
});
}
}
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..3a4ed4c5017aa7798d7df6c6bfbd1d95d8401536 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.error('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,23 +67,23 @@ 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) {
- console.log('------------ unregisterErrorObserverCallback ------------', err);
+ console.error('------------ unregisterErrorObserverCallback ------------', err);
}
}
try {
- errorManager.off("error", observerId, unregisterErrorObserverCallback);
+ errorManager.off('error', observerId, unregisterErrorObserverCallback);
} catch (paramError) {
- console.log("error: " + paramError.code + ", " + paramError.message);
+ console.error('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);
- })
+ console.error('----------- unregisterErrorObserver fail ----------', err);
+ });
} catch (paramError) {
- console.log("error: " + paramError.code + ", " + paramError.message);
+ console.error('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..1224636ae4c0aa4ceb8634b244cd088257b64331 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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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..c7a4b185eba559adfde134dd38793d475bf724a0 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|
+ | 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.|
+ | 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.error( `applyQuickFix failed with error: ${error}`);
} else {
- console.info( 'applyQuickFix success')
+ console.info( 'applyQuickFix success');
}
- })
+ });
} catch (paramError) {
- console.log("error: " + paramError.code + ", " + paramError.message);
+ console.error('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|
+ | Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
- | hapModuleQuickFixFiles | Array\ | Yes| Quick fix files, each of which must contain a valid file path.|
+ | hapModuleQuickFixFiles | Array\ | Yes| Quick fix patch files, each of which must contain a valid file path.|
**Return value**
- | Type| Description|
+ | Type| Description|
| -------- | -------- |
- | Promise\ | Promise used to return the result.|
+ | 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.error(`applyQuickFix err: ${error}`);
+ });
} catch (paramError) {
- console.log("error: " + paramError.code + ", " + paramError.message);
+ console.error('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.error(`getApplicationQuickFixInfo error: ${error}`);
} else {
- console.info(`getApplicationQuickFixInfo success: + ${data}`)
+ console.info(`getApplicationQuickFixInfo success: ${data}`);
}
- })
+ });
} catch (paramError) {
- console.log("error: " + paramError.code + ", " + paramError.message);
- }
+ console.error('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|
+ | Type| Description|
| -------- | -------- |
- | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
+ | 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.error(`getApplicationQuickFixInfo err: ${error}`);
+ });
} catch (paramError) {
- console.log("error: " + paramError.code + ", " + paramError.message);
+ console.error('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 54200ed3e7e27043eb2798522a3fd1c991eca5a3..b57435673e0d2372d4980c5a540fea618719c839 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
@@ -33,7 +33,7 @@ import StartOptions from '@ohos.app.ability.StartOptions';
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)}');
+ console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
return;
}
console.log('size = ${missions.length}');
@@ -49,6 +49,6 @@ import StartOptions from '@ohos.app.ability.StartOptions';
});
});
} catch (paramError) {
- console.log('error: ${paramError.code}, ${paramError.message}');
+ console.error('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..a052c4dbec6fdb7c790c7195baf763f96dd90dad 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.error('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..c7fd0b0f4a3f21eec8dbf66c51f890d6436b08f0 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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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..dbef711c25369d3eac61ca1b6516a7c43d8ecbc2 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,17 +48,17 @@ 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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
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..bba49ff8ca2d8c96fd89e07b59c488d5cea12054 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,16 +43,16 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
} else {
console.log('formHost deleteForm success');
}
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -92,14 +92,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -133,14 +133,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -175,14 +175,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -222,14 +222,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -263,14 +263,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -309,14 +309,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -351,14 +351,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -397,14 +397,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -438,14 +438,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -484,14 +484,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -525,14 +525,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -571,14 +571,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -612,14 +612,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -658,14 +658,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -699,14 +699,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -745,14 +745,14 @@ 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) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -778,11 +778,11 @@ import formHost from '@ohos.app.form.formHost';
try {
formHost.isSystemReady((error, data) => {
if (error) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -809,10 +809,10 @@ try {
formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success');
}).catch((error) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -840,13 +840,13 @@ import formHost from '@ohos.app.form.formHost';
try {
formHost.getAllFormsInfo((error, data) => {
if (error) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -873,12 +873,12 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -912,15 +912,15 @@ 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}`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -955,15 +955,15 @@ 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}`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1003,13 +1003,13 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1036,16 +1036,16 @@ 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}`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1077,14 +1077,14 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1118,25 +1118,25 @@ 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 {
formHost.acquireFormState(want, (error, data) => {
if (error) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1175,29 +1175,29 @@ 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}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
-## 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,15 +1277,15 @@ 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) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1324,15 +1324,15 @@ 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');
}).catch((error) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1366,15 +1366,15 @@ 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) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1413,15 +1413,15 @@ 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');
}).catch((error) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
## shareForm
@@ -1454,16 +1454,16 @@ 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) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1502,16 +1502,16 @@ 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');
}).catch((error) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1545,15 +1545,15 @@ 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) {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
@@ -1590,14 +1590,14 @@ 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');
}).catch((error) => {
- console.log(`error, code: ${error.code}, message: ${error.message}`);
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message}`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
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..908c5a428a1a5f6cccd3f5ae2bc04e01ffa29716 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,17 +39,17 @@ 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) {
- console.log(`callback error, code: ${error.code}, message: ${error.message})`);
+ console.error(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log(`formProvider setFormNextRefreshTime success`);
}
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -86,15 +86,15 @@ 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`);
}).catch((error) => {
- console.log(`promise error, code: ${error.code}, message: ${error.message})`);
+ console.error(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -127,18 +127,18 @@ 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})`);
+ console.error(`callback error, code: ${error.code}, message: ${error.message})`);
} else {
console.log(`formProvider updateForm success`);
}
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -176,16 +176,16 @@ 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`);
}).catch((error) => {
- console.log(`promise error, code: ${error.code}, message: ${error.message})`);
+ console.error(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -219,13 +219,13 @@ import formProvider from '@ohos.app.form.formProvider';
try {
formProvider.getFormsInfo((error, data) => {
if (error) {
- console.log(`callback error, code: ${error.code}, message: ${error.message})`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
## getFormsInfo
@@ -258,18 +258,18 @@ 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})`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -308,16 +308,16 @@ 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})`);
+ console.error(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch 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,24 +353,24 @@ 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})`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -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,23 +404,23 @@ 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 {
formProvider.requestPublishForm(want, (error, data) => {
if (error) {
- console.log(`callback error, code: ${error.code}, message: ${error.message})`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -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,21 +460,21 @@ 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})`);
+ console.error(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -502,33 +502,33 @@ import formProvider from '@ohos.app.form.formProvider';
try {
formProvider.isRequestPublishFormSupported((error, isSupported) => {
if (error) {
- console.log(`callback error, code: ${error.code}, message: ${error.message})`);
+ console.error(`callback error, code: ${error.code}, message: ${error.message})`);
} 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 {
formProvider.requestPublishForm(want, (error, data) => {
if (error) {
- console.log(`callback error, code: ${error.code}, message: ${error.message})`);
+ console.error(`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) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
}
}
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
@@ -557,27 +557,27 @@ 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})`);
+ console.error(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch error, code: ${error.code}, message: ${error.message})`);
}
}
}).catch((error) => {
- console.log(`promise error, code: ${error.code}, message: ${error.message})`);
+ console.error(`promise error, code: ${error.code}, message: ${error.message})`);
});
} catch (error) {
- console.log(`catch error, code: ${error.code}, message: ${error.message})`);
+ console.error(`catch 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..5b2b923deeb737e90cd173b822e65a35b00e741a 100644
--- a/en/application-dev/reference/apis/js-apis-appAccount.md
+++ b/en/application-dev/reference/apis/js-apis-appAccount.md
@@ -1,4 +1,4 @@
-# @ohos.account.appAccount (App Account Management)
+# @ohos.account.appAccount (App Account Management)
The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization.
@@ -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 = {
@@ -1661,7 +1685,7 @@ Deletes the authorization token of the specified authentication type for an app
| name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. |
-| token | string | Yes | Token to delete.|
+| token | string | Yes | Authorization token to delete.|
**Return value**
@@ -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. Error codes are used from API version 9. For details, see [Account Management Error Codes](../errorcodes/errorcode-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)
@@ -4871,9 +4910,9 @@ Checks the account labels. This API uses an asynchronous callback to return the
| labels | Array<string> | Yes | Labels to check. |
| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the check result.|
-### isAccountRemovable9+
+### checkAccountRemovable9+
-isAccountRemovable(name: string, callback: AuthCallback): void;
+checkAccountRemovable(name: string, callback: AuthCallback): void;
Checks whether an app account can be deleted. This API uses an asynchronous callback to return the result.
@@ -4931,7 +4970,7 @@ Obtains the remote object of an authenticator. This API cannot be overloaded.
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
- isAccountRemovable(name, callback) {
+ checkAccountRemovable(name, callback) {
var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
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-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..23bd66e43063c5e2ea38b65d38da68272b041adb 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');
-})
+ console.error('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.error('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-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md
index c1da72e6dbe619a208cc72ad7f34256862b21589..f32952bbbf73311db85ce014fbd4c8892f3b1d56 100644
--- a/en/application-dev/reference/apis/js-apis-application-appManager.md
+++ b/en/application-dev/reference/apis/js-apis-application-appManager.md
@@ -22,17 +22,20 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example**
```ts
- appManager.isRunningInStabilityTest((err, flag) => {
- console.log('error: ${JSON.stringify(err)}');
- console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
- })
+ appManager.isRunningInStabilityTest((error, flag) => {
+ if (error && error.code !== 0) {
+ console.error('isRunningInStabilityTest fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('isRunningInStabilityTest success, the result is: ${JSON.stringify(flag)}');
+ }
+ });
```
@@ -46,9 +49,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value**
-| Type| Description|
-| -------- | -------- |
-| Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example**
@@ -56,7 +59,7 @@ Checks whether this application is undergoing a stability test. This API uses a
appManager.isRunningInStabilityTest().then((flag) => {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -71,9 +74,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value**
-| Type| Description|
-| -------- | -------- |
-| Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example**
@@ -81,7 +84,7 @@ Checks whether this application is running on a RAM constrained device. This API
appManager.isRamConstrainedDevice().then((data) => {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -95,17 +98,20 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example**
```ts
- appManager.isRamConstrainedDevice((err, data) => {
- console.log('error: ${JSON.stringify(err)}');
- console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
- })
+ appManager.isRamConstrainedDevice((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('isRamConstrainedDevice fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
+ }
+ });
```
## appManager.getAppMemorySize
@@ -118,9 +124,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value**
-| Type| Description|
-| -------- | -------- |
-| Promise<number> | Promise used to return the memory size, in MB.|
+ | Type| Description|
+ | -------- | -------- |
+ | Promise<number> | Promise used to return the memory size, in MB.|
**Example**
@@ -128,7 +134,7 @@ Obtains the memory size of this application. This API uses a promise to return t
appManager.getAppMemorySize().then((data) => {
console.log('The size of app memory is: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -142,16 +148,19 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| callback | AsyncCallback<number> | Yes| Callback used to return the memory size, in MB.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | 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)}');
+ appManager.getAppMemorySize((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getAppMemorySize fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('The size of app memory is: ${JSON.stringify(data)}');
+ }
});
```
## appManager.getProcessRunningInfos(deprecated)
@@ -178,7 +187,7 @@ Obtains information about the running processes. This API uses a promise to retu
appManager.getProcessRunningInfos().then((data) => {
console.log('The process running infos is: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('error: ${JSON.stringify(error)}');
+ console.error('error: ${JSON.stringify(error)}');
});
```
@@ -203,9 +212,12 @@ Obtains information about the running processes. This API uses an asynchronous c
**Example**
```ts
- appManager.getProcessRunningInfos((err, data) => {
- console.log('error: ${JSON.stringify(err)}');
- console.log('The process running infos is: ${JSON.stringify(data)}');
+ appManager.getProcessRunningInfos((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getProcessRunningInfos fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getProcessRunningInfos success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -320,7 +332,7 @@ Deregisters the application state observer. This API uses an asynchronous callba
function unregisterApplicationStateObserverCallback(err) {
if (err) {
- console.log('------------ unregisterApplicationStateObserverCallback ------------', err);
+ console.error('------------ unregisterApplicationStateObserverCallback ------------', err);
}
}
appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback);
@@ -360,7 +372,7 @@ Deregisters the application state observer. This API uses a promise to return th
console.log('----------- unregisterApplicationStateObserver success ----------', data);
})
.catch((err) => {
- console.log('----------- unregisterApplicationStateObserver fail ----------', err);
+ console.error('----------- unregisterApplicationStateObserver fail ----------', err);
});
```
@@ -387,7 +399,7 @@ Obtains information about the applications that are running in the foreground. T
```ts
function getForegroundApplicationsCallback(err, data) {
if (err) {
- console.log('--------- getForegroundApplicationsCallback fail ---------', err);
+ console.error('--------- getForegroundApplicationsCallback fail ---------', err);
} else {
console.log('--------- getForegroundApplicationsCallback success ---------', data);
}
@@ -421,7 +433,7 @@ Obtains information about the applications that are running in the foreground. T
console.log('--------- getForegroundApplications success -------', data);
})
.catch((err) => {
- console.log('--------- getForegroundApplications fail -------', err);
+ console.error('--------- getForegroundApplications fail -------', err);
});
```
@@ -454,7 +466,7 @@ appManager.killProcessWithAccount(bundleName, accountId)
console.log('------------ killProcessWithAccount success ------------', data);
})
.catch((err) => {
- console.log('------------ killProcessWithAccount fail ------------', err);
+ console.error('------------ killProcessWithAccount fail ------------', err);
});
```
@@ -486,7 +498,7 @@ let bundleName = 'bundleName';
let accountId = 0;
function killProcessWithAccountCallback(err, data) {
if (err) {
- console.log('------------- killProcessWithAccountCallback fail, err: --------------', err);
+ console.error('------------- killProcessWithAccountCallback fail, err: --------------', err);
} else {
console.log('------------- killProcessWithAccountCallback success, data: --------------', data);
}
@@ -519,7 +531,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return
let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err) {
- console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err);
+ console.error('------------- killProcessesByBundleNameCallback fail, err: --------------', err);
} else {
console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data);
}
@@ -560,7 +572,7 @@ Kills a process by bundle name. This API uses a promise to return the result.
console.log('------------ killProcessesByBundleName success ------------', data);
})
.catch((err) => {
- console.log('------------ killProcessesByBundleName fail ------------', err);
+ console.error('------------ killProcessesByBundleName fail ------------', err);
});
```
@@ -589,7 +601,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t
let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
if (err) {
- console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err);
+ console.error('------------- clearUpApplicationDataCallback fail, err: --------------', err);
} else {
console.log('------------- clearUpApplicationDataCallback success, data: --------------', data);
}
@@ -630,6 +642,6 @@ Clears application data by bundle name. This API uses a promise to return the re
console.log('------------ clearUpApplicationData success ------------', data);
})
.catch((err) => {
- console.log('------------ clearUpApplicationData fail ------------', err);
+ console.error('------------ clearUpApplicationData fail ------------', err);
});
```
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..624d5946bdb8988dccc8709701d44ae1c9addd96 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-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..00396ca388d9145f2b3905166b2ef317959f2744 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,41 @@ 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 = {
+ 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));
+ callbackId = applicationContext.registerEnvironmentCallback(environmentCallback);
+ 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));
+ if (error && error.code !== 0) {
+ console.error('unregisterEnvironmentCallback fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}');
+ }
});
}
}
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-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md
index e82f3f2f199c103a6b2ee6d1f15c54144ece2036..539d728f614c4c56655eb390e427febf63c16841 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.error('catch error, error: ${JSON.stringify(error)}');
}
```
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..80f45e11e8d85b07f240b0f036aa4c86b2329b8a 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.error('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.error('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.error('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.error('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..c09b0387f8aa1bff0b9f084136ad6ed70859c71f 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.error('unregisterMissionListener fail, error: ${error}');
+ });
```
@@ -124,20 +124,20 @@ 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);
+ missionManager.unregisterMissionListener(listenerid).catch(function (error) {
+ console.error('unregisterMissionListener fail, error: ${error}');
});
```
@@ -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.error('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,10 +212,10 @@ 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){
- console.log(err);
+ let mission = missionManager.getMissionInfo('', 10).catch(function (error){
+ console.error('getMissionInfo fail, error: ${error}');
});
```
@@ -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.error('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,10 +284,10 @@ 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){
- console.log(err);
+ let allMissions = missionManager.getMissionInfos('', 10).catch(function (error){
+ console.error('getMissionInfos fail, error: ${error}');
});
```
@@ -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.error('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.error('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,18 +365,20 @@ 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;
+ }).catch(function(error) {
+ console.error('getMissionInfos fail, error: ${error}');
+ });
+ console.log('size = ${allMissions.length}');
+ console.log('missions = ${JSON.stringify(allMissions)}');
+ let id = allMissions[0].missionId;
- var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){
- console.log(err);
+ let snapshot = missionManager.getMissionSnapShot('', id).catch(function (error){
+ console.error('getMissionSnapShot fail, error: ${error}');
});
```
@@ -407,27 +405,25 @@ 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.error('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.error('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,18 +455,20 @@ 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;
+ }).catch(function(error) {
+ console.error('getMissionInfos fail, error: ${error}');
+ });
+ console.log('size = ${allMissions.length}');
+ console.log('missions = ${JSON.stringify(allMissions)}');
+ let id = allMissions[0].missionId;
- var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){
- console.log(err);
+ let snapshot = missionManager.getLowResolutionMissionSnapShot('', id).catch(function (error){
+ console.error('getLowResolutionMissionSnapShot fail, error: ${error}');
});
```
@@ -497,21 +495,20 @@ 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.error('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,17 +540,19 @@ 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;
+ }).catch(function(error) {
+ console.error('getMissionInfos fail, error: ${error}');
+ });
+ 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);
+ missionManager.lockMission(id).catch(function (error){
+ console.error('lockMission fail, error: ${error}');
});
```
@@ -580,21 +579,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.error('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,21 +624,23 @@ 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;
+ }).catch(function(error) {
+ console.error('getMissionInfos fail, error: ${error}');
+ });
+ 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);
+ missionManager.lockMission(id).catch(function (error){
+ console.error('lockMission fail, error: ${error}');
});
- missionManager.unlockMission(id).catch(function (err){
- console.log(err);
+ missionManager.unlockMission(id).catch(function (error){
+ console.error('unlockMission fail, error: ${error}');
});
```
@@ -667,21 +667,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.error('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,18 +712,20 @@ 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;
+ }).catch(function(error) {
+ console.error('getMissionInfos fail, error: ${error}');
+ });
+ 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);
+ missionManager.clearMission(id).catch(function (error){
+ console.error('clearMission fail, error: ${error}');
});
```
@@ -747,7 +748,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,9 +774,9 @@ Clears all unlocked missions. This API uses a promise to return the result.
**Example**
```ts
- import missionManager from '@ohos.application.missionManager'
- missionManager.clearAllMissions().catch(function (err){
- console.log(err);
+ import missionManager from '@ohos.application.missionManager';
+ missionManager.clearAllMissions().catch(function (error){
+ console.error('clearAllMissions fail, error: ${error}');
});
```
@@ -802,21 +803,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.error('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 +838,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.error('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 +879,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,17 +890,19 @@ 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;
+ }).catch(function(error) {
+ console.error('getMissionInfos fail, error: ${error}');
+ });
+ 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);
+ missionManager.moveMissionToFront(id).catch(function (error){
+ console.error('moveMissionToFront fail, error: ${error}');
});
```
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..e0aeababdf7186ba26db281d2465e3f033392a51 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.error('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.error('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.error('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-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md
index ebf538d3b5508c1ee26aa77d4db01aa995239c3b..283786a82fd1ce50d7632b9354b99f32ff4419fb 100644
--- a/en/application-dev/reference/apis/js-apis-arraylist.md
+++ b/en/application-dev/reference/apis/js-apis-arraylist.md
@@ -404,11 +404,9 @@ arrayList.add(2);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
-arrayList.replaceAllElements((value: number, index: number)=> {
- return value = 2 * value;
-});
-arrayList.replaceAllElements((value: number, index: number) => {
- return value = value - 2;
+arrayList.replaceAllElements((value) => {
+ // Add the user operation logic based on the actual scenario.
+ return value;
});
```
@@ -453,7 +451,7 @@ arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.forEach((value, index) => {
- console.log(`value:${value}`, index);
+ console.log("value:" + value, "index:" + index);
});
```
@@ -796,14 +794,14 @@ arrayList.add(4);
// Method 1:
for (let item of arrayList) {
- console.log(`value:${item}`);
+ console.log(`value:${item}`);
}
// Method 2:
let iter = arrayList[Symbol.iterator]();
let temp = iter.next().value;
while(temp != undefined) {
- console.log(`value:${temp}`);
- temp = iter.next().value;
+ console.log(`value:${temp}`);
+ temp = iter.next().value;
}
```
diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md
index a992de969d6b6e673b89eff8f14f28f5328ce017..4abed77e24d5c6cf16d7fd84ce36cf806d06ce4e 100644
--- a/en/application-dev/reference/apis/js-apis-audio.md
+++ b/en/application-dev/reference/apis/js-apis-audio.md
@@ -75,7 +75,7 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to
```js
import featureAbility from '@ohos.ability.featureAbility';
-import fileio from '@ohos.fileio';
+import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';
let audioStreamInfo = {
@@ -130,7 +130,7 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res
```js
import featureAbility from '@ohos.ability.featureAbility';
-import fileio from '@ohos.fileio';
+import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';
let audioStreamInfo = {
@@ -349,7 +349,10 @@ Enumerates the audio stream types.
| VOICE_CALL8+ | 0 | Audio stream for voice calls.|
| RINGTONE | 2 | Audio stream for ringtones. |
| MEDIA | 3 | Audio stream for media purpose. |
+| ALARM10+ | 4 | Audio stream for alarming. |
+| ACCESSIBILITY10+ | 5 | Audio stream for accessibility. |
| VOICE_ASSISTANT8+ | 9 | Audio stream for voice assistant.|
+| ULTRASONIC10+ | 10 | Audio stream for ultrasonic. This is a system API.|
| ALL9+ | 100 | All public audio streams. This is a system API.|
## InterruptRequestResultType9+
@@ -457,7 +460,7 @@ Enumerates the audio sample formats.
| SAMPLE_FORMAT_S16LE | 1 | Signed 16-bit integer, little endian.|
| SAMPLE_FORMAT_S24LE | 2 | Signed 24-bit integer, little endian. Due to system restrictions, only some devices support this sampling format.|
| SAMPLE_FORMAT_S32LE | 3 | Signed 32-bit integer, little endian. Due to system restrictions, only some devices support this sampling format.|
-| SAMPLE_FORMAT_F32LE9+ | 4 | Signed 32-bit integer, little endian. Due to system restrictions, only some devices support this sampling format.|
+| SAMPLE_FORMAT_F32LE9+ | 4 | Signed 32-bit floating point number, little endian. Due to system restrictions, only some devices support this sampling format.|
## AudioErrors9+
@@ -529,9 +532,9 @@ Enumerates the audio content types.
| CONTENT_TYPE_SPEECH | 1 | Speech. |
| CONTENT_TYPE_MUSIC | 2 | Music. |
| CONTENT_TYPE_MOVIE | 3 | Movie. |
-| CONTENT_TYPE_SONIFICATION | 4 | Sonification content.|
+| CONTENT_TYPE_SONIFICATION | 4 | Notification tone. |
| CONTENT_TYPE_RINGTONE8+ | 5 | Ringtone. |
-
+| CONTENT_TYPE_ULTRASONIC10+| 9 | Ultrasonic. This is a system API.|
## StreamUsage
Enumerates the audio stream usage.
@@ -544,7 +547,10 @@ Enumerates the audio stream usage.
| STREAM_USAGE_MEDIA | 1 | Used for media. |
| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Used for voice communication.|
| STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | Used for voice assistant.|
+| STREAM_USAGE_ALARM10+ | 4 | Used for alarming. |
| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.|
+| STREAM_USAGE_ACCESSIBILITY10+ | 8 | Used for accessibility. |
+| STREAM_USAGE_SYSTEM10+ | 9 | System tone (such as screen lock or keypad tone). This is a system API.|
## InterruptRequestType9+
@@ -1757,7 +1763,7 @@ Sets a device to the active state. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------- | ---- | ------------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. |
+| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. |
| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
@@ -1789,7 +1795,7 @@ Sets a device to the active state. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------- | ---- | ------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.|
+| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. |
| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
**Return value**
@@ -1823,7 +1829,7 @@ Checks whether a device is active. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------- | ---- | ------------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. |
+| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. |
| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.|
**Example**
@@ -1854,7 +1860,7 @@ Checks whether a device is active. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------- | ---- | ------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.|
+| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. |
**Return value**
@@ -4054,7 +4060,7 @@ Describes an audio device.
| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ |
| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. |
| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. |
-| id9+ | number | Yes | No | Device ID. |
+| id9+ | number | Yes | No | Device ID, which is unique. |
| name9+ | string | Yes | No | Device name. |
| address9+ | string | Yes | No | Device address. |
| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. |
@@ -4577,16 +4583,27 @@ async function getCacheDir(){
path = await context.getCacheDir();
}
let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
-let ss = fileio.createStreamSync(filePath, 'r');
+let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
+let stat = await fs.stat(path);
let buf = new ArrayBuffer(bufferSize);
-ss.readSync(buf);
-audioRenderer.write(buf, (err, writtenbytes) => {
- if (writtenbytes < 0) {
- console.error('write failed.');
- } else {
- console.info(`Actual written bytes: ${writtenbytes}`);
- }
-});
+let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
+for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * this.bufferSize,
+ length: this.bufferSize
+ }
+ let readsize = await fs.read(file.fd, buf, options)
+ let writeSize = await new Promise((resolve,reject)=>{
+ this.audioRenderer.write(buf,(err,writeSize)=>{
+ if(err){
+ reject(err)
+ }else{
+ resolve(writeSize)
+ }
+ })
+ })
+}
+
```
@@ -4621,18 +4638,22 @@ async function getCacheDir(){
path = await context.getCacheDir();
}
let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
-let ss = fileio.createStreamSync(filePath, 'r');
+let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
+let stat = await fs.stat(path);
let buf = new ArrayBuffer(bufferSize);
-ss.readSync(buf);
-audioRenderer.write(buf).then((writtenbytes) => {
- if (writtenbytes < 0) {
- console.error('write failed.');
- } else {
- console.info(`Actual written bytes: ${writtenbytes}`);
- }
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
-});
+let len = stat.size % this.bufferSize == 0 ? Math.floor(stat.size / this.bufferSize) : Math.floor(stat.size / this.bufferSize + 1);
+for (let i = 0;i < len; i++) {
+ let options = {
+ offset: i * this.bufferSize,
+ length: this.bufferSize
+ }
+ let readsize = await fs.read(file.fd, buf, options)
+ try{
+ let writeSize = await this.audioRenderer.write(buf);
+ } catch(err) {
+ console.error(`audioRenderer.write err: ${err}`);
+ }
+}
```
diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-BundlePackInfo.md
similarity index 95%
rename from en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md
rename to en/application-dev/reference/apis/js-apis-bundleManager-BundlePackInfo.md
index a9e4c359659c55169acdbf0e3bc8f583b67febe9..e6fd8bd2c8cd018a0ed0fe0d5cfdb226f542b438 100644
--- a/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundleManager-BundlePackInfo.md
@@ -1,6 +1,6 @@
-# PackInfo
+# BundlePackInfo
-The **PackInfo** module provides information in the **pack.info** file. The information can be obtained using [freeInstall.getBundlePackInfo](js-apis-freeInstall.md).
+The **BundlePackInfo** module provides information in the **pack.info** file. The information can be obtained using [freeInstall.getBundlePackInfo](js-apis-freeInstall.md).
> **NOTE**
>
@@ -91,7 +91,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info
| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Name of the ability. The name must be unique in the bundle. |
| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.|
-| visible | boolean | Yes | No | Whether the ability can be called by other bundles. The value **true** means that the ability can be called by other bundles, and **false** means the opposite.|
+| exported | boolean | Yes | No | Whether the ability can be called by other bundles. The value **true** means that the ability can be called by other bundles, and **false** means the opposite.|
| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. |
## ExtensionAbility
diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md
index cacab28b20157441ee4f64bc69261c7f37f0809f..b15708816fdcaf8293209bcb008e2119979817f3 100644
--- a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md
@@ -22,7 +22,7 @@ The **AbilityInfo** module defines the ability information. A system application
| icon | string | Yes | No | Index of the ability icon resource file. |
| iconId | number | Yes | No | ID of the ability icon. |
| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.|
-| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. |
+| exported | boolean | Yes | No | Whether the ability can be called by other bundles. |
| type | [AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type. This attribute can be used only in the FA model.|
| orientation | [DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | No | Ability display orientation. |
| launchType | [LaunchType](js-apis-bundleManager.md#launchtype) | Yes | No | Ability launch mode. |
diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md
index 2537274b8d5bd50d6c47258be2770bd5d51a9733..8997e94099071ce9b4e806f06b008477352af187 100644
--- a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md
+++ b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md
@@ -9,16 +9,15 @@ The **ApplicationInfo** module defines the application information. A system app
## ApplicationInfo
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
-
| Name | Type | Readable| Writable| Description |
| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Application name. |
-| description | string | Yes | No | Application description. |
+| description | string | Yes | No | Description of the application, for example, "description": $string: mainability_description". |
| descriptionId | number | Yes | No | ID of the application description. |
| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. |
-| label | string | Yes | No | Application label. |
+| label | string | Yes | No | Application name, for example, "label": "$string: mainability_description".|
| labelId | number | Yes | No | ID of the application label. |
-| icon | string | Yes | No | Application icon. |
+| icon | string | Yes | No | Application icon, for example, "icon": "$media:icon". |
| iconId | number | Yes | No | ID of the application icon. |
| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. |
| permissions | Array\ | Yes | No | Permissions required for accessing the application. The permissions can be obtained by passing in **GET_APPLICATION_INFO_WITH_PERMISSION** to the **appFlags** parameter of [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo).|
@@ -27,9 +26,9 @@ The **ApplicationInfo** module defines the application information. A system app
| removable | boolean | Yes | No | Whether the application is removable. |
| accessTokenId | number | Yes | No | Access token ID of the application. |
| uid | number | Yes | No | UID of the application. |
-| iconResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Icon resource of the application. |
-| labelResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Label resource of the application. |
-| descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Description resource of the application. |
+| iconResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application icon. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call **getMediaContent** in [@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts) to obtain the resource details. |
+| labelResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application label. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call **getMediaContent** in [@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts) to obtain the resource details. |
+| descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application description. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call **getMediaContent** in [@ohos.resourceManager.d.ts](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.resourceManager.d.ts) to obtain the resource details.|
| appDistributionType | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. |
| appProvisionType | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**. |
| systemApp | boolean | Yes | No | Whether the application is a system application. |
diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md
index a346a61081df95cc18e35898c07674db7bd3f318..1503f821c413923f28e11a31a77c5cd2eb07c101 100644
--- a/en/application-dev/reference/apis/js-apis-bundleManager.md
+++ b/en/application-dev/reference/apis/js-apis-bundleManager.md
@@ -2215,7 +2215,7 @@ try {
### bundleManager.getProfileByAbility
-getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback>): void;
+getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\\>): void;
Obtains the JSON strings of the configuration file based on the given module ame, ability name, and metadata name. This API uses an asynchronous callback to return the result.
@@ -2266,7 +2266,7 @@ try {
### bundleManager.getProfileByAbility
-getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise>;
+getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise\\>;
Obtains the JSON strings of the configuration file based on the given module ame, ability name, and metadata name. This API uses a promise to return the result.
@@ -2336,7 +2336,7 @@ try {
### bundleManager.getProfileByExtensionAbility
-getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback>): void;
+getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\\>): void;
Obtains the JSON strings of the configuration file based on the given module ame, Extension ability name, and metadata name. This API uses an asynchronous callback to return the result.
@@ -2386,7 +2386,7 @@ try {
### bundleManager.getProfileByExtensionAbility
-getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise>;
+getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise\\>;
Obtains the JSON strings of the configuration file based on the given module ame, Extension ability name, and metadata name. This API uses a promise to return the result.
@@ -2659,7 +2659,6 @@ try {
### 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.
@@ -2710,6 +2709,42 @@ try {
}
```
+### bundleManager.getApplicationInfoSync
+
+getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md);
+
+Synchronously obtains the application information based on the given bundle name and application flags.
+
+**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.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------------- | -------------------------- | ---- | ----------------------------------------------------- |
+| bundleName | string | Yes | Bundle name. |
+| applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain.|
+
+**Return value**
+
+| Type | Description |
+| ----------------------------------------------------------- | ------------------------- |
+| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Application information obtained.|
+
+**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. |
+| 17700026 | The specified bundle is disabled. |
+
+**Example**
+
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
@@ -2727,7 +2762,6 @@ 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.
@@ -2743,7 +2777,7 @@ Synchronously obtains the bundle information based on the given bundle name, bun
| ----------- | ------ | ---- | -------------------------------------------------------- |
| bundleName | string | Yes | Bundle name. |
| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.|
-| userId | number | No | User ID. |
+| userId | number | Yes | User ID. |
**Return value**
@@ -2778,6 +2812,42 @@ try {
}
```
+### bundleManager.getBundleInfoSync
+
+getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md);
+
+Synchronously obtains the bundle information based on the given bundle name and bundle flags.
+
+**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.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ----------- | --------------------- | ---- | ------------------------------------------------------ |
+| bundleName | string | Yes | Bundle name. |
+| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.|
+
+**Return value**
+
+| Type | Description |
+| ------------------------------------------------- | -------------------- |
+| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.|
+
+**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. |
+| 17700026 | The specified bundle is disabled. |
+
+**Example**
+
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
@@ -2790,3 +2860,37 @@ try {
hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message);
}
```
+
+## ModuleType
+
+Enumerates the module types.
+
+ **System capability**: SystemCapability.BundleManager.BundleFramework.Core
+
+| Name | Value | Description |
+| ------- | ---- | -------------------- |
+| ENTRY | 1 | Main module of the application. |
+| FEATURE | 2 | Dynamic feature module of the application.|
+| SHARED | 3 | Dynamic shared library module of the application. |
+
+## BundleType
+
+Enumerates the bundle types.
+
+ **System capability**: SystemCapability.BundleManager.BundleFramework.Core
+
+| Name | Value | Description |
+| -------------- | ---- | --------------- |
+| APP | 0 | The bundle is a common application. |
+| ATOMIC_SERVICE | 1 | The bundle is an atomic service.|
+
+## AtomicServiceModuleType
+
+Enumerates the module types of an atomic service.
+
+ **System capability**: SystemCapability.BundleManager.BundleFramework.Core
+
+| Name | Value | Description |
+| ------ | ---- | --------------------------- |
+| NORMAL | 0 | Page package in the atomic service. |
+| MAIN | 1 | Landing page package in the atomic service.|
diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md
index 11f54832d6556e24f35cd1baedee0d9abfe39079..bf20a7708d16aa7a8f8daeb7f43c8f5fb60580c3 100644
--- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md
+++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md
@@ -16,7 +16,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor';
| Permission | Permission Level | Description |
| ------------------------------------ | ----------- | ------------------------------ |
-| ohos.permission.LISTEN_BUNDLE_CHANGE | system_core | Permission to listen for bundle installation, uninstall, and updates.|
+| ohos.permission.LISTEN_BUNDLE_CHANGE | system_basic | Permission to listen for bundle installation, uninstall, and updates.|
For details, see [Permission Levels](../../security/accesstoken-overview.md).
@@ -33,7 +33,7 @@ For details, see [Permission Levels](../../security/accesstoken-overview.md).
## bundleMonitor.on
-on(type: BundleChangedEvent, callback: callback\): void;
+on(type: BundleChangedEvent, callback: Callback\): void;
Subscribes to bundle installation, uninstall, and update events.
@@ -66,7 +66,7 @@ try {
## bundleMonitor.off
-off(type: BundleChangedEvent, callback?: callback\): void;
+off(type: BundleChangedEvent, callback?: Callback\): void;
Unsubscribes from bundle installation, uninstall, and update events.
diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md
index b30722bd2fddd6ef83914ffe6b8a3421831935ce..ec4684a53f03a85706e29f6fc918371ab54d5363 100644
--- a/en/application-dev/reference/apis/js-apis-camera.md
+++ b/en/application-dev/reference/apis/js-apis-camera.md
@@ -2,7 +2,8 @@
> **NOTE**
>
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> - The APIs provided by this module are system APIs.
## Modules to Import
@@ -476,10 +477,10 @@ Listens for camera status changes. This API uses an asynchronous callback to ret
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------- | ---- | --------- |
-| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The callback function returns the camera information, including the device and device status (available or unavailable). The event can be listened for only when a **CameraManager** instance is obtained.|
-| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. |
+| Name | Type | Mandatory| Description |
+| -------- | -----------------| ---- | --------- |
+| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The event can be listened for when a **CameraManager** instance is obtained. This event is triggered and the corresponding information is returned only when the device is enabled or disabled.|
+| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change.| |
**Example**
@@ -504,8 +505,8 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | --------- |
-| type | string | Yes | Event type. The value is fixed at **'cameraMute'**. The callback function returns the mute status changes. The event can be listened for only when a **CameraManager** instance is obtained.|
-| callback | AsyncCallback\ | Yes | Callback used to return the camera mute status. |
+| type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status. The event can be listened for when a **CameraManager** instance is obtained. This event is triggered and the status is returned when the camera is enabled or disabled.|
+| callback | AsyncCallback\ | Yes | Callback used to return the mute status. The value **true** means that the camera is enabled, and **false** means that the camera is disabled. |
**Example**
@@ -727,7 +728,7 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | --- | ------------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns an error code, for example, an error code indicating that the device is unavailable or a conflict occurs. The event can be listened for only when a **CameraInput** instance is obtained.|
+| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **CameraInput** instance is created. This event is triggered and the result is returned when an error occurs on the camera. For example, if the device is unavailable or a conflict occurs, the error information is returned.|
| cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.|
| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
@@ -761,9 +762,9 @@ Enumerates the exposure modes.
| Name | Value | Description |
| ----------------------------- | ---- | ----------- |
-| EXPOSURE_MODE_LOCKED | 0 | Exposure locked.|
-| EXPOSURE_MODE_AUTO | 1 | Auto exposure.|
-| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure.|
+| EXPOSURE_MODE_LOCKED | 0 | Exposure locked. The metering point cannot be set.|
+| EXPOSURE_MODE_AUTO | 1 | Auto exposure. The metering point can be set by calling [setMeteringPoint](#setmeteringpoint).|
+| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure. The metering point cannot be set.|
## FocusMode
@@ -773,10 +774,10 @@ Enumerates the focus modes.
| Name | Value | Description |
| -------------------------- | ---- | ------------ |
-| FOCUS_MODE_MANUAL | 0 | Manual focus. |
-| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.|
-| FOCUS_MODE_AUTO | 2 | Auto focus. |
-| FOCUS_MODE_LOCKED | 3 | Focus locked. |
+| FOCUS_MODE_MANUAL | 0 | Manual focus. The focal length of the camera can be manually set to change the focus position. However, the focal point cannot be set. |
+| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus. The focal point cannot be set.|
+| FOCUS_MODE_AUTO | 2 | Auto focus. The focal point can be set by calling [setFocusPoint](#setfocuspoint), and auto focus is performed once based on the focal point. After the auto focus operation is complete (regardless of whether the focus is successful or fails), the focus mode is locked. To enable the camera to initiate another auto focus, the application must call **CONTINUOUS_AUTO** again. |
+| FOCUS_MODE_LOCKED | 3 | Focus locked. The focal point cannot be set. |
## FocusState
@@ -1391,7 +1392,9 @@ try {
setMeteringPoint(point: Point): void
-Sets the metering point for the device.
+Sets the metering point, which is the center point of the metering rectangle. The metering point must be in the coordinate system (0-1), where the upper left corner is {0, 0} and the lower right corner is {1, 1}.
+
+The coordinate system is based on the horizontal device direction with the device's charging port on the right. If the layout of the preview screen of an application is based on the vertical direction with the charging port on the lower side, the layout width and height are {w, h}, and the touch point is {x, y}, then the coordinate point after conversion is {y/h, 1-x/w}.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1448,7 +1451,7 @@ try {
setExposureBias(exposureBias: number): void
-Sets an exposure compensation value for the device.
+Sets an exposure compensation value (EV).
Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values.
@@ -1590,7 +1593,9 @@ try {
setFocusPoint(point: Point): void
-Sets a focal point for the device.
+Sets the focal point. The focal point must be in the coordinate system (0-1), where the upper left corner is {0, 0} and the lower right corner is {1, 1}.
+
+The coordinate system is based on the horizontal device direction with the device's charging port on the right. If the layout of the preview screen of an application is based on the vertical direction with the charging port on the lower side, the layout width and height are {w, h}, and the touch point is {x, y}, then the coordinate point after conversion is {y/h, 1-x/w}.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1697,7 +1702,7 @@ try {
setZoomRatio(zoomRatio: number): void
-Sets a zoom ratio for the device.
+Sets a zoom ratio, with a maximum precision of two decimal places.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1849,7 +1854,7 @@ Listens for focus state changes. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The callback function returns the focus state change. The event can be listened for only when the session is created.|
+| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The event can be listened for when a session is created. This event is triggered only when the camera focus state changes in auto focus mode.|
| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. |
**Example**
@@ -1872,7 +1877,7 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **CaptureSession** API, for example, **beginConfig()**, **commitConfig()**, or **addInput()**.|
+| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a session is created. This event is triggered and the error message is returned when an error occurs during the calling of a session-related API such as **beginConfig()**, **commitConfig()**, and **addInput**.|
| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -2053,8 +2058,8 @@ Listens for preview frame start events. This API uses an asynchronous callback t
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | --------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The callback is invoked when the preview on the first frame starts. This event can be listened for only when a **previewOutput** instance is created.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure for the first time.|
+| callback | AsyncCallback | Yes | Callback used to return the result. The preview starts as long as this event is returned. |
**Example**
@@ -2076,8 +2081,8 @@ Listens for preview frame end events. This API uses an asynchronous callback to
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The callback is invoked when the preview on the last frame ends. This event can be listened for only when a **previewOutput** instance is created.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the last frame of preview ends.|
+| callback | AsyncCallback | Yes | Callback used to return the result. The preview ends as long as this event is returned. |
**Example**
@@ -2097,9 +2102,9 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------------------- | ---- | ------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **PreviewOutput** API, for example, **start()** or **release()**.|
+| Name | Type | Mandatory| Description |
+| -------- | --------------| ---- | ------------------------ |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the use of a preview-related API such as **start()** or **release()**.|
| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -2366,7 +2371,7 @@ Listens for shooting start events. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'captureStart'**. The callback function returns the shooting start event.|
+| type | string | Yes | Event type. The value is fixed at **'captureStart'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure each time a photo is taken.|
| callback | AsyncCallback | Yes | Callback used to return the capture ID. |
**Example**
@@ -2387,10 +2392,10 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------- | --- | ------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The callback function returns the captured frame information (captureId and time).|
-| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory| Description |
+| -------- | ---------- | --- | ------------------------------------ |
+| type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The event can be listened for when a **photoOutput** instance is created.|
+| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. A new photographing request can be delivered as long as this event is returned. |
**Example**
@@ -2411,9 +2416,9 @@ Listens for shooting end events. This API uses an asynchronous callback to retur
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------- | ---- | ---------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The callback function returns the shooting end event.|
+| Name | Type | Mandatory| Description |
+| -------- | --------------- | ---- | ---------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding information is returned when the photographing is complete.|
| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. |
**Example**
@@ -2435,9 +2440,9 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------- | ---- | ----------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns an error code when an API call fails.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------- | ---- | ----------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a photographing-related API.|
| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -2637,8 +2642,8 @@ Listens for video recording start events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ----------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The callback is invoked when the recording on the first frame of an image starts.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **videoOutput** instance is created. The event is triggered and the corresponding information is returned when the bottom layer starts exposure for the first time.|
+| callback | AsyncCallback | Yes | Callback used to return the result. The recording starts as long as this event is returned. |
**Example**
@@ -2660,8 +2665,8 @@ Listens for video recording stop events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The callback is invoked when the recording on the last frame of an image stops.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and returned when the last frame of recording is complete.|
+| callback | AsyncCallback | Yes | Callback used to return the result. The recording ends as long as this event is returned. |
**Example**
@@ -2681,9 +2686,9 @@ Listens for errors that occur during video recording. This API uses a callback t
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------ | ---- | -------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **VideoOutput** API, for example, **start()** or **release()**.|
+| Name | Type | Mandatory| Description |
+| -------- | ----------- | ---- | -------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a recording-related API such as **start()** and **release()**.|
| callback | Callback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -2808,9 +2813,9 @@ Listens for metadata objects. This API uses an asynchronous callback to return t
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------ | ---- | ------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The callback function returns the valid metadata. This event can be listened for only when a **MetadataOutput** instance is created.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------- | ---- | ------------------------------------ |
+| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding metadata is returned when valid metadata is detected.|
| callback | Callback\> | Yes | Callback used to return the metadata.|
**Example**
@@ -2831,9 +2836,9 @@ Listens for metadata errors. This API uses an asynchronous callback to return th
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------ | ---- | --------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **MetadataOutput** instance API, for example, **start()** or **release()**.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------- | ---- | --------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a metadata-related API such as **start()** and **release()**.|
| callback | Callback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -2852,7 +2857,7 @@ Enumerates the metadata object types.
| Name | Value | Description |
| ------------------------- | ---- | ----------------- |
-| FACE_DETECTION | 0 | Face detection.|
+| FACE_DETECTION | 0 | Face detection. The detection point must be in the coordinate system (0-1), where the upper left corner is {0, 0} and the lower right corner is {1, 1}. The coordinate system is based on the horizontal device direction with the device's charging port on the right. If the layout of a preview screen of an application is based on the vertical direction with the charging port on the lower side, the layout width and height are {w, h} and the return point is {x, y}, then the coordinate point after conversion is {1-y, x}.|
## Rect
diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md
index 70d35b6cb168e6f10b847a42bdefa8fd53eb3d40..4c66c928fb7ee6c5482d39db7b39acaa6793691e 100644
--- a/en/application-dev/reference/apis/js-apis-convertxml.md
+++ b/en/application-dev/reference/apis/js-apis-convertxml.md
@@ -47,21 +47,27 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
**Example**
```js
-let xml =
- '' +
- '' +
- ' Happy' +
- ' Work' +
- ' Play' +
- '';
-let conv = new convertxml.ConvertXML()
-let options = {trim : false, declarationKey:"_declaration",
- instructionKey : "_instruction", attributesKey : "_attributes",
- textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
- commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
- nameKey : "_name", elementsKey : "_elements"}
-let result = JSON.stringify(conv.convertToJSObject(xml, options));
-console.log(result);
+try {
+ let xml =
+ '' +
+ '' +
+ ' Happy' +
+ ' Work' +
+ ' Play' +
+ '';
+ let conv = new convertxml.ConvertXML()
+ let options = {
+ trim: false, declarationKey: "_declaration",
+ instructionKey: "_instruction", attributesKey: "_attributes",
+ textKey: "_text", cdataKey: "_cdata", doctypeKey: "_doctype",
+ commentKey: "_comment", parentKey: "_parent", typeKey: "_type",
+ nameKey: "_name", elementsKey: "_elements"
+ }
+ let result = JSON.stringify(conv.convertToJSObject(xml, options));
+ console.log(result);
+} catch (e) {
+ console.log(e.toString());
+}
// Output (non-compact)
// {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]}
```
diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md
index 82a333b14b2ea90e92540ee31142ea884c7f2593..b79161a08e5916eecca479c99f6fd852f8e6fd4a 100644
--- a/en/application-dev/reference/apis/js-apis-data-dataShare.md
+++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md
@@ -1,14 +1,15 @@
-# @ohos.data.dataShare (DataShare)
+# @ohos.data.dataShare (Data Sharing)
The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
> **NOTE**
>
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> - 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.
+> - The APIs provided by this module are system APIs.
+>
+> - The APIs of this module can be used only in the stage model.
## Modules to Import
@@ -55,7 +56,7 @@ Observe the following when using this API:
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ |
-| context | [Context](js-apis-application-context.md#context) | Yes | Context of an application. |
+| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. |
| uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. |
| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.|
@@ -105,7 +106,7 @@ Observe the following when using this API:
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------- | ---- | ------------------------------ |
-| context | [Context](js-apis-application-context.md#context) | Yes | Context of an application. |
+| context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of an application. |
| uri | string | Yes | URI of the server application to connect.|
**Return value**
@@ -187,18 +188,19 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono
| -------- | -------------------- | ---- | ------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.|
| uri | string | Yes | URI of the data.|
-| callback | AsyncCallback<void> | No | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
+| callback | AsyncCallback<void> | No | Callback for the data change event. If this parameter is left empty, all notification events of the URI are unsubscribed from.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
-function offCallback() {
- console.info("**** Observer off callback ****");
+function callback() {
+ console.info("**** Observer callback ****");
}
let uri = ("datashare:///com.samples.datasharetest.DataShare");
-dataShareHelper.off("dataChange", uri, offCallback);
+dataShareHelper.on("dataChange", uri, callback);
+dataShareHelper.off("dataChange", uri, callback);
```
### insert
diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md
index d3285fa80427790ba723737e20bc5559f0cc85ab..5c27d183e38680ec392471f55e374a5127714e82 100644
--- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md
+++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md
@@ -15,7 +15,7 @@ import distributedObject from '@ohos.data.distributedDataObject';
## distributedObject.create9+
-create(context: Context, source: object): DistributedObjectV9
+create(context: Context, source: object): DataObject
Creates a distributed data object.
@@ -25,14 +25,14 @@ Creates a distributed data object.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| context | Context | Yes| Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md).|
+| context | Context | Yes| Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| source | object | Yes| Attributes of the distributed data object.|
**Return value**
| Type| Description|
| -------- | -------- |
-| [DistributedObjectV9](#distributedobjectv9) | Distributed data object created.|
+| [DataObject](#dataobject) | Distributed data object created.|
**Example**
@@ -55,15 +55,14 @@ Stage model:
import distributedObject from '@ohos.data.distributedDataObject';
import UIAbility from '@ohos.app.ability.UIAbility';
-// Obtain the context.
-let context;
+let g_object = null;
+
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
- context = this.context
+ // Create a distributed data object, which has attributes of the string, number, boolean, and object types.
+ g_object = distributedObject.create(this.context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
}
}
-// Create a distributed data object, which contains attributes of the string, number, boolean, and object types.
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
```
## distributedObject.genSessionId
@@ -109,9 +108,9 @@ Called when the **revokeSave()** API is successfully called.
| -------- | -------- | -------- | -------- |
| sessionId | string | Yes| Unique ID for multi-device collaboration.|
-## DistributedObjectV9
+## DataObject
-Provides APIs for managing a distributed data object.
+Provides APIs for managing a distributed data object. Before using any API of this class, use [create()](#distributedobjectcreate9) to create a **DataObject** object.
### setSessionId9+
@@ -132,7 +131,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Error codes**
- For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md).
+For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
@@ -140,36 +139,10 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-// Add g_object to the distributed network.
-g_object.setSessionId(distributedObject.genSessionId(), ()=>{
- console.log("join session");
-});
-```
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId(), ()=>{
- console.log("join session");
+ console.info("join session");
});
```
@@ -191,7 +164,7 @@ Exits all joined sessions.
**Error codes**
- For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md).
+ For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
@@ -199,44 +172,14 @@ Exits all joined sessions.
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId(), ()=>{
- console.log("join session");
+ console.info("join session");
});
// Exit the distributed network.
g_object.setSessionId(() => {
- console.log("leave all lession.");
-});
-```
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-// Add g_object to the distributed network.
-g_object.setSessionId(distributedObject.genSessionId(), ()=>{
- console.log("join session");
-});
-// Exit the distributed network.
-g_object.setSessionId(() => {
- console.log("leave all lession.");
+ console.info("leave all lession.");
});
```
@@ -264,7 +207,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Error codes**
- For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md).
+ For details about the error codes, see [Distributed Data Object Error Codes](../errorcodes/errorcode-distributed-dataObject.md).
| ID| Error Message|
| -------- | -------- |
@@ -272,41 +215,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-// Add g_object to the distributed network.
-g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
- console.log("join session.");
- }).catch((error)=>{
- console.info("error:" + error.code + error.message);
-});
-// Exit the distributed network.
-g_object.setSessionId().then (()=>{
- console.log("leave all lession.");
- }).catch((error)=>{
- console.info("error:" + error.code + error.message);
-});
-```
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
console.info("join session.");
@@ -315,7 +224,7 @@ g_object.setSessionId(distributedObject.genSessionId()).then (()=>{
});
// Exit the distributed network.
g_object.setSessionId().then (()=>{
- console.log("leave all lession.");
+ console.info("leave all lession.");
}).catch((error)=>{
console.info("error:" + error.code + error.message);
});
@@ -338,39 +247,7 @@ Subscribes to data changes of this distributed data object.
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-globalThis.changeCallback = (sessionId, changeData) => {
- console.info("change" + sessionId);
- if (changeData != null && changeData != undefined) {
- changeData.forEach(element => {
- console.info("changed !" + element + " " + g_object[element]);
- });
- }
-}
-g_object.on("change", globalThis.changeCallback);
-```
-
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
@@ -394,40 +271,13 @@ Unsubscribes from the data changes of this distributed data object.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes. |
+| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered. **sessionId** indicates the session ID of the distributed data object. **fields** indicates the changed attributes of the distributed data object.|
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-// Unregister the specified data change callback.
-g_object.off("change", globalThis.changeCallback);
-// Unregister all data change callbacks.
-g_object.off("change");
-```
-
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks.
@@ -451,37 +301,10 @@ Subscribes to statue changes of this distributed data object.
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-globalThis.statusCallback = (sessionId, networkId, status) => {
- globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-g_object.on("status", globalThis.statusCallback);
-```
-
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback);
```
@@ -503,37 +326,7 @@ Unsubscribes from the status change of this distributed data object.
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
-globalThis.statusCallback = (sessionId, networkId, status) => {
- globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
-}
-// Unregister the specified status change callback.
-g_object.off("status",globalThis.statusCallback);
-// Unregister all status change callbacks.
-g_object.off("status");
-```
-
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
@@ -568,38 +361,10 @@ The saved data will be released in the following cases:
**Example**
-FA model:
```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local", (result) => {
- console.log("save callback");
- console.info("save sessionId: " + result.sessionId);
- console.info("save version: " + result.version);
- console.info("save deviceId: " + result.deviceId);
-});
-```
-
-Stage model:
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
-g_object.setSessionId("123456");
-g_object.save("local", (result) => {
- console.log("save callback");
+ console.info("save callback");
console.info("save sessionId: " + result.sessionId);
console.info("save version: " + result.version);
console.info("save deviceId: " + result.deviceId);
@@ -637,37 +402,9 @@ The saved data will be released in the following cases:
**Example**
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local").then((result) => {
- console.log("save callback");
- console.info("save sessionId " + result.sessionId);
- console.info("save version " + result.version);
- console.info("save deviceId " + result.deviceId);
-}, () => {
- console.error("save failed");
-});
-```
-
-```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context
- }
-}
-let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false});
-g_object.setSessionId("123456");
-g_object.save("local").then((result) => {
- console.log("save callback");
+ console.info("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
@@ -680,7 +417,7 @@ g_object.save("local").then((result) => {
revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void
-Revokes the saving operation of a distributed data object. This API uses an asynchronous callback to return the result.
+Revokes the saving operation of this distributed data object. This API uses an asynchronous callback to return the result.
If the object is saved on the local device, the data saved on all trusted devices will be deleted.
If the object is stored on another device, the data on the local device will be deleted.
@@ -695,55 +432,19 @@ If the object is stored on another device, the data on the local device will be
**Example**
-FA model:
-
```js
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
// Save data for persistence.
g_object.save("local", (result) => {
- console.log("save callback");
- console.info("save sessionId " + result.sessionId);
- console.info("save version " + result.version);
- console.info("save deviceId " + result.deviceId);
-});
-// Delete the persistence data.
-g_object.revokeSave((result) => {
- console.log("revokeSave callback");
- console.log("revokeSave sessionId " + result.sessionId);
-});
-```
-
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
-g_object.setSessionId("123456");
-// Save data for persistence.
-g_object.save("local", (result) => {
- console.log("save callback");
+ console.info("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
});
// Delete the persistence data.
g_object.revokeSave((result) => {
- console.log("revokeSave callback");
- console.log("revokeSave sessionId " + result.sessionId);
+ console.info("revokeSave callback");
+ console.info("revokeSave sessionId " + result.sessionId);
});
```
@@ -751,7 +452,7 @@ g_object.revokeSave((result) => {
revokeSave(): Promise<RevokeSaveSuccessResponse>
-Revokes the saving operation of a distributed data object. This API uses a promise to return the result.
+Revokes the saving operation of this distributed data object. This API uses a promise to return the result.
If the object is saved on the local device, the data saved on all trusted devices will be deleted.
If the object is stored on another device, the data on the local device will be deleted.
@@ -766,18 +467,11 @@ If the object is stored on another device, the data on the local device will be
**Example**
-FA model:
-
```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import featureAbility from '@ohos.ability.featureAbility';
-// Obtain the context.
-let context = featureAbility.getContext();
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
// Save data for persistence.
g_object.save("local").then((result) => {
- console.log("save callback");
+ console.info("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
@@ -786,41 +480,8 @@ g_object.save("local").then((result) => {
});
// Delete the persistence data.
g_object.revokeSave().then((result) => {
- console.log("revokeSave callback");
- console.log("sessionId" + result.sessionId);
-}, () => {
- console.error("revokeSave failed");
-});
-```
-
-Stage model:
-
-```ts
-import distributedObject from '@ohos.data.distributedDataObject';
-import UIAbility from '@ohos.app.ability.UIAbility';
-
-// Obtain the context.
-let context;
-class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
- context = this.context
- }
-}
-let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false});
-g_object.setSessionId("123456");
-g_object.save("local").then((result) => {
- console.log("save callback");
- console.info("save sessionId " + result.sessionId);
- console.info("save version " + result.version);
- console.info("save deviceId " + result.deviceId);
-}, () => {
- console.error("save failed");
-});
-
-// Delete the persistence data.
-g_object.revokeSave().then((result) => {
- console.log("revokeSave callback");
- console.log("sessionId" + result.sessionId);
+ console.info("revokeSave callback");
+ console.info("sessionId" + result.sessionId);
}, () => {
console.error("revokeSave failed");
});
@@ -861,7 +522,7 @@ let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, is
## DistributedObject(deprecated)
-Provides APIs for managing a distributed data object.
+Provides APIs for managing a distributed data object. Before using any API of this class, use [createDistributedObject()](#distributedobjectcreatedistributedobjectdeprecated) to create a **DistributedObject** object.
### setSessionId(deprecated)
@@ -1004,7 +665,7 @@ Unsubscribes from the status change of this distributed data object.
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('status')](#offstatus9) instead.
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [off('status')](#offstatus9).
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md
index b279dfcd4e2938efb33a33a70a35228a9de89b4d..99e43bc6a0e1a748dcea5eb8777db5361ded3040 100644
--- a/en/application-dev/reference/apis/js-apis-data-preferences.md
+++ b/en/application-dev/reference/apis/js-apis-data-preferences.md
@@ -5,7 +5,7 @@ The **Preferences** module provides APIs for processing data in the form of key-
The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.
-> **NOTE**
+> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -22,8 +22,8 @@ import data_preferences from '@ohos.data.preferences';
| Name | Type| Readable| Writable| Description |
| ---------------- | -------- | ---- | ---- | --------------------------------------- |
-| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key. The key must be less than 80 bytes. |
-| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value. The value must be less than 8192 bytes.|
+| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 80 bytes. |
+| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value, which is 8192 bytes.|
## data_preferences.getPreferences
@@ -38,8 +38,8 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
-| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
-| name | string | Yes | Name of the **Preferences** instance.|
+| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
+| name | string | Yes | Name of the **Preferences** instance. |
| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
**Example**
@@ -55,42 +55,40 @@ let preferences = null;
try {
data_preferences.getPreferences(context, 'mystore', function (err, val) {
if (err) {
- console.info("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
return;
}
- console.info("Got the preferences successfully.");
+ preferences = val;
+ console.info("Obtained the preferences successfully.");
})
} catch (err) {
- console.info("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
-// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
-let context = null;
+let preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
+ onWindowStageCreate(windowStage) {
+ try {
+ data_preferences.getPreferences(this.context, 'mystore', function (err, val) {
+ if (err) {
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ return;
+ }
+ preferences = val;
+ console.info("Obtained the preferences successfully.");
+ })
+ } catch (err) {
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ }
}
}
-
-let preferences = null;
-try {
- data_preferences.getPreferences(context, 'mystore', function (err, val) {
- if (err) {
- console.info("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
- return;
- }
- console.info("Got the preferences successfully.");
- })
-} catch (err) {
- console.info("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
-}
```
## data_preferences.getPreferences
@@ -105,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
-| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
+| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance.|
**Return value**
@@ -128,41 +126,37 @@ try {
let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((object) => {
preferences = object;
- console.info("Got the preferences successfully.");
+ console.info("Obtained the preferences successfully.");
}).catch((err) => {
- console.log("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.log("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
-// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
-let context = null;
+let preferences = null;
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
+ onWindowStageCreate(windowStage) {
+ try {
+ let promise = data_preferences.getPreferences(this.context, 'mystore');
+ promise.then((object) => {
+ preferences = object;
+ console.info("Obtained the preferences successfully.");
+ }).catch((err) => {
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ })
+ } catch(err) {
+ console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
+ }
}
}
-
-let preferences = null;
-try {
- let promise = data_preferences.getPreferences(context, 'mystore');
- promise.then((object) => {
- preferences = object;
- console.info("Got the preferences successfully.");
- }).catch((err) => {
- console.log("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
- })
-} catch(err) {
- console.log("Failed to get the preferences. code =" + err.code + ", message =" + err.message);
-}
```
## data_preferences.deletePreferences
@@ -181,7 +175,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
-| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
+| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
@@ -218,27 +212,21 @@ try {
Stage model:
```ts
-// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
-
-let context = null;
-
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
- }
-}
-
-try {
- data_preferences.deletePreferences(context, 'mystore', function (err, val) {
- if (err) {
+ onWindowStageCreate(windowStage) {
+ try {
+ data_preferences.deletePreferences(this.context, 'mystore', function (err, val) {
+ if (err) {
+ console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ return;
+ }
+ console.info("Deleted the preferences successfully." );
+ })
+ } catch (err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
- return;
}
- console.info("Deleted the preferences successfully." );
- })
-} catch (err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ }
}
```
@@ -258,7 +246,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
-| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
+| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value**
@@ -299,27 +287,21 @@ try {
Stage model:
```ts
-// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
-
-let context = null;
-
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
+ onWindowStageCreate(windowStage) {
+ try{
+ let promise = data_preferences.deletePreferences(this.context, 'mystore');
+ promise.then(() => {
+ console.info("Deleted the preferences successfully.");
+ }).catch((err) => {
+ console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ })
+ } catch(err) {
+ console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
+ }
}
}
-
-try{
- let promise = data_preferences.deletePreferences(context, 'mystore');
- promise.then(() => {
- console.info("Deleted the preferences successfully.");
- }).catch((err) => {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
- })
-} catch(err) {
- console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
-}
```
## data_preferences.removePreferencesFromCache
@@ -336,7 +318,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
-| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
+| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
@@ -365,27 +347,21 @@ try {
Stage model:
```ts
-// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
-
-let context = null;
-
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
- }
-}
-
-try {
- data_preferences.removePreferencesFromCache(context, 'mystore', function (err, val) {
- if (err) {
+ onWindowStageCreate(windowStage) {
+ try {
+ data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err, val) {
+ if (err) {
+ console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
+ return;
+ }
+ console.info("Removed the preferences successfully.");
+ })
+ } catch (err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
- return;
}
- console.info("Removed the preferences successfully.");
- })
-} catch (err) {
- console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
+ }
}
```
@@ -404,7 +380,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
-| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
+| context | Context | Yes | Application context. For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md). For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value**
@@ -437,25 +413,22 @@ try {
Stage model:
```ts
-// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
-let context = null;
+
class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage){
- context = this.context;
+ onWindowStageCreate(windowStage) {
+ try {
+ let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore');
+ promise.then(() => {
+ console.info("Removed the preferences successfully.");
+ }).catch((err) => {
+ console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
+ })
+ } catch(err) {
+ console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
+ }
}
}
-
-try {
- let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
- promise.then(() => {
- console.info("Removed the preferences successfully.");
- }).catch((err) => {
- console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
- })
-} catch(err) {
- console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message);
-}
```
## Preferences
@@ -469,7 +442,7 @@ Before calling any method of **Preferences**, you must obtain a **Preferences**
get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void
-Obtains the value of a key. This API uses an asynchronous callback to return the result. If the value is **null** or is not the type of the default value, the default value is returned.
+Obtains the value of a key. This API uses an asynchronous callback to return the result. If the value is **null** or is not of the default value type, **defValue** is returned.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -487,13 +460,13 @@ Obtains the value of a key. This API uses an asynchronous callback to return the
try {
preferences.get('startup', 'default', function (err, val) {
if (err) {
- console.info("Failed to get the value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Obtained the value of 'startup' successfully. val: " + val);
})
} catch (err) {
- console.info("Failed to get the value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -502,7 +475,7 @@ try {
get(key: string, defValue: ValueType): Promise<ValueType>
-Obtains the value of a key. This API uses a promise to return the result. If the value is **null** or is not the type of the default value, the default value is returned.
+Obtains the value of a key. This API uses a promise to return the result. If the value is **null** or is not of the default value type, **defValue** is returned.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -530,7 +503,7 @@ try {
console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
- console.info("Failed to get the value of 'startup'. code =" + err.code + ", message =" + err.message);
+ console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message);
}
```
@@ -672,7 +645,7 @@ try {
has(key: string, callback: AsyncCallback<boolean>): void
-Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result..
+Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -708,7 +681,7 @@ try {
has(key: string): Promise<boolean>
-Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result..
+Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -804,10 +777,10 @@ try {
promise.then(() => {
console.info("Deleted the key 'startup'.");
}).catch((err) => {
- console.log("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
+ console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
})
} catch(err) {
- console.log("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
+ console.info("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
}
```
@@ -955,7 +928,7 @@ Subscribes to data changes. A callback will be triggered to return the new value
try {
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
- console.info("Failed to get the preferences.");
+ console.info("Failed to obtain the preferences.");
return;
}
let observer = function (key) {
@@ -997,7 +970,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. |
-| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.|
+| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks for all data changes will be unregistered.|
**Example**
@@ -1005,7 +978,7 @@ Unsubscribes from data changes.
try {
data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
- console.info("Failed to get the preferences.");
+ console.info("Failed to obtain the preferences.");
return;
}
let observer = function (key) {
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-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md
index 63e6decf149d62da32381aefbee2707dab29c632..dbb9244fbe3f973baf0b307a80b7a0ed23482f71 100644
--- a/en/application-dev/reference/apis/js-apis-data-storage.md
+++ b/en/application-dev/reference/apis/js-apis-data-storage.md
@@ -7,8 +7,8 @@ The **DataStorage** module provides applications with data processing capability
>
> - 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 no longer maintained since API version 9. You are advised to use [`@ohos.data.preferences`](js-apis-data-preferences.md).
->
+> - The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.preferences](js-apis-data-preferences.md).
+>
> - The APIs of this module can be used only in the FA model.
@@ -24,8 +24,8 @@ import data_storage from '@ohos.data.storage';
| Name | Type| Readable| Writable| Description |
| ---------------- | -------- | ---- | ---- | ------------------------------------- |
-| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key. It must be less than 80 bytes. |
-| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value. It must be less than 8192 bytes.|
+| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 80 bytes. |
+| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value, which is 8192 bytes.|
## data_storage.getStorageSync
@@ -79,7 +79,7 @@ Reads the specified file and loads its data to the **Storage** instance for data
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | -------------------------- |
| path | string | Yes | Path of the target file.|
-| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback used to return the execution result. |
+| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback invoked to return the result. |
**Example**
@@ -172,7 +172,7 @@ context.getFilesDir().then((filePath) => {
console.info("======================>getFilesDirPromise====================>");
data_storage.deleteStorageSync(path + '/mystore');
-});
+});
```
## data_storage.deleteStorage
@@ -276,9 +276,9 @@ let context = featureAbility.getContext();
context.getFilesDir().then((filePath) => {
path = filePath;
console.info("======================>getFilesDirPromise====================>");
-
+
data_storage.removeStorageFromCacheSync(path + '/mystore');
-});
+});
```
@@ -367,7 +367,7 @@ Provides APIs for obtaining and modifying storage data.
getSync(key: string, defValue: ValueType): ValueType
-Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned.
+Obtains the value corresponding to a key. If the value is null or not of the default value type, **defValue** is returned.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -396,7 +396,7 @@ console.info("The value of startup is " + value);
get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void
-Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. This API uses an asynchronous callback to return the result.
+Obtains the value corresponding to a key. If the value is null or not of the default value type, **defValue** is returned. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -406,7 +406,7 @@ Obtains the value corresponding to a key. If the value is null or not in the def
| -------- | ------------------------------ | ---- | ----------------------------------------- |
| key | string | Yes | Key of the data. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value.|
-| callback | AsyncCallback<ValueType> | Yes | Callback used to return the execution result. |
+| callback | AsyncCallback<ValueType> | Yes | Callback invoked to return the result. |
**Example**
@@ -425,7 +425,7 @@ storage.get('startup', 'default', function(err, value) {
get(key: string, defValue: ValueType): Promise<ValueType>
-Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. This API uses a promise to return the result.
+Obtains the value corresponding to a key. If the value is null or not of the default value type, **defValue** is returned. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
@@ -581,7 +581,7 @@ Checks whether the storage object contains data with a given key. This API uses
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------- |
| key | string | Yes | Key of the data. It cannot be empty.|
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the execution result. |
+| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. |
**Return value**
@@ -867,7 +867,7 @@ Subscribes to data changes. The **StorageObserver** needs to be implemented. Whe
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ------ |---------------------------------------- |
| type | string |Yes| Event type. The value **change** indicates data change events.|
-| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback used to return data changes. |
+| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback invoked to return the data change. |
**Example**
@@ -894,7 +894,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ------ |---------------------------------------- |
| type | string |Yes| Event type. The value **change** indicates data change events.|
-| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback used to return data changes. |
+| callback | Callback<[StorageObserver](#storageobserver)> | Yes|Callback for the data change. |
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md
index 274836333aa773d32a386ad22b03706e890859c7..46d97bd96c27c9d3f05d519ebde6ff1ed8d3e4c5 100644
--- a/en/application-dev/reference/apis/js-apis-deque.md
+++ b/en/application-dev/reference/apis/js-apis-deque.md
@@ -1,9 +1,5 @@
# @ohos.util.Deque (Linear Container Deque)
-> **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.
-
Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects:
**Queue** follows the principle of FIFO only and allows element removal at the front and insertion at the rear.
@@ -15,6 +11,11 @@ Double-ended queue (deque) is a sequence container implemented based on the queu
This topic uses the following to identify the use of generics:
- T: Type
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+
## Modules to Import
```ts
@@ -269,7 +270,7 @@ deque.insertEnd(4);
deque.insertFront(5);
deque.insertEnd(4);
deque.forEach((value, index) => {
- console.log("value:" + value, index);
+ console.log("value:" + value, "index:" + index);
});
```
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-environment.md b/en/application-dev/reference/apis/js-apis-file-environment.md
index 9c340eef3974ed2875f417c71cb8a5f7dd4b10d8..c87c8465d7909f495baf6babad02e8e5b118424c 100644
--- a/en/application-dev/reference/apis/js-apis-file-environment.md
+++ b/en/application-dev/reference/apis/js-apis-file-environment.md
@@ -4,7 +4,7 @@ The **Environment** module provides APIs for obtaining the root directories of t
> **NOTE**
>
-> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
@@ -26,7 +26,7 @@ Obtains the root directory of the storage. This API uses a promise to return the
| Type | Description |
| --------------------- | ---------------- |
-| Promise<string> | Promise returned with the root directory of the storage.|
+| Promise<string> | Promise used to return the root directory of the storage.|
**Example**
@@ -50,7 +50,7 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------------- |
-| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of the storage.|
+| callback | AsyncCallback<string> | Yes | Asynchronous callback invoked to return the root directory of the storage.|
**Example**
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..306d752c6de0ec32a36b5bc024d8b88b016bcb3d 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]);
+ }
+ }
+ });
+ ```
+
+## fs.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]);
+ }
+ ```
+## fs.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);
+ });
+ ```
+
+## fs.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");
+ }
+ });
+ ```
+
+## fs.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>
@@ -1831,6 +2065,78 @@ Synchronously opens a stream based on the file descriptor.
fs.closeSync(file);
```
+## fs.createWatcher10+
+
+createWatcher(path: string, events: number, listener: WatchEventListener): Watcher
+
+Creates a **Watcher** object to observe file or directory changes.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.FileManagement.File.FileIO
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ---------------------------------------- |
+| path | string | Yes | Path of the file or directory to observe in the application sandbox. |
+| events | number | Yes | Events to observe. Multiple events can be separated|by a bitwise OR operator (|). - **0x1: IN_ACCESS**: A file is accessed. - **0x2: IN_MODIFY**: The file content is modified. - **0x4: IN_ATTRIB**: Metadata is changed. - **0x8: IN_CLOSE_WRITE**: The file opened for writing is closed. - **0x10: IN_CLOSE_NOWRITE**: The file or directory not opened for writing is closed. - **0x20: IN_OPEN**: A file or directory is opened. - **0x40: IN_MOVED_FROM**: A file in the observed directory is moved. - **0x80: IN_MOVED_TO**: A file is moved to the observed directory. - **0x100: IN_CREATE**: A file or directory is created in the observed directory. - **0x200: IN_DELETE**: A file or directory is deleted form the observed directory. - **0x400: IN_DELETE_SELF**: The observed directory is deleted. After the directory is deleted, the listening stops. - **0x800: IN_MOVE_SELF**: The observed file or directory is moved. After the file or directory is moved, the listening continues. - **0xfff: IN_ALL_EVENTS**: All events.|
+| listener | WatchEventListener | Yes | Callback invoked when an observed event occurs. The callback will be invoked each time an observed event occurs. |
+
+**Return value**
+
+| Type | Description |
+| ------------------ | --------- |
+| [Watcher](#watcher10) | **Watcher** object created.|
+
+**Example**
+
+ ```js
+ let filePath = pathDir + "/test.txt";
+ let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
+ let watcher = fs.createWatcher(filePath, 0x2 | 0x10, (watchEvent) => {
+ if (watchEvent.event == 0x2) {
+ console.info(watchEvent.fileName + 'was modified');
+ } else if (watchEvent.event == 0x10) {
+ console.info(watchEvent.fileName + 'was closed');
+ }
+ });
+ watcher.start();
+ fs.writeSync(file.fd, 'test');
+ fs.closeSync(file);
+ watcher.stop();
+ ```
+
+## WatchEventListener10+
+
+(event: WatchEvent): void
+
+Called when an observed event occurs.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.FileManagement.File.FileIO
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ---------------------------------------- |
+| event | WatchEvent | Yes | Event for the callback to invoke. |
+
+## WatchEvent10+
+
+Defines the event to observe.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.FileManagement.File.FileIO
+
+| Name | Type | Readable | Writable | Description |
+| ---- | ------ | ---- | ---- | ------- |
+| fileName | string | Yes | No | Name of the file for which the event occurs.|
+| event | number | Yes | No | Events to observe. For details, see **events** in [createWatcher](#fscreatewatcher10).|
+| cookie | number | Yes | No | Cookie bound with the event. Currently, only the **IN_MOVED_FROM** and **IN_MOVED_TO** events are supported. The **IN_MOVED_FROM** and **IN_MOVED_TO** events of the same file have the same **cookie** value.|
+
## Stat
Represents detailed file information. Before calling any API of the **Stat()** class, use [stat()](#fsstat) to create a **Stat** instance synchronously or asynchronously.
@@ -2354,6 +2660,146 @@ 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");
+ ```
+
+## Watcher10+
+
+Provides APIs for file or directory listening. Before using the APIs of **Watcher** , call **createWatcher()** to create a **Watcher** object.
+
+### start10+
+
+start(): void
+
+Starts file or directory listening.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.FileManagement.File.FileIO
+
+**Example**
+
+ ```js
+ let filePath = pathDir + "/test.txt";
+ let watcher = fs.createWatcher(filePath, 0xfff, () => {});
+ watcher.start();
+ watcher.stop();
+ ```
+
+### stop10+
+
+stop(): void
+
+Stops file or directory listening.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.FileManagement.File.FileIO
+
+**Example**
+
+ ```js
+ let filePath = pathDir + "/test.txt";
+ let watcher = fs.createWatcher(filePath, 0xfff, () => {});
+ watcher.start();
+ watcher.stop();
+ ```
+
## OpenMode
Defines the constants of the **mode** parameter used in **open()**. It species the mode for opening a file.
@@ -2372,3 +2818,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-securityLabel.md b/en/application-dev/reference/apis/js-apis-file-securityLabel.md
index b9071ecc64025491ed21e55490f4753b83440eb1..13fd25683a394092653f3f7f93ef36efdaf37bca 100644
--- a/en/application-dev/reference/apis/js-apis-file-securityLabel.md
+++ b/en/application-dev/reference/apis/js-apis-file-securityLabel.md
@@ -5,7 +5,7 @@ The **securityLabel** module provides APIs for managing data security levels of
> **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).
+> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
@@ -45,7 +45,7 @@ For details about how to obtain the FA model context, see [Context](js-apis-inne
## securityLabel.setSecurityLabel
-setSecurityLabel(path:string, type:dataLevel):Promise<void>
+setSecurityLabel(path:string, type:DataLevel):Promise<void>
Sets a security label for a file in asynchronous mode. This API uses a promise to return the result.
@@ -56,7 +56,7 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
-| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
+| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Return value**
@@ -76,7 +76,7 @@ Sets a security label for a file in asynchronous mode. This API uses a promise t
## securityLabel.setSecurityLabel
-setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void
+setSecurityLabel(path:string, type:DataLevel, callback: AsyncCallback<void>):void
Sets a security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result.
@@ -87,7 +87,7 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro
| Name | Type | Mandatory| Description |
| --------- | ------------------------- | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
-| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
+| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. |
**Example**
@@ -104,7 +104,7 @@ Sets a security label for a file in asynchronous mode. This API uses an asynchro
## securityLabel.setSecurityLabelSync
-setSecurityLabelSync(path:string, type:dataLevel):void
+setSecurityLabelSync(path:string, type:DataLevel):void
Sets a security label for a file in synchronous mode.
@@ -115,7 +115,7 @@ Sets a security label for a file in synchronous mode.
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
-| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
+| type | DataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Example**
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..6238db4bd28dd10cb7ac75014778827eda399f4f 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,8 @@ 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 +219,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 +254,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 (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 +262,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 +313,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 +355,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 (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 +363,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 +413,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 +464,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 +509,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 +541,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 +549,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 +586,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 +594,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 +634,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 +672,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 +703,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 +711,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 +742,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 +750,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 +780,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 +788,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 +820,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 +828,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 +860,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 +868,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 +899,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 +907,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 +938,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 +946,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 +979,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 +987,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 +1030,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 +1046,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 +1067,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 +1077,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-freeInstall.md b/en/application-dev/reference/apis/js-apis-freeInstall.md
index 73d618e2f6eeed9df97b72dd4df8ba5839b1864c..937cc8437c21d80b54b241d746803e0aae9d4f18 100644
--- a/en/application-dev/reference/apis/js-apis-freeInstall.md
+++ b/en/application-dev/reference/apis/js-apis-freeInstall.md
@@ -267,7 +267,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This
| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| bundleName | string | Yes | Bundle name. |
| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. |
-| callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-packInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **BundlePackInfo** object obtained; otherwise, **err** is an error object.|
+| callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **BundlePackInfo** object obtained; otherwise, **err** is an error object.|
**Error codes**
@@ -318,7 +318,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundleFlag**. This API
| Type | Description |
| ---------------------------------------------------------- | ----------------------------------- |
-| Promise<[BundlePackInfo](js-apis-bundleManager-packInfo.md)> | Promise used to return the **BundlePackInfo** object obtained.|
+| Promise<[BundlePackInfo](js-apis-bundleManager-BundlePackInfo.md)> | Promise used to return the **BundlePackInfo** object obtained.|
**Error codes**
diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md
index d39dbd1e6649359d5e6433fe11b0a2d68febf953..807394ad4538e34997ac5b5eb917e47aad295161 100644
--- a/en/application-dev/reference/apis/js-apis-hashmap.md
+++ b/en/application-dev/reference/apis/js-apis-hashmap.md
@@ -1,8 +1,5 @@
# @ohos.util.HashMap (Nonlinear Container HashMap)
-> **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.
-
**HashMap** is a map implemented based on the array, linked list, and red-black tree. It provides efficient data query, insertion, and removal. The elements in a **HashMap** instance are mappings of key-value pairs. Each key must be unique and have only one value.
**HashMap** is faster in accessing data than **[TreeMap](js-apis-treemap.md)**, because the former accesses the keys based on the hash codes, whereas the latter stores and accesses the keys in sorted order.
@@ -15,6 +12,11 @@ This topic uses the following to identify the use of generics:
- K: Key
- V: Value
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+
## Modules to Import
```ts
@@ -482,7 +484,7 @@ let hashMap = new HashMap();
hashMap.set("sparrow", 123);
hashMap.set("gull", 357);
hashMap.forEach((value, key) => {
- console.log("value:" + value, key);
+ console.log("value:" + value, "key:" + key);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md
index f2ece05248321395e2ca3f651ff32a462503d5c4..8d21ef6d1994144aeb89be8d226ef041bdbdb95a 100644
--- a/en/application-dev/reference/apis/js-apis-hashset.md
+++ b/en/application-dev/reference/apis/js-apis-hashset.md
@@ -305,7 +305,7 @@ let hashSet = new HashSet();
hashSet.add("sparrow");
hashSet.add("squirrel");
hashSet.forEach((value, key) => {
- console.log("value:" + value, key);
+ console.log("value:" + value, "key:" + key);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md
index 3735792dd3f5ce66569fbebf3a1036019e7457ed..1a78a92b3269530da9ccf5794254f4a07ea326ed 100644
--- a/en/application-dev/reference/apis/js-apis-http.md
+++ b/en/application-dev/reference/apis/js-apis-http.md
@@ -581,6 +581,8 @@ httpResponseCache.delete().then(() => {
| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. |
| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. |
+For details about the error codes, see [Curl Error Codes] (https://curl.se/libcurl/c/libcurl-errors.html).
+
## HttpDataType9+
Enumerates HTTP data types.
diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md
index cad81d4e80c3303859274b2b79c3258bf8d2556c..0dfcc793a2d005d34501735f320e78ab421b1a08 100644
--- a/en/application-dev/reference/apis/js-apis-huks.md
+++ b/en/application-dev/reference/apis/js-apis-huks.md
@@ -3,7 +3,7 @@
The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations.
The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs.
->  **NOTE**
+> **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.
@@ -1818,9 +1818,9 @@ Enumerates the user authentication types.
| Name | Value | Description |
| ------------------------------- | ---- | ------------------------- |
-| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 | Fingerprint authentication. |
-| HUKS_USER_AUTH_TYPE_FACE | 2 | Facial authentication.|
-| HUKS_USER_AUTH_TYPE_PIN | 4 | PIN authentication.|
+| HUKS_USER_AUTH_TYPE_FINGERPRINT | 1 << 0 | Fingerprint authentication. |
+| HUKS_USER_AUTH_TYPE_FACE | 1 << 1 | Facial authentication.|
+| HUKS_USER_AUTH_TYPE_PIN | 1 << 2 | PIN authentication.|
## HuksAuthAccessType9+
@@ -1830,8 +1830,8 @@ Enumerates the access control types.
| Name | Value | Description |
| --------------------------------------- | ---- | ------------------------------------------------ |
-| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | The key becomes invalid after the password is cleared. |
-| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | The key becomes invalid after a new biometric feature is added.|
+| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 << 0 | The key becomes invalid after the password is cleared. |
+| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 1 << 1 | The key becomes invalid after a new biometric feature is added.|
## HuksChallengeType9+
@@ -1892,7 +1892,7 @@ Enumerates the tags used to invoke parameters.
| Name | Value | Description |
| -------------------------------------------- | ---------------------------------------- | -------------------------------------- |
| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. |
-| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. |
+| HUKS_TAG_ALGORITHM | HuksTagType.HUKS_TAG_TYPE_UINT \| 1 | Algorithm. |
| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of the key. |
| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. |
| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. |
@@ -1922,7 +1922,7 @@ Enumerates the tags used to invoke parameters.
| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. |
| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. |
| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. |
-| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. |
+| HUKS_TAG_ALL_USERS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. |
| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. |
| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. |
| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE\**.| HKS_USER_AUTH_TYPE_FINGERPRINT |
@@ -2889,11 +2889,6 @@ Enumerates the error codes.
| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.|
| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.|
| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.|
-| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.|
-| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.|
-| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.|
-| HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.|
-| HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.|
| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to obtain the ALG. |
| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to obtain the key size.|
| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to obtain the padding algorithm.|
@@ -2920,7 +2915,5 @@ Enumerates the error codes.
| HUKS_ERROR_INVALID_SALT | -123 |Invalid salt value.|
| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration count.|
| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.|
-| HUKS_ERROR_INVALID_WRAPPED_FORMAT9+ | -126 |Incorrect format of the wrapped key being imported.|
-| HUKS_ERROR_INVALID_USAGE_OF_KEY9+ | -127 |Incorrect purpose of the wrapped key being imported.|
| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.|
| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.|
diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md
index cda33f5434360fe5ca3f21f9f2c0a04ad5b50474..02cebd741ce26bd61dd4a4282efcf2cc6d89ad08 100644
--- a/en/application-dev/reference/apis/js-apis-i18n.md
+++ b/en/application-dev/reference/apis/js-apis-i18n.md
@@ -1,6 +1,6 @@
# @ohos.i18n (Internationalization)
-The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402.
+ The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402.
The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities.
> **NOTE**
@@ -53,7 +53,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China"
} catch(error) {
- console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -92,7 +92,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese
} catch(error) {
- console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -100,7 +100,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLanguages(): Array<string>
-Obtains the list of system languages.
+Obtains the list of system languages. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
@@ -123,7 +123,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ]
} catch(error) {
- console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -131,7 +131,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemCountries(language: string): Array<string>
-Obtains the list of countries and regions supported for the specified language.
+Obtains the list of countries and regions supported for the specified language. For details about countries or regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
@@ -160,7 +160,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total
} catch(error) {
- console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -198,7 +198,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let res = I18n.System.isSuggested('zh', 'CN'); // res = true
} catch(error) {
- console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -206,7 +206,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLanguage(): string
-Obtains the system language.
+Obtains the system language. For details about languages, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
@@ -229,7 +229,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language.
} catch(error) {
- console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -264,7 +264,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setSystemLanguage('zh'); // Set the current system language to zh.
} catch(error) {
- console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -272,7 +272,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemRegion(): string
-Obtains the system region.
+Obtains the system region. For details about system regions, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
@@ -295,7 +295,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region.
} catch(error) {
- console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -330,7 +330,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setSystemRegion('CN'); // Set the current system region to CN.
} catch(error) {
- console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -338,7 +338,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getSystemLocale(): string
-Obtains the system locale.
+Obtains the system locale. For details about system locales, see [Instantiating the Locale Object](../../internationalization/intl-guidelines.md#how-to-develop).
**System capability**: SystemCapability.Global.I18n
@@ -361,7 +361,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale.
} catch(error) {
- console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -396,7 +396,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN.
} catch(error) {
- console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -427,7 +427,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled.
} catch(error) {
- console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -463,7 +463,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.set24HourClock(true);
} catch(error) {
- console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -502,7 +502,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list.
} catch(error) {
- console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -539,7 +539,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.removePreferredLanguage(index);
} catch(error) {
- console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -570,7 +570,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list.
} catch(error) {
- console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -601,7 +601,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list.
} catch(error) {
- console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -632,7 +632,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application.
} catch(error) {
- console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -640,7 +640,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static setUsingLocalDigit(flag: boolean): void
-Sets whether to enable the local digit switch.
+Specifies whether to enable use of local digits.
**System API**: This is a system API.
@@ -667,7 +667,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
I18n.System.setUsingLocalDigit(true); // Enable the local digit switch.
} catch(error) {
- console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -675,7 +675,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
static getUsingLocalDigit(): boolean
-Checks whether the local digit switch is turned on.
+Checks whether use of local digits is enabled.
**System capability**: SystemCapability.Global.I18n
@@ -698,7 +698,7 @@ For details about the error codes, see [i18n Error Codes](../errorcodes/errorcod
try {
let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled.
} catch(error) {
- console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -1025,7 +1025,7 @@ Checks whether the specified date in this **Calendar** object is a weekend.
| Name | Type | Mandatory | Description |
| ---- | ---- | ---- | ---------------------------------------- |
-| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.|
+| date | Date | No | Specified date in this **Calendar** object. If the **date** parameter is not specified, the system checks whether the current date is a weekend.|
**Return value**
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..6001a514c8b5f07874460271d0ebce3cf96c0987 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,16 @@ 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, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('openFile fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('openFile success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -69,12 +73,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 +94,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 +102,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 +127,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 +135,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 +171,15 @@ 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', (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getType fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getType success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -199,11 +207,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 +235,15 @@ 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/*', (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getFileTypes fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getFileTypes success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -260,11 +272,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 +299,15 @@ 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', (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('normalizeUri fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('normalizeUri success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -319,11 +335,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 +362,15 @@ 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', (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('denormalizeUri fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('denormalizeUri success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -378,11 +398,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 +425,15 @@ 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', (error) => {
+ if (error && error.code !== 0) {
+ console.error('notifyChange fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('notifyChange success');
+ }
});
```
@@ -437,11 +461,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 +489,21 @@ 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, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('insert fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('insert success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -504,17 +532,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 +566,18 @@ 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, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('batchInsert fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('batchInsert success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -574,14 +606,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 +638,16 @@ 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, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('delete fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('delete success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -641,12 +677,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 +708,22 @@ 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, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('update fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('update success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -714,18 +754,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 +791,17 @@ 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, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('query fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('query success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -790,13 +834,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 +856,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 +868,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) => {
- if (err) {
- console.error('Operation failed. Cause: ' + err);
- return;
+dataAbilityHelper.call('dataability:///com.example.jsapidemo.UserDataAbility',
+ 'method', 'arg', {'key1':'value1'}, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('call fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('call success, data: ${JSON.stringify(data)}');
}
- console.info('Operation succeeded: ' + data);
});
```
@@ -848,7 +892,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 +909,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('call success, data: ${data}');
}).catch((error) => {
- console.error('Operation failed. Cause: ' + error);
+ console.error('call failed, error: ${error}');
});
```
@@ -887,7 +931,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 +943,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) => {
- if (err) {
- console.error('Operation failed. Cause: ' + err);
- return;
+dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbility', op, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('executeBatch fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('executeBatch success, data: ${JSON.stringify(data)}');
}
- console.info('Operation succeeded: ' + data);
});
```
@@ -922,7 +966,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 +983,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('executeBatch success, data: ${data}');
}).catch((error) => {
- console.error('Operation failed. Cause: ' + error);
+ console.error('executeBatch failed, error: ${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..80fcf902d83b94b26cd7f667d971855d4be959b9 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,34 @@ 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));
+ featureAbility.startAbility(startAbilityParameter, (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('startAbility fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('startAbility success, data: ${JSON.stringify(data)}');
+ }
});
} catch(error) {
- console.log("startAbility error: " + JSON.stringify(error));
+ console.error('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..c71633638b2339f0457234c4d49a28330969a483 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,11 +14,11 @@ 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. |
-| 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. |
-| 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). |
+| 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 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#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. - **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#wantConstant.Entity). |
| moduleName9+ | string | No | Module to which the ability belongs.|
**Example**
@@ -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.error('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.error('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.error('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..79fcf1af73e773ca24167bef9f2aa4052d5293a2 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,13 @@ 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();
-context.getOrCreateLocalDir((err, data)=>{
- console.info("getOrCreateLocalDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getOrCreateLocalDir((error, data)=>{
+ if (error && error.code !== 0) {
+ console.error('getOrCreateLocalDir fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getOrCreateLocalDir success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -68,9 +72,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 +99,14 @@ 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}, (error, data) =>{
+ if (error && error.code !== 0) {
+ console.error('verifyPermission fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('verifyPermission success, data: ${JSON.stringify(data)}');
+ }
});
});
```
@@ -125,9 +133,13 @@ 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', (error, data) =>{
+ if (error && error.code !== 0) {
+ console.error('verifyPermission fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('verifyPermission success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -156,10 +168,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 +197,20 @@ 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));
+ (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('requestPermissionsFromUser fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('requestPermissionsFromUser success, data: ${JSON.stringify(data)}');
+ }
}
);
```
@@ -225,15 +241,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 +274,13 @@ Obtains information about the current application. This API uses an asynchronous
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getApplicationInfo((err, data) => {
- console.info("getApplicationInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getApplicationInfo((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getApplicationInfo fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getApplicationInfo success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -284,9 +304,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 +330,13 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getBundleName((err, data) => {
- console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getBundleName((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getBundleName fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getBundleName success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -336,9 +360,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 +384,13 @@ Obtains the display orientation of this ability. This API uses an asynchronous c
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getDisplayOrientation((err, data) => {
- console.info("getDisplayOrientation err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getDisplayOrientation((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getDisplayOrientation fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getDisplayOrientation success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -384,9 +412,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 +436,13 @@ Obtains the external cache directory of the application. This API uses an asynch
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getExternalCacheDir((err, data) => {
- console.info("getExternalCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getExternalCacheDir((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getExternalCacheDir fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getExternalCacheDir success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -432,9 +464,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 +490,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;
-context.setDisplayOrientation(orientation, (err) => {
- console.info("setDisplayOrientation err: " + JSON.stringify(err));
+let context = featureAbility.getContext();
+let orientation = bundle.DisplayOrientation.UNSPECIFIED;
+context.setDisplayOrientation(orientation, (error) => {
+ console.error('setDisplayOrientation fail, error: ${JSON.stringify(error)}');
});
```
@@ -485,10 +517,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 +543,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;
-context.setShowOnLockScreen(show, (err) => {
- console.info("setShowOnLockScreen err: " + JSON.stringify(err));
+let context = featureAbility.getContext();
+let show = true;
+context.setShowOnLockScreen(show, (error) => {
+ console.error('setShowOnLockScreen fail, error: ${JSON.stringify(error)}');
});
```
@@ -542,10 +574,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 +600,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;
-context.setWakeUpScreen(wakeUp, (err) => {
- console.info("setWakeUpScreen err: " + JSON.stringify(err));
+let context = featureAbility.getContext();
+let wakeUp = true;
+context.setWakeUpScreen(wakeUp, (error) => {
+ console.error('setWakeUpScreen fail, error: ${JSON.stringify(error)}');
});
```
@@ -599,10 +631,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 +659,13 @@ Obtains information about the current process, including the PID and process nam
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getProcessInfo((err, data) => {
- console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getProcessInfo((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getProcessInfo fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getProcessInfo success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -653,9 +689,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 +717,13 @@ This API is available only to Page abilities.
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getElementName((err, data) => {
- console.info("getElementName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getElementName((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getElementName fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getElementName success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -709,9 +749,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 +773,13 @@ Obtains the name of the current process. This API uses an asynchronous callback
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getProcessName((err, data) => {
- console.info("getProcessName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getProcessName((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getProcessName fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getProcessName success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -759,9 +803,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 +829,13 @@ 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();
-context.getCallingBundle((err, data) => {
- console.info("getCallingBundle err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getCallingBundle((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getCallingBundle fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getCallingBundle success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -811,9 +859,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 +883,13 @@ Obtains the cache directory of the application in the internal storage. This API
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getCacheDir((err, data) => {
- console.info("getCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getCacheDir((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getCacheDir fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getCacheDir success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -859,9 +911,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 +935,13 @@ Obtains the file directory of the application in the internal storage. This API
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getFilesDir((err, data) => {
- console.info("getFilesDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getFilesDir((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getFilesDir fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getFilesDir success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -907,9 +963,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 +989,13 @@ 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();
-context.getOrCreateDistributedDir((err, data) => {
- console.info("getOrCreateDistributedDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getOrCreateDistributedDir((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getOrCreateDistributedDir fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getOrCreateDistributedDir success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -959,9 +1019,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 +1043,13 @@ Obtains the application type. This API uses an asynchronous callback to return t
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getAppType((err, data) => {
- console.info("getAppType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getAppType((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getAppType fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getAppType success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -1007,9 +1071,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 +1095,13 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getHapModuleInfo((err, data) => {
- console.info("getHapModuleInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getHapModuleInfo((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getHapModuleInfo fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getHapModuleInfo success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -1055,9 +1123,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 +1147,13 @@ Obtains the version information of the application. This API uses an asynchronou
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getAppVersionInfo((err, data) => {
- console.info("getAppVersionInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getAppVersionInfo((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getAppVersionInfo fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getAppVersionInfo success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -1103,9 +1175,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 +1199,13 @@ Obtains information about this ability. This API uses an asynchronous callback t
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.getAbilityInfo((err, data) => {
- console.info("getAbilityInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.getAbilityInfo((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getAbilityInfo fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getAbilityInfo success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -1151,9 +1227,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 +1251,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 +1272,13 @@ Checks whether the configuration of this ability is being updated. This API uses
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var context = featureAbility.getContext();
-context.isUpdatingConfigurations((err, data) => {
- console.info("isUpdatingConfigurations err: " + JSON.stringify(err) + "data: " + JSON.stringify(data));
+let context = featureAbility.getContext();
+context.isUpdatingConfigurations((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('isUpdatingConfigurations fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('isUpdatingConfigurations success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -1220,9 +1300,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 +1324,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 +1348,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 +1373,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..886cc755ef0939723d9c23bc612fe37ce0f7bc55 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,14 @@ The **ProcessInfo** module defines process information. You can use [getProcessI
```ts
import featureAbility from '@ohos.ability.featureAbility';
-var 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;
+let context = featureAbility.getContext();
+context.getProcessInfo((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getProcessInfo fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getProcessInfo success, data: ${JSON.stringify(data)}');
+ let pid = data.pid;
+ let processName = data.processName;
+ }
});
```
diff --git a/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md
new file mode 100644
index 0000000000000000000000000000000000000000..ff2ca7a3df236c2bf50ab883de28cae0b0599259
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md
@@ -0,0 +1,24 @@
+# WorkSchedulerExtensionContext
+
+The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility.
+
+This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility.
+
+> **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 APIs of this module can be used only in the stage model.
+
+## Usage
+
+The context is obtained through a WorkSchedulerExtensionAbility child class instance.
+
+```ts
+import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
+
+class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
+ onWorkStart(workInfo) {
+ let WorkSchedulerExtensionContext = this.context; // Obtain the WorkSchedulerExtensionContext.
+ }
+}
+```
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..051aa07c40253bc6805c57fcdf65aad84f401713 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, data: ${JSON.stringify(data)}');
}
let monitor = {
- abilityName: "abilityname",
+ abilityName: 'abilityname',
onAbilityCreate: onAbilityCreateCallback
-}
+};
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
-abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
- console.info("addAbilityMonitor callback");
+abilityDelegator.addAbilityMonitor(monitor, (error : any) => {
+ console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}');
});
```
@@ -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");
+abilityDelegator.removeAbilityMonitor(monitor, (error : any) => {
+ console.error('removeAbilityMonitor fail, error: ${JSON.stringify(error)}');
});
```
@@ -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,21 @@ 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");
+abilityDelegator.waitAbilityMonitor(monitor, (error : any, data : any) => {
+ if (error && error.code !== 0) {
+ console.error('waitAbilityMonitor fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('waitAbilityMonitor success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -225,17 +229,21 @@ 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");
+abilityDelegator.waitAbilityMonitor(monitor, timeout, (error : any, data : any) => {
+ if (error && error.code !== 0) {
+ console.error('waitAbilityMonitor fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('waitAbilityMonitor success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -268,17 +276,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 +341,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 +370,7 @@ let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err : any, data : any) => {
- console.info("getCurrentTopAbility callback");
+ console.info('getCurrentTopAbility callback');
ability = data;
});
```
@@ -389,7 +397,7 @@ let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility().then((data : any) => {
- console.info("getCurrentTopAbility promise");
+ console.info('getCurrentTopAbility promise');
ability = data;
});
```
@@ -414,13 +422,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 +457,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 +490,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 +526,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 +557,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 +593,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 +619,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 +644,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 +676,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 +703,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 +731,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 +765,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 +794,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 +827,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 +856,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 +892,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 +923,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 +959,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 +990,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 +1031,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 +1068,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..e64c3175c7934190d70af04156c149741c87697c 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,19 @@ Describes an ability monitor.
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
function onAbilityCreateCallback(data) {
- console.info("onAbilityCreateCallback");
+ console.info('onAbilityCreateCallback, data: ${JSON.stringify(data)}');
}
-var monitor = {
- abilityName: "abilityname",
+let monitor = {
+ abilityName: 'abilityname',
+ moduleName: "moduleName",
onAbilityCreate: onAbilityCreateCallback
-}
+};
-var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
-abilityDelegator.addAbilityMonitor(monitor, (err : any) => {
- console.info("addAbilityMonitor callback");
+let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
+abilityDelegator.addAbilityMonitor(monitor, (error : any) => {
+ if (error && error.code !== 0) {
+ console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}');
+ }
});
```
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..f041998eb633cf8d00b45613b666ca563189dd77 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
@@ -30,16 +30,20 @@ The ability running information is obtained by calling [getAbilityRunningInfos](
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
-abilitymanager.getAbilityRunningInfos((err,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));
+abilitymanager.getAbilityRunningInfos((error, data) => {
+ if (error && error.code !== 0) {
+ console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getAbilityRunningInfos success, 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)}');
+ }
}
});
```
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..90fa9dc102e3f38498451bcf23a117321be08be9 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,16 @@ 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));
+ if (error && error.code !== 0) {
+ console.error('waitAbilityStageMonitor fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('waitAbilityStageMonitor success, data: ${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..a24262809348f1a94ce0a8598fdd25e08d7e9302 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.error('failed to get attribute value, because ${JSON.stringify(err)}');
});
} catch (exception) {
- console.log('failed to get attribute value, because ' + JSON.stringify(exception));
+ console.error('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.error('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.error('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.error('failed to perform action, because ${JSON.stringify(err)}');
});
} catch (exception) {
- console.log('failed to perform action, because ' + JSON.stringify(exception));
+ console.error('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.error('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.error('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.error('failed to find element, because ${JSON.stringify(err)}');
});
} catch (exception) {
- console.log('failed to find element, because ' + JSON.stringify(exception));
+ console.error('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.error('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.error('failed to find element, because ${JSON.stringify(err)}');
});
} catch (exception) {
- console.log('failed to find element, because ' + JSON.stringify(exception));
+ console.error('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.error('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.error('failed to find element, because ${JSON.stringify(err)}');
});
} catch (exception) {
- console.log('failed to find element, because ' + JSON.stringify(exception));
+ console.error('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.error('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..dad20d67a6f369ae8c73356e9bff45103ec53495 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 lifecycleId: ${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,57 @@ 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) => {
+ if (error && error.code !== 0) {
+ console.error('unregisterAbilityLifecycleCallback fail, err: ${JSON.stringify(error)}');
+ } else {
+ console.log('unregisterAbilityLifecycleCallback success, data: ${JSON.stringify(data)}');
+ }
});
}
}
```
-## ApplicationContext.registerEnvironmentCallback
+## ApplicationContext.off(type: 'abilityLifecycle', callbackId: 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)
-registerEnvironmentCallback(callback: EnvironmentCallback): **number**;
+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 +169,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 +183,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 = {
+ 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));
+ // 2. Use applicationContext to register a listener for system environment changes.
+ callbackId = applicationContext.on('environment', environmentCallback);
+ console.log('registerEnvironmentCallback callbackId: ${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 +218,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 +227,154 @@ 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) => {
+ if (error && error.code !== 0) {
+ console.error('unregisterEnvironmentCallback fail, err: ${JSON.stringify(error)}');
+ } else {
+ console.log('unregisterEnvironmentCallback success, data: ${JSON.stringify(data)}');
+ }
});
}
}
```
+
+## 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.error('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(error => {
+ if (error && error.code !== 0) {
+ console.error('killAllProcesses fail, error: ${JSON.stringify(error)}');
+ }
+});
+```
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 327415245ddfca715a5cfbce5174303fd0337aab..4b0dc98ea7bb95c66ebfe29cf938d376419a46f0 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
@@ -62,8 +62,7 @@ let bundleContext;
try {
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.error('createBundleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
}
```
@@ -102,11 +101,12 @@ let moduleContext;
try {
moduleContext = this.context.createModuleContext('entry');
} catch (error) {
- console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) +
- ' error.message: ' + JSON.stringify(error.message));
+ console.error('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.
@@ -141,8 +141,7 @@ let moduleContext;
try {
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.error('createModuleContext failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
}
```
@@ -167,7 +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.error('getApplicationContext 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-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md
index b67c612c1b3b6dd82537b6dd5e6e7fcad2d6bdcb..1ada23c202d88e7afa85da2a021130be1a434bc0 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.error('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..5c3200aedcf788ea30bba84156fd623ae7a2138f 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.error('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 85b9503b48dc15a49c19cd74be00f071e93e3969..3d3e1d3190082c757a442371fa671576cc5a6758 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
@@ -23,13 +23,13 @@ import errorManager from '@ohos.app.ability.errorManager';
let observer = {
onUnhandledException(errorMsg) {
- console.log('onUnhandledException, errorMsg: ', errorMsg);
+ console.error('onUnhandledException, errorMsg: ', errorMsg);
}
};
try {
errorManager.on('error', observer);
} catch (error) {
- console.log('registerErrorObserver failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
+ console.error('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..17441d6bb281e87f0ae45c8a4764f657809b7bee 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.error('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..c679a6fe5c87954f27b76531a3d21a3c3726e410 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.error('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.error('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..d7cfc2a25b572c3178c3da71d9e04c5fb9c3a8af 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.error('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.error('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..c0a89f932f5dff0e1c073da07544184079d0284c 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.error('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..143c640c90657ef42cc45e4dc3a83e378f45507d 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,21 @@ 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));
+ (error, data) => {
+ if (error && error.code !== 0) {
+ console.error('startSyncRemoteMissions fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('startSyncRemoteMissions success, 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..cafe6d2675bfd9fe1deae8d548f4d07dc78f2e9b 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.error('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.error('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.error('error: ${paramError.code}, ${paramError.message}');
}
```
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-processInformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md
index 6cecaa946c3c60bd05d106349cdc7ff65c458b1f..d2ee664b5fade510aabf9a0113e4ce406e2f6af4 100644
--- a/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md
+++ b/en/application-dev/reference/apis/js-apis-inner-application-processInformation.md
@@ -14,7 +14,11 @@ The process information is obtained by calling [getRunningProcessInformation](js
import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((error, data) => {
- console.log('error: ${error.code}, data: ${JSON.stringify(data)}');
+ if (error && error.code !== 0) {
+ console.error('getRunningProcessInformation fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('getRunningProcessInformation success, data: ${JSON.stringify(data)}');
+ }
});
```
@@ -28,5 +32,3 @@ appManager.getRunningProcessInformation((error, data) => {
| uid | number | Yes| No| User ID.|
| processName | string | Yes| No| Process name.|
| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.|
-
-
\ No newline at end of file
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 f0025296af4ced3c2c7c344e395478df608366a5..b1441077dc9b63aafab110388ad11114aa62796a 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
@@ -28,6 +28,6 @@ import appManager from '@ohos.app.ability.appManager';
appManager.getProcessRunningInfos().then((data) => {
console.log('success: ${JSON.stringify(data)}');
}).catch((error) => {
- console.log('failed: ${JSON.stringify(error)}');
+ console.error('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..687ccf64618e815fe3f19d261340fcb11fb1ae87 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.error('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.error('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.error('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.error('error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}');
}
```
@@ -171,7 +167,7 @@ Starts an ability. This API uses a promise to return the result.
startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void
-Starts an ability with the start options specified. This API uses an asynchronous callback to return the result.
+Starts an ability. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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 -----------') }
- }
+ onFailed(code) { console.error('----------- 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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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.error('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..ca376d9776ffc064b82468e7c3af596a86faba53 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,16 @@ 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);
+abilityDelegator.executeShellCommand(cmd, (error: any, data: any) => {
+ if (error && error.code !== 0) {
+ console.error('executeShellCommand fail, error: ${JSON.stringify(error)}');
+ } else {
+ console.log('executeShellCommand success, data: ${JSON.stringify(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 f735fb4b0f84720e1150f219b04ff0b79e63b3ed..9960a9bbedd04f2ceb18c3b7d34731df1689228a 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
@@ -1916,7 +1916,7 @@ Sets a label for this UIAbility in the mission. This API uses a promise to retur
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.
+Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. The maximum size of the icon is 600 MB.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -1966,7 +1966,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call
setMissionIcon(icon: image.PixelMap): Promise\;
-Sets an icon for this ability in the mission. This API uses a promise to return the result.
+Sets an icon for this ability in the mission. This API uses a promise to return the result. The maximum size of the icon is 600 MB.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
@@ -2112,7 +2112,7 @@ try {
return;
}
// Carry out normal service processing.
- console.info('requestDialogService succeed, result = ' + JSON.stringify(result));
+ console.info('requestDialogService succeed, result = ${JSON.stringify(result)}');
});
} catch (err) {
// Process input parameter errors.
@@ -2160,7 +2160,7 @@ try {
this.context.requestDialogService(want)
.then((result) => {
// Carry out normal service processing.
- console.info('requestDialogService succeed, result = ' + JSON.stringify(result));
+ console.info('requestDialogService succeed, result = ${JSON.stringify(result)}');
})
.catch((err) => {
// Process service logic errors.
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..b4818183f77657d3852de06570e199086dc70941
--- /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.error('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.error('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 5081673fb64f13171a596fd2ed163d4bd8d3c7c9..c39fa3514e9722ba2d33a7dce55378ecb875e3e6 100644
--- a/en/application-dev/reference/apis/js-apis-installer.md
+++ b/en/application-dev/reference/apis/js-apis-installer.md
@@ -175,7 +175,6 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc
| -------- | ------------------------------------------------------------ |
| 17700004 | The specified user ID is not found. |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
-| 17700101 | The system service is excepted. |
**Example**
@@ -284,7 +283,7 @@ Defines the parameters that need to be specified for bundle installation, uninst
| Name | Type | Mandatory | Description |
| ------------------------------ | ------------------------------ | ------------------ | ------------------ |
-| userId | number | Yes | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#queryosaccountlocalidfromprocess9) to obtain the user of the current process.|
+| userId | number | Yes | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId) to obtain the user of the current process.|
| installFlag | number | Yes | Installation flag. The value **0** means initial installation and **1** means overwrite installation.|
| isKeepData | boolean | Yes | Whether to retain the data directory during bundle uninstall.|
| hashParams | Array<[HashParam](#hashparam)> | Yes| Hash parameters. |
diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md
index 89893c1c97d183c69765535141b2012fae9e080a..057dc7e3f1f52f8d491ed1edf35037d42c7ee337 100644
--- a/en/application-dev/reference/apis/js-apis-lightweightmap.md
+++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md
@@ -747,7 +747,7 @@ let lightWeightMap = new LightWeightMap();
lightWeightMap.set("sparrow", 123);
lightWeightMap.set("gull", 357);
lightWeightMap.forEach((value, key) => {
- console.log("value:" + value, key);
+ console.log("value:" + value, "key:" + key);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md
index 25c7950dc4968bc3f9f33ad6b277ecdc68a6ea09..47295b0dd86d5b805607850b92a9692f71940dc7 100644
--- a/en/application-dev/reference/apis/js-apis-lightweightset.md
+++ b/en/application-dev/reference/apis/js-apis-lightweightset.md
@@ -611,7 +611,7 @@ let lightWeightSet = new LightWeightSet();
lightWeightSet.add("sparrow");
lightWeightSet.add("gull");
lightWeightSet.forEach((value, key) => {
- console.log("value:" + value, key);
+ console.log("value:" + value, "key:" + key);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md
index bc51f25fbb6c54f7fadc6bdd05533113a1c7254c..ceb144301277ac8cdd08f52713ae6cf576817a18 100644
--- a/en/application-dev/reference/apis/js-apis-linkedlist.md
+++ b/en/application-dev/reference/apis/js-apis-linkedlist.md
@@ -1,8 +1,5 @@
# @ohos.util.LinkedList (Linear Container LinkedList)
-> **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.
-
**LinkedList** is implemented based on the doubly linked list. Each node of the doubly linked list has references pointing to the previous element and the next element. When querying an element, the system traverses the list from the beginning or end. **LinkedList** offers efficient insertion and removal operations but supports low query efficiency. **LinkedList** allows null elements.
Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList** is a doubly linked list that supports insertion and removal at both ends.
@@ -14,6 +11,11 @@ Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList*
This topic uses the following to identify the use of generics:
- T: Type
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
+
## Modules to Import
```ts
@@ -505,6 +507,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
| -------- | -------- |
| 10200011 | The removeFirstFound method cannot be bound. |
| 10200010 | Container is empty. |
+| 10200017 | The element does not exist in this container. |
**Example**
@@ -545,6 +548,7 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco
| -------- | -------- |
| 10200011 | The removeLastFound method cannot be bound. |
| 10200010 | Container is empty. |
+| 10200017 | The element does not exist in this container. |
**Example**
@@ -631,7 +635,7 @@ linkedList.add(4);
linkedList.add(5);
linkedList.add(4);
linkedList.forEach((value, index) => {
- console.log("value:" + value, index);
+ console.log("value:" + value, "index:" + index);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md
index bd1272f3a7a48a47f30ba689ff9df972932727d6..295824f50139aca548f3dcd5952ce75c2bec7cfc 100644
--- a/en/application-dev/reference/apis/js-apis-list.md
+++ b/en/application-dev/reference/apis/js-apis-list.md
@@ -1,8 +1,5 @@
# @ohos.util.List (Linear Container List)
-> **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.
-
**List** is implemented based on the singly linked list. Each node has a reference pointing to the next element. When querying an element, the system traverses the list from the beginning. **List** offers efficient insertion and removal operations but supports low query efficiency. **List** allows null elements.
Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **List** is a singly linked list that does not support insertion or removal at both ends.
@@ -12,6 +9,10 @@ Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **Lis
This topic uses the following to identify the use of generics:
- T: Type
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
## Modules to Import
```ts
@@ -505,7 +506,7 @@ list.add(4);
list.add(5);
list.add(4);
list.forEach((value, index) => {
- console.log("value: " + value, index);
+ console.log("value:" + value, "index:" + index);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md
index 057e05ac3fd59f22e9bcea5b0fd6064142e95602..123602526ffa59a7af9f20c7ee7eb0775ffae0e6 100644
--- a/en/application-dev/reference/apis/js-apis-matrix4.md
+++ b/en/application-dev/reference/apis/js-apis-matrix4.md
@@ -19,7 +19,7 @@ import matrix4 from '@ohos.matrix4'
init(array: Array<number>): Matrix4Transit
-Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used.
+Matrix constructor, which is used to create a 4 x 4 matrix by using the input parameter. Column-major order is used.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
@@ -33,7 +33,7 @@ Matrix constructor, which is used to create a 4x4 matrix by using the input para
| Type | Description |
| -------------- | ---------------------------- |
-| Matrix4Transit | 4x4 matrix object created based on the input parameter.|
+| Matrix4Transit | 4 x 4 matrix object created based on the input parameter.|
**array** parameters
@@ -458,7 +458,7 @@ struct Test {
.width('600px')
.height('300px')
.margin({ top: 50 })
- Text(`Coordinates before matrix transformation: [${this.transformPoint}]`)
+ Text(`Coordinates after matrix transformation: [${this.transformPoint}]`)
.fontSize(16)
.margin({ top: 100 })
Image($r("app.media.image"))
diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md
index 5a1dcff96d3f5d3c7e2dc1beeb8038e3b68bb46c..3d29422be8cb7f4c363d3272fa1d00dae4019bc9 100644
--- a/en/application-dev/reference/apis/js-apis-media.md
+++ b/en/application-dev/reference/apis/js-apis-media.md
@@ -1162,7 +1162,7 @@ Unsubscribes from the event that checks whether the bit rate is successfully set
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type, which is **'bitrateDone'** in this case|
+| type | string | Yes | Event type, which is **'bitrateDone'** in this case.|
**Example**
@@ -1720,13 +1720,14 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco
**Example**
```js
+// Configure the parameters based on those supported by the hardware device.
let AVRecorderProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : media.CodecMimeType.AUDIO_AAC,
audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4,
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640,
videoFrameHeight : 480,
@@ -1790,13 +1791,14 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco
**Example**
```js
+// Configure the parameters based on those supported by the hardware device.
let AVRecorderProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : media.CodecMimeType.AUDIO_AAC,
audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4,
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoFrameWidth : 640,
videoFrameHeight : 480,
@@ -2484,7 +2486,7 @@ Describes the audio and video recording parameters.
| audioSourceType | [AudioSourceType](#audiosourcetype9) | No | Type of the audio source to record. This parameter is mandatory for audio recording. |
| videoSourceType | [VideoSourceType](#videosourcetype9) | No | Type of the video source to record. This parameter is mandatory for video recording. |
| profile | [AVRecorderProfile](#avrecorderprofile9) | Yes | Recording profile. This parameter is mandatory. |
-| url | string | Yes | Recording output URL: fd://xx (fd number).  This parameter is mandatory. |
+| url | string | Yes | Recording output URL: fd://xx (fd number).  This parameter is mandatory. |
| rotation | number | No | Rotation angle of the recorded video. The value can only be 0, 90, 180, or 270. |
| location | [Location](#location) | No | Geographical location of the recorded video. |
@@ -2606,13 +2608,14 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco
**Example**
```js
+// Configure the parameters based on those supported by the hardware device.
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
@@ -2676,13 +2679,14 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco
**Example**
```js
+// Configure the parameters based on those supported by the hardware device.
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
- videoBitrate : 48000,
+ videoBitrate : 2000000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
@@ -3801,7 +3805,7 @@ audioPlayer.on('error', (error) => { // Set the 'error' event callback
console.info(`audio error called, error: ${error}`);
});
-// Set the FD (local playback) of the video file selected by the user.
+// Set the FD (local playback) of the audio file selected by the user.
let fdPath = 'fd://';
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md
index 0ee9b746e29fd8bb0473b664a1acabd0f2f157ae..cd52a40c909762b31e033274b2b5193ecf34e6f6 100644
--- a/en/application-dev/reference/apis/js-apis-medialibrary.md
+++ b/en/application-dev/reference/apis/js-apis-medialibrary.md
@@ -34,6 +34,7 @@ This API can be used only in the stage model.
**Example (from API version 9)**
```ts
+// Obtain a MediaLibrary instance. The instance obtained here is used in later.
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
```
@@ -92,46 +93,59 @@ Obtains file assets (also called files). This API uses an asynchronous callback
**Example**
```js
-let fileKeyObj = mediaLibrary.FileKey;
-let imageType = mediaLibrary.MediaType.IMAGE;
-let imagesFetchOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
-};
-media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
- if (fetchFileResult == undefined) {
- console.error('Failed to get fetchFileResult: ' + error);
- return;
- }
- const count = fetchFileResult.getCount();
- if (count < 0) {
- console.error('Failed to get count from fetchFileResult: count: ' + count);
- return;
- }
- if (count == 0) {
- console.info('The count of fetchFileResult is zero');
- return;
- }
-
- console.info('Get fetchFileResult success, count: ' + count);
- fetchFileResult.getFirstObject((err, fileAsset) => {
- if (fileAsset == undefined) {
- console.error('Failed to get first object: ' + err);
+async function example() {
+ let fileKeyObj = mediaLibrary.FileKey;
+ let imageType = mediaLibrary.MediaType.IMAGE;
+ // Create options for fetching the files. The options are used to obtain files of the image type.
+ let imagesFetchOp = {
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ };
+ // Obtain the files in asynchronous callback mode.
+ media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
+ // Check whether the result set of the obtained files is undefined. If yes, the API call fails.
+ if (fetchFileResult == undefined) {
+ console.error('get fetchFileResult failed with error: ' + error);
return;
}
- 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.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
- })
+ // Obtain the total number of files in the result set.
+ const count = fetchFileResult.getCount();
+ // Check whether the number is less than 0. If yes, the API call fails.
+ if (count < 0) {
+ console.error('get count from fetchFileResult failed, count: ' + count);
+ return;
}
+ // Check whether the number is 0. If yes, the API call is successful, but the result set is empty. Check whether the options for fetching the files are correctly set and whether the corresponding files exist on the device.
+ if (count == 0) {
+ console.info('The count of fetchFileResult is zero');
+ return;
+ }
+ console.info('Get fetchFileResult successfully, count: ' + count);
+ // Obtain the first file in the result set in asynchronous callback mode.
+ fetchFileResult.getFirstObject((error, fileAsset) => {
+ // Check whether the first file is undefined. If yes, the API call fails.
+ if (fileAsset == undefined) {
+ console.error('get first object failed with error: ' + error);
+ return;
+ }
+ console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
+ // Call getNextObject to obtain the next file until the last one.
+ for (let i = 1; i < count; i++) {
+ fetchFileResult.getNextObject((error, fileAsset) => {
+ if (fileAsset == undefined) {
+ console.error('get next object failed with error: ' + error);
+ return;
+ }
+ console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
+ })
+ }
+ });
+ // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called.
+ fetchFileResult.close();
});
-});
+}
```
+
### getFileAssets7+
getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult>
@@ -157,38 +171,51 @@ Obtains file assets. This API uses a promise to return the result.
**Example**
```js
-let fileKeyObj = mediaLibrary.FileKey;
-let imageType = mediaLibrary.MediaType.IMAGE;
-let imagesFetchOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
-};
-media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) {
- const count = fetchFileResult.getCount();
- if (count < 0) {
- console.error('Failed to get count from fetchFileResult: count: ' + count);
- return;
- }
- if (count == 0) {
- console.info('The count of fetchFileResult is zero');
- return;
- }
- console.info('Get fetchFileResult success, count: ' + count);
- fetchFileResult.getFirstObject().then(function(fileAsset) {
- console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName);
- for (let i = 1; i < count; i++) {
- fetchFileResult.getNextObject().then(function(fileAsset) {
- console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName);
- }).catch(function(err) {
- console.error('Failed to get next object: ' + err);
- })
+async function example() {
+ let fileKeyObj = mediaLibrary.FileKey;
+ let imageType = mediaLibrary.MediaType.IMAGE;
+ // Create options for fetching the files. The options are used to obtain files of the image type.
+ let imagesFetchOp = {
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ };
+ // Obtain the files in promise mode.
+ media.getFileAssets(imagesFetchOp).then((fetchFileResult) => {
+ // Obtain the total number of files in the result set.
+ const count = fetchFileResult.getCount();
+ // Check whether the number is less than 0. If yes, the API call fails.
+ if (count < 0) {
+ console.error('get count from fetchFileResult failed, count: ' + count);
+ return;
}
- }).catch(function(err) {
- console.error('Failed to get first object: ' + err);
+ // Check whether the number is 0. If yes, the API call is successful, but the result set is empty. Check whether the options for fetching the files are correctly set and whether the corresponding files exist on the device.
+ if (count == 0) {
+ console.info('The count of fetchFileResult is zero');
+ return;
+ }
+ console.info('Get fetchFileResult successfully, count: ' + count);
+ // Obtain the first file in the result set in promise mode.
+ fetchFileResult.getFirstObject().then((fileAsset) => {
+ console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
+ // Call getNextObject to obtain the next file until the last one.
+ for (let i = 1; i < count; i++) {
+ fetchFileResult.getNextObject().then((fileAsset) => {
+ console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('get next object failed with error: ' + error);
+ })
+ }
+ }).catch((error) => {
+ // Calling getFirstObject fails.
+ console.error('get first object failed with error: ' + error);
+ });
+ // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called.
+ fetchFileResult.close();
+ }).catch((error) => {
+ // Calling getFileAssets fails.
+ console.error('get file assets failed with error: ' + error);
});
-}).catch(function(err){
- console.error("Failed to get file assets: " + err);
-});
+}
```
### on8+
@@ -232,7 +259,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb
```js
media.off('imageChange', () => {
- // stop listening success
+ // Stop listening successfully.
})
```
@@ -263,11 +290,11 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE);
- media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => {
+ media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (error, fileAsset) => {
if (fileAsset != undefined) {
console.info('createAsset successfully, message');
} else {
- console.error('createAsset failed, message = ' + err);
+ console.error('createAsset failed with error: ' + error);
}
});
}
@@ -307,8 +334,8 @@ async function example() {
const path = await media.getPublicDirectory(DIR_IMAGE);
media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => {
console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset));
- }).catch((err) => {
- console.error('createAsset failed, message = ' + err);
+ }).catch((error) => {
+ console.error('createAsset failed with error: ' + error);
});
}
```
@@ -349,14 +376,15 @@ async function example() {
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
- console.error('asset not exist')
- return
+ console.error('asset not exist');
+ return;
}
media.deleteAsset(asset.uri).then(() => {
- console.info("deleteAsset successfully");
- }).catch((err) => {
- console.error("deleteAsset failed with error:"+ err);
+ console.info('deleteAsset successfully');
+ }).catch((error) => {
+ console.error('deleteAsset failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -391,16 +419,17 @@ async function example() {
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
- console.error('asset not exist')
- return
+ console.error('asset not exist');
+ return;
}
- media.deleteAsset(asset.uri, (err) => {
- if (err != undefined) {
- console.info("deleteAsset successfully");
+ media.deleteAsset(asset.uri, (error) => {
+ if (error != undefined) {
+ console.error('deleteAsset failed with error: ' + error);
} else {
- console.error("deleteAsset failed with error:"+ err);
+ console.info('deleteAsset successfully');
}
});
+ fetchFileResult.close();
}
```
@@ -423,11 +452,11 @@ Obtains a public directory. This API uses an asynchronous callback to return the
```js
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
-media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => {
+media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => {
if (dicResult == 'Camera/') {
- console.info('mediaLibraryTest : getPublicDirectory passed');
+ console.info('getPublicDirectory DIR_CAMERA successfully');
} else {
- console.error('mediaLibraryTest : getPublicDirectory failed');
+ console.error('getPublicDirectory DIR_CAMERA failed with error: ' + error);
}
});
```
@@ -457,12 +486,15 @@ Obtains a public directory. This API uses a promise to return the result.
```js
async function example() {
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
- const dicResult = await media.getPublicDirectory(DIR_CAMERA);
- if (dicResult == 'Camera/') {
- console.info('MediaLibraryTest : getPublicDirectory');
- } else {
- console.error('MediaLibraryTest : getPublicDirectory failed');
- }
+ media.getPublicDirectory(DIR_CAMERA).then((dicResult) => {
+ if (dicResult == 'Camera/') {
+ console.info('getPublicDirectory DIR_CAMERA successfully');
+ } else {
+ console.error('getPublicDirectory DIR_CAMERA failed');
+ }
+ }).catch((error) => {
+ console.error('getPublicDirectory failed with error: ' + error);
+ });
}
```
@@ -486,19 +518,19 @@ Obtains the albums. This API uses an asynchronous callback to return the result.
**Example**
```js
-let AlbumNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
-};
-media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => {
- if (albumList != undefined) {
- const album = albumList[0];
- console.info('album.albumName = ' + album.albumName);
- console.info('album.count = ' + album.count);
- } else {
- console.error('getAlbum fail, message = ' + err);
- }
-})
+async function example() {
+ let AlbumNoArgsfetchOp = {
+ selections: '',
+ selectionArgs: [],
+ };
+ media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => {
+ if (albumList != undefined) {
+ console.info('getAlbums successfully: ' + JSON.stringify(albumList));
+ } else {
+ console.error('getAlbums failed with error: ' + error);
+ }
+ })
+}
```
### getAlbums7+
@@ -526,15 +558,17 @@ Obtains the albums. This API uses a promise to return the result.
**Example**
```js
-let AlbumNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
-};
-media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){
- console.info("getAlbums successfully:"+ JSON.stringify(albumList));
-}).catch(function(err){
- console.error("getAlbums failed with error: " + err);
-});
+async function example() {
+ let AlbumNoArgsfetchOp = {
+ selections: '',
+ selectionArgs: [],
+ };
+ media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => {
+ console.info('getAlbums successfully: ' + JSON.stringify(albumList));
+ }).catch((error) => {
+ console.error('getAlbums failed with error: ' + error);
+ });
+}
```
### release8+
@@ -550,12 +584,12 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------- |
-| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.|
+| callback | AsyncCallback<void> | Yes | Callback that returns no value.|
**Example**
```js
-media.release((err) => {
+media.release(() => {
// do something
});
```
@@ -604,16 +638,16 @@ Stores a media asset. This API uses an asynchronous callback to return the URI t
```js
let option = {
- src : "/data/storage/el2/base/haps/entry/image.png",
- mimeType : "image/*",
- relativePath : "Pictures/"
+ src : '/data/storage/el2/base/haps/entry/image.png',
+ mimeType : 'image/*',
+ relativePath : 'Pictures/'
};
-mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => {
- if (err) {
- console.error("An error occurred when storing media resources.");
+mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => {
+ if (error) {
+ console.error('storeMediaAsset failed with error: ' + error);
return;
}
- console.info("Media resources stored. ");
+ console.info('Media resources stored. ');
// Obtain the URI that stores the media asset.
});
```
@@ -647,15 +681,15 @@ Stores a media asset. This API uses a promise to return the URI that stores the
```js
let option = {
- src : "/data/storage/el2/base/haps/entry/image.png",
- mimeType : "image/*",
- relativePath : "Pictures/"
+ src : '/data/storage/el2/base/haps/entry/image.png',
+ mimeType : 'image/*',
+ relativePath : 'Pictures/'
};
mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
- console.info("Media resources stored.");
+ console.info('Media resources stored.');
// Obtain the URI that stores the media asset.
-}).catch((err) => {
- console.error("An error occurred when storing media resources.");
+}).catch((error) => {
+ console.error('storeMediaAsset failed with error: ' + error);
});
```
@@ -676,7 +710,7 @@ Starts image preview, with the first image to preview specified. This API can be
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **datashare://**.|
+| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
| index | number | Yes | Index of the first image to preview. |
| callback | AsyncCallback<void> | Yes | Callback used to return the image preview result. If the preview fails, an error message is returned. |
@@ -684,22 +718,22 @@ Starts image preview, with the first image to preview specified. This API can be
```js
let images = [
- "datashare:///media/xxxx/2",
- "datashare:///media/xxxx/3"
+ 'datashare:///media/xxxx/2',
+ 'datashare:///media/xxxx/3'
];
/* Preview online images.
let images = [
- "https://media.xxxx.com/image1.jpg",
- "https://media.xxxx.com/image2.jpg"
+ 'https://media.xxxx.com/image1.jpg',
+ 'https://media.xxxx.com/image2.jpg'
];
*/
let index = 1;
-mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => {
- if (err) {
- console.error("An error occurred when previewing the images.");
+mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => {
+ if (error) {
+ console.error('startImagePreview failed with error: ' + error);
return;
}
- console.info("Succeeded in previewing the images.");
+ console.info('Succeeded in previewing the images.');
});
```
@@ -720,28 +754,28 @@ Starts image preview. This API can be used to preview local images whose URIs st
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **datashare://**.|
+| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
| callback | AsyncCallback<void> | Yes | Callback used to return the image preview result. If the preview fails, an error message is returned. |
**Example**
```js
let images = [
- "datashare:///media/xxxx/2",
- "datashare:///media/xxxx/3"
+ 'datashare:///media/xxxx/2',
+ 'datashare:///media/xxxx/3'
];
/* Preview online images.
let images = [
- "https://media.xxxx.com/image1.jpg",
- "https://media.xxxx.com/image2.jpg"
+ 'https://media.xxxx.com/image1.jpg',
+ 'https://media.xxxx.com/image2.jpg'
];
*/
-mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => {
- if (err) {
- console.error("An error occurred when previewing the images.");
+mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => {
+ if (error) {
+ console.error('startImagePreview failed with error: ' + error);
return;
}
- console.info("Succeeded in previewing the images.");
+ console.info('Succeeded in previewing the images.');
});
```
@@ -762,7 +796,7 @@ Starts image preview, with the first image to preview specified. This API can be
| Name | Type | Mandatory | Description |
| ------ | ------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **https://** or **datashare://**.|
+| images | Array<string> | Yes | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
| index | number | No | Index of the first image to preview. If this parameter is not specified, the default value **0** is used. |
**Return value**
@@ -775,20 +809,20 @@ Starts image preview, with the first image to preview specified. This API can be
```js
let images = [
- "datashare:///media/xxxx/2",
- "datashare:///media/xxxx/3"
+ 'datashare:///media/xxxx/2',
+ 'datashare:///media/xxxx/3'
];
/* Preview online images.
let images = [
- "https://media.xxxx.com/image1.jpg",
- "https://media.xxxx.com/image2.jpg"
+ 'https://media.xxxx.com/image1.jpg',
+ 'https://media.xxxx.com/image2.jpg'
];
*/
let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
- console.info("Succeeded in previewing the images.");
-}).catch((err) => {
- console.error("An error occurred when previewing the images.");
+ console.info('Succeeded in previewing the images.');
+}).catch((error) => {
+ console.error('startImagePreview failed with error: ' + error);
});
```
@@ -816,15 +850,15 @@ Starts media selection. This API uses an asynchronous callback to return the lis
```js
let option : mediaLibrary.MediaSelectOption = {
- type : "media",
+ type : 'media',
count : 2
};
-mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => {
- if (err) {
- console.error("An error occurred when selecting media resources.");
+mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => {
+ if (error) {
+ console.error('startMediaSelect failed with error: ' + error);
return;
}
- console.info("Media resources selected.");
+ console.info('Media resources selected.');
// Obtain the media selection value.
});
```
@@ -858,14 +892,14 @@ Starts media selection. This API uses a promise to return the list of URIs that
```js
let option : mediaLibrary.MediaSelectOption = {
- type : "media",
+ type : 'media',
count : 2
};
mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
- console.info("Media resources selected.");
+ console.info('Media resources selected.');
// Obtain the media selection value.
-}).catch((err) => {
- console.error("An error occurred when selecting media resources.");
+}).catch((error) => {
+ console.error('startMediaSelect failed with error: ' + error);
});
```
@@ -893,14 +927,12 @@ Obtains information about online peer devices. This API uses a promise to return
async function example() {
media.getActivePeers().then((devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.info('get distributed info is undefined!')
+ console.info('get distributed info is undefined!');
}
- }).catch((err) => {
- console.error("get distributed info failed with error:" + err);
+ }).catch((error) => {
+ console.error('get distributed info failed with error: ' + error);
});
}
```
@@ -927,15 +959,13 @@ Obtains information about online peer devices. This API uses an asynchronous cal
```js
async function example() {
- media.getActivePeers((err, devicesInfo) => {
+ media.getActivePeers((error, devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.error('get distributed fail, message = ' + err)
+ console.error('get distributed failed with error: ' + error);
}
- })
+ });
}
```
@@ -964,14 +994,12 @@ Obtains information about all peer devices. This API uses a promise to return th
async function example() {
media.getAllPeers().then((devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.info('get distributed info is undefined!')
+ console.info('get distributed info is undefined!');
}
- }).catch((err) => {
- console.error("get distributed info failed with error: " + err);
+ }).catch((error) => {
+ console.error('get distributed info failed with error: ' + error);
});
}
```
@@ -998,15 +1026,13 @@ Obtains information about online peer devices. This API uses an asynchronous cal
```js
async function example() {
- media.getAllPeers((err, devicesInfo) => {
+ media.getAllPeers((error, devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.error('get distributed fail, message = ' + err)
+ console.error('get distributed failed with error: ' + error);
}
- })
+ });
}
```
@@ -1068,19 +1094,23 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isDirectory((err, isDirectory) => {
- // do something
+ asset.isDirectory((error, isDirectory) => {
+ if (error) {
+ console.error('isDirectory failed with error: ' + error);
+ } else {
+ console.info('isDirectory result:' + isDirectory);
+ }
});
+ fetchFileResult.close();
}
```
@@ -1104,21 +1134,21 @@ Checks whether this file asset is a directory. This API uses a promise to return
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isDirectory().then(function(isDirectory){
- console.info("isDirectory result:"+ isDirectory);
- }).catch(function(err){
- console.error("isDirectory failed with error: " + err);
+ asset.isDirectory().then((isDirectory) => {
+ console.info('isDirectory result:' + isDirectory);
+ }).catch((error) => {
+ console.error('isDirectory failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1142,20 +1172,20 @@ Commits the modification in this file asset to the database. This API uses an as
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle';
asset.commitModify(() => {
- console.info('commitModify success');
+ console.info('commitModify successfully');
});
+ fetchFileResult.close();
}
```
@@ -1179,18 +1209,18 @@ Commits the modification in this file asset to the database. This API uses a pro
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle';
- asset.commitModify();
+ await asset.commitModify();
+ fetchFileResult.close();
}
```
@@ -1200,9 +1230,7 @@ open(mode: string, callback: AsyncCallback<number>): void
Opens this file asset. This API uses an asynchronous callback to return the result.
-> **NOTE**
->
-> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource.
+**NOTE**: When a file is opened in 'w' mode, the returned FD cannot be read. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1222,13 +1250,13 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE);
- const asset = await media.createAsset(mediaType, "image00003.jpg", path);
- asset.open('rw', (openError, fd) => {
- if(fd > 0){
- asset.close(fd);
- }else{
- console.error('File Open Failed!' + openError);
- }
+ const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
+ asset.open('rw', (error, fd) => {
+ if (fd > 0) {
+ asset.close(fd);
+ } else {
+ console.error('File Open failed with error: ' + error);
+ }
});
}
```
@@ -1239,9 +1267,7 @@ open(mode: string): Promise<number>
Opens this file asset. This API uses a promise to return the result.
-> **NOTE**
->
-> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource.
+**NOTE**: When a file is opened in 'w' mode, the returned FD cannot be read. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1266,14 +1292,12 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE);
- const asset = await media.createAsset(mediaType, "image00003.jpg", path);
- asset.open('rw')
- .then((fd) => {
- console.info('File fd!' + fd);
- })
- .catch((err) => {
- console.error('File err!' + err);
- });
+ const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
+ asset.open('rw').then((fd) => {
+ console.info('File open fd: ' + fd);
+ }).catch((error) => {
+ console.error('File open failed with error: ' + error);
+ });
}
```
@@ -1298,30 +1322,28 @@ Closes this file asset. This API uses an asynchronous callback to return the res
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => {
- console.info('File fd!' + fd);
- asset.close(fd, (closeErr) => {
- if (closeErr != undefined) {
- console.error('mediaLibraryTest : close : FAIL ' + closeErr);
- console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL');
+ console.info('File open fd: ' + fd);
+ asset.close(fd, (error) => {
+ if (error) {
+ console.error('asset.close failed with error: ' + error);
} else {
- console.info("=======asset.close success====>");
+ console.info('asset.close successfully');
}
});
- })
- .catch((err) => {
- console.error('File err!' + err);
+ }).catch((error) => {
+ console.error('File open failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1351,31 +1373,26 @@ Closes this file asset. This API uses a promise to return the result.
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => {
console.info('File fd!' + fd);
- asset.close(fd).then((closeErr) => {
- if (closeErr != undefined) {
- console.error('mediaLibraryTest : close : FAIL ' + closeErr);
- console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL');
-
- } else {
- console.info("=======asset.close success====>");
- }
+ asset.close(fd).then(() => {
+ console.info('asset.close successfully');
+ }).catch((closeErr) => {
+ console.error('asset.close fail, closeErr: ' + closeErr);
});
- })
- .catch((err) => {
- console.error('File err!' + err);
+ }).catch((error) => {
+ console.error('open File failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1399,19 +1416,23 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.getThumbnail((err, pixelmap) => {
- console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
+ asset.getThumbnail((error, pixelmap) => {
+ if (error) {
+ console.error('mediaLibrary getThumbnail failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
+ }
});
+ fetchFileResult.close();
}
```
@@ -1439,17 +1460,21 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.getThumbnail(size, (err, pixelmap) => {
- console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
+ asset.getThumbnail(size, (error, pixelmap) => {
+ if (error) {
+ console.error('mediaLibrary getThumbnail failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
+ }
});
+ fetchFileResult.close();
}
```
@@ -1484,19 +1509,17 @@ async function example() {
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.getThumbnail(size)
- .then((pixelmap) => {
- console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
- })
- .catch((err) => {
- console.error('mediaLibraryTest : getThumbnail fail, err: ' + err);
+ asset.getThumbnail(size).then((pixelmap) => {
+ console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
+ }).catch((error) => {
+ console.error('mediaLibrary getThumbnail failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1524,16 +1547,20 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.favorite(true,function(err){
- // do something
+ asset.favorite(true,(error) => {
+ if (error) {
+ console.error('mediaLibrary favorite failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary favorite Successful');
+ }
});
+ fetchFileResult.close();
}
```
@@ -1566,18 +1593,18 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.favorite(true).then(function() {
- console.info("favorite successfully");
- }).catch(function(err){
- console.error("favorite failed with error: " + err);
+ asset.favorite(true).then(() => {
+ console.info('mediaLibrary favorite Successful');
+ }).catch((error) => {
+ console.error('mediaLibrary favorite failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1604,20 +1631,20 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isFavorite((err, isFavorite) => {
- if (isFavorite) {
- console.info('FileAsset is favorite');
- }else{
- console.info('FileAsset is not favorite');
+ asset.isFavorite((error, isFavorite) => {
+ if (error) {
+ console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
}
});
+ fetchFileResult.close();
}
```
@@ -1644,18 +1671,18 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isFavorite().then(function(isFavorite){
- console.info("isFavorite result:"+ isFavorite);
- }).catch(function(err){
- console.error("isFavorite failed with error: " + err);
+ asset.isFavorite().then((isFavorite) => {
+ console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
+ }).catch((error) => {
+ console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1685,17 +1712,20 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.trash(true, trashCallBack);
- function trashCallBack(err, trash) {
- console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash');
- }
+ asset.trash(true, (error) => {
+ if (error) {
+ console.error('mediaLibrary trash failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary trash Successful');
+ }
+ });
+ fetchFileResult.close();
}
```
@@ -1730,18 +1760,18 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.trash(true).then(function() {
- console.info("trash successfully");
- }).catch(function(err){
- console.error("trash failed with error: " + err);
+ asset.trash(true).then(() => {
+ console.info('trash successfully');
+ }).catch((error) => {
+ console.error('trash failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1768,20 +1798,20 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isTrash((err, isTrash) => {
- if (isTrash == undefined) {
- console.error('Failed to get trash state: ' + err);
- return;
- }
- console.info('Get trash state success: ' + isTrash);
+ asset.isTrash((error, isTrash) => {
+ if (error) {
+ console.error('Failed to get trash state failed with error: ' + error);
+ return;
+ }
+ console.info('Get trash state successfully, isTrash result: ' + isTrash);
});
+ fetchFileResult.close();
}
```
@@ -1808,17 +1838,18 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isTrash().then(function(isTrash){
- console.info("isTrash result: " + isTrash);
- }).catch(function(err){
- console.error("isTrash failed with error: " + err);
+ asset.isTrash().then((isTrash) => {
+ console.info('isTrash result: ' + isTrash);
+ }).catch((error) => {
+ console.error('isTrash failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1849,11 +1880,12 @@ async function example() {
let getFileCountOneOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getFileCountOneOp);
const fetchCount = fetchFileResult.getCount();
+ console.info('fetchCount result: ' + fetchCount);
+ fetchFileResult.close();
}
```
@@ -1878,25 +1910,22 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
const fetchCount = fetchFileResult.getCount();
- console.info('mediaLibraryTest : count:' + fetchCount);
+ console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount);
let fileAsset = await fetchFileResult.getFirstObject();
for (var i = 1; i < fetchCount; i++) {
- fileAsset = await fetchFileResult.getNextObject();
- if(i == fetchCount - 1) {
- console.info('mediaLibraryTest : isLast');
- var result = fetchFileResult.isAfterLast();
- console.info('mediaLibraryTest : isAfterLast:' + result);
- console.info('mediaLibraryTest : isAfterLast end');
- fetchFileResult.close();
- }
+ fileAsset = await fetchFileResult.getNextObject();
+ if(i == fetchCount - 1) {
+ var result = fetchFileResult.isAfterLast();
+ console.info('mediaLibrary fileAsset isAfterLast result: ' + result);
+ }
}
+ fetchFileResult.close();
}
```
@@ -1915,10 +1944,9 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.close();
@@ -1946,19 +1974,19 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getFirstObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ fetchFileResult.getFirstObject((error, fileAsset) => {
+ if (error) {
+ console.error('fetchFileResult getFirstObject failed with error: ' + error);
+ return;
+ }
+ console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName);
})
+ fetchFileResult.close();
}
```
@@ -1983,17 +2011,17 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getFirstObject().then(function(fileAsset){
- console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset));
- }).catch(function(err){
- console.error("getFirstObject failed with error: " + err);
+ fetchFileResult.getFirstObject().then((fileAsset) => {
+ console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('getFirstObject failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -2002,6 +2030,9 @@ async function example() {
getNextObject(callback: AsyncCallback<FileAsset>): void
Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.
+> **NOTE**
+>
+> Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2018,20 +2049,24 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getNextObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.log('fileAsset.displayName : ' + fileAsset.displayName);
- })
+ let fileAsset = await fetchFileResult.getFirstObject();
+ if (! fetchFileResult.isAfterLast) {
+ fetchFileResult.getNextObject((error, fileAsset) => {
+ if (error) {
+ console.error('fetchFileResult getNextObject failed with error: ' + error);
+ return;
+ }
+ console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
+ })
+ }
+ fetchFileResult.close();
}
+
```
### getNextObject7+
@@ -2039,6 +2074,9 @@ async function example() {
getNextObject(): Promise<FileAsset>
Obtains the next file asset in the result set. This API uses a promise to return the result.
+> **NOTE**
+>
+> Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
@@ -2055,15 +2093,20 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- const fetchCount = fetchFileResult.getCount();
- console.info('mediaLibraryTest : count:' + fetchCount);
- let fileAsset = await fetchFileResult.getNextObject();
+ let fileAsset = await fetchFileResult.getFirstObject();
+ if (! fetchFileResult.isAfterLast) {
+ fetchFileResult.getNextObject().then((fileAsset) => {
+ console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('fetchFileResult getNextObject failed with error: ' + error);
+ })
+ }
+ fetchFileResult.close();
}
```
@@ -2088,19 +2131,19 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getLastObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ fetchFileResult.getLastObject((error, fileAsset) => {
+ if (error) {
+ console.error('getLastObject failed with error: ' + error);
+ return;
+ }
+ console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
})
+ fetchFileResult.close();
}
```
@@ -2125,13 +2168,17 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- let lastObject = await fetchFileResult.getLastObject();
+ fetchFileResult.getLastObject().then((fileAsset) => {
+ console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('getLastObject failed with error: ' + error);
+ });
+ fetchFileResult.close();
}
```
@@ -2147,7 +2194,7 @@ Obtains a file asset with the specified index in the result set. This API uses a
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------ |
-| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. |
+| index | number | Yes | Index of the file to obtain. The value starts from 0 and must be smaller than the **count** value of the result set. |
| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the last file asset.|
**Example**
@@ -2157,19 +2204,19 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getPositionObject(0, (err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ fetchFileResult.getPositionObject(0, (error, fileAsset) => {
+ if (error) {
+ console.error('getPositionObject failed with error: ' + error);
+ return;
+ }
+ console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
})
+ fetchFileResult.close();
}
```
@@ -2185,7 +2232,7 @@ Obtains a file asset with the specified index in the result set. This API uses a
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | -------------- |
-| index | number | Yes | Index of the file asset to obtain. The value starts from **0**.|
+| index | number | Yes | Index of the file to obtain. The value starts from 0 and must be smaller than the **count** value of the result set.|
**Return value**
@@ -2200,17 +2247,17 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getPositionObject(1) .then(function (fileAsset){
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
- }).catch(function (err) {
- console.error("getFileAssets failed with error: " + err);
+ fetchFileResult.getPositionObject(0).then((fileAsset) => {
+ console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('getPositionObject failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -2226,7 +2273,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------- |
-| callback | AsyncCallback> | Yes | Callback used to return the file assets.|
+| callback | AsyncCallback<Array<[FileAsset](#fileasset7)>> | Yes | Callback used to return the file assets.|
**Example**
@@ -2235,21 +2282,21 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getAllObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
+ fetchFileResult.getAllObject((error, fileAssetList) => {
+ if (error) {
+ console.error('getAllObject failed with error: ' + error);
return;
}
for (let i = 0; i < fetchFileResult.getCount(); i++) {
- console.info('fileAsset.displayName : ' + fileAsset[i].displayName);
+ console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
}
})
+ fetchFileResult.close();
}
```
@@ -2265,7 +2312,7 @@ Obtains all the file assets in the result set. This API uses a promise to return
| Type | Description |
| ---------------------------------------- | --------------------- |
-| Promise> | Promise used to return the file assets.|
+| Promise<Array<[FileAsset](#fileasset7)>> | Promise used to return the file assets.|
**Example**
@@ -2274,13 +2321,19 @@ async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- var data = fetchFileResult.getAllObject();
+ fetchFileResult.getAllObject().then((fileAssetList) => {
+ for (let i = 0; i < fetchFileResult.getCount(); i++) {
+ console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
+ }
+ }).catch((error) => {
+ console.error('getAllObject failed with error: ' + error);
+ });
+ fetchFileResult.close();
}
```
@@ -2329,12 +2382,12 @@ async function example() {
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
album.albumName = 'hello';
- album.commitModify((err) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('Modify successful.');
+ album.commitModify((error) => {
+ if (error) {
+ console.error('commitModify failed with error: ' + error);
+ return;
+ }
+ console.info('commitModify successful.');
})
}
```
@@ -2366,10 +2419,10 @@ async function example() {
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
album.albumName = 'hello';
- album.commitModify().then(function() {
- console.info("commitModify successfully");
- }).catch(function(err){
- console.error("commitModify failed with error: " + err);
+ album.commitModify().then(() => {
+ console.info('commitModify successfully');
+ }).catch((error) => {
+ console.error('commitModify failed with error: ' + error);
});
}
```
@@ -2400,15 +2453,22 @@ async function example() {
selectionArgs: [],
};
let fileNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
+ selections: '',
+ selectionArgs: [],
}
+ // Obtain the albums that meet the retrieval options and return the album list.
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
- album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack);
- function getFileAssetsCallBack(err, fetchFileResult) {
- // do something
- }
+ // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
+ album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
+ if (error) {
+ console.error('album getFileAssets failed with error: ' + error);
+ return;
+ }
+ let count = fetchFileResult.getcount();
+ console.info('album getFileAssets successfully, count: ' + count);
+ });
+ fetchFileResult.close();
}
```
@@ -2442,17 +2502,21 @@ async function example() {
selections: '',
selectionArgs: [],
};
- let fileNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
+ let fileNoArgsfetchOp = {
+ selections: '',
+ selectionArgs: [],
};
+ // Obtain the albums that meet the retrieval options and return the album list.
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
- album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){
- console.info("getFileAssets successfully: " + JSON.stringify(albumFetchFileResult));
- }).catch(function(err){
- console.error("getFileAssets failed with error: " + err);
+ // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
+ album.getFileAssets(fileNoArgsfetchOp).then((albumFetchFileResult) => {
+ let count = fetchFileResult.getcount();
+ console.info('album getFileAssets successfully, count: ' + count);
+ }).catch((error) => {
+ console.error('album getFileAssets failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -2491,32 +2555,32 @@ Enumerates media types.
Enumerates key file information.
> **NOTE**
->
+>
> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Value | Description |
| ------------- | ------------------- | ---------------------------------------------------------- |
-| ID | "file_id" | File ID. |
-| RELATIVE_PATH | "relative_path" | Relative public directory of the file. |
-| DISPLAY_NAME | "display_name" | Display file name. |
-| PARENT | "parent" | Parent directory ID. |
-| 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 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. |
-| DURATION | "duration" | Duration, in ms. |
-| WIDTH | "width" | Image width, in pixels. |
-| HEIGHT | "height" | Image height, in pixels. |
-| ORIENTATION | "orientation" | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
-| ALBUM_ID | "bucket_id" | ID of the album to which the file belongs. |
-| ALBUM_NAME | "bucket_display_name" | Name of the album to which the file belongs. |
+| ID | 'file_id' | File ID. |
+| RELATIVE_PATH | 'relative_path' | Relative public directory of the file. |
+| DISPLAY_NAME | 'display_name' | Display file name. |
+| PARENT | 'parent' | Parent directory ID. |
+| MIME_TYPE | 'mime_type' | Extended file attributes, such as image/, video/, and file/*. |
+| 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 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. |
+| DURATION | 'duration' | Duration, in ms. |
+| WIDTH | 'width' | Image width, in pixels. |
+| HEIGHT | 'height' | Image height, in pixels. |
+| ORIENTATION | 'orientation' | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
+| ALBUM_ID | 'bucket_id' | ID of the album to which the file belongs. |
+| ALBUM_NAME | 'bucket_display_name' | Name of the album to which the file belongs. |
## DirectoryType8+
@@ -2559,9 +2623,9 @@ Describes options for fetching media files.
| Name | Type | Readable| Writable| Description |
| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
-| selections | string | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example: selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
+| selections | string | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example: selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs | Array<string> | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**. Example: selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
-| order | string | Yes | Yes | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example: Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC" Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"|
+| order | string | Yes | Yes | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example: Ascending: order: mediaLibrary.FileKey.DATE_ADDED + ' ASC' Descending: order: mediaLibrary.FileKey.DATE_ADDED + ' DESC'|
| uri8+ | string | Yes | Yes | File URI. |
| networkId8+ | string | Yes | Yes | Network ID of the registered device. |
| extendArgs8+ | string | Yes | Yes | Extended parameters for fetching the files. Currently, no extended parameters are available. |
diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md
index c7b8ecb87cca8ffe72417ca65c07086c8421fae1..94a4257dfcc0af730c79334f61473c4811cb3bfd 100644
--- a/en/application-dev/reference/apis/js-apis-osAccount.md
+++ b/en/application-dev/reference/apis/js-apis-osAccount.md
@@ -304,13 +304,13 @@ Checks whether an OS account is activated. This API uses a promise to return the
}
```
-### checkConstraintEnabled9+
+### checkOsAccountConstraintEnabled9+
-checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback<boolean>): void
+checkOsAccountConstraintEnabled(localId: number, constraint: string, callback: AsyncCallback<boolean>): void
Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
+**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Account.OsAccount
@@ -337,25 +337,25 @@ Checks whether the specified constraint is enabled for an OS account. This API u
let localId = 100;
let constraint = "constraint.wifi";
try {
- accountManager.checkConstraintEnabled(localId, constraint, (err, isEnabled)=>{
+ accountManager.checkOsAccountConstraintEnabled(localId, constraint, (err, isEnabled)=>{
if (err) {
- console.log("checkConstraintEnabled failed, error: " + JSON.stringify(err));
+ console.log("checkOsAccountConstraintEnabled failed, error: " + JSON.stringify(err));
} else {
- console.log("checkConstraintEnabled successfully, isEnabled: " + isEnabled);
+ console.log("checkOsAccountConstraintEnabled successfully, isEnabled: " + isEnabled);
}
});
} catch (err) {
- console.log("checkConstraintEnabled exception: " + JSON.stringify(err));
+ console.log("checkOsAccountConstraintEnabled exception: " + JSON.stringify(err));
}
```
-### checkConstraintEnabled9+
+### checkOsAccountConstraintEnabled9+
-checkConstraintEnabled(localId: number, constraint: string): Promise<boolean>
+checkOsAccountConstraintEnabled(localId: number, constraint: string): Promise<boolean>
Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
+**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
**System capability**: SystemCapability.Account.OsAccount
@@ -387,13 +387,13 @@ Checks whether the specified constraint is enabled for an OS account. This API u
let localId = 100;
let constraint = "constraint.wifi";
try {
- accountManager.checkConstraintEnabled(localId, constraint).then((isEnabled) => {
- console.log("checkConstraintEnabled successfully, isEnabled: " + isEnabled);
+ accountManager.checkOsAccountConstraintEnabled(localId, constraint).then((isEnabled) => {
+ console.log("checkOsAccountConstraintEnabled successfully, isEnabled: " + isEnabled);
}).catch((err) => {
- console.log("checkConstraintEnabled failed, error: " + JSON.stringify(err));
+ console.log("checkOsAccountConstraintEnabled failed, error: " + JSON.stringify(err));
});
} catch (err) {
- console.log("checkConstraintEnabled exception: " + JSON.stringify(err));
+ console.log("checkOsAccountConstraintEnabled exception: " + JSON.stringify(err));
}
```
@@ -973,9 +973,9 @@ Obtains the number of OS accounts created. This API uses a promise to return the
}
```
-### queryOsAccountLocalIdFromProcess9+
+### getOsAccountLocalId9+
-queryOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void
+getOsAccountLocalId(callback: AsyncCallback<number>): void
Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result.
@@ -998,21 +998,21 @@ Obtains the ID of the OS account to which the current process belongs. This API
```js
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.queryOsAccountLocalIdFromProcess((err, localId) => {
+ accountManager.getOsAccountLocalId((err, localId) => {
if (err) {
- console.log("queryOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err));
+ console.log("getOsAccountLocalId failed, error: " + JSON.stringify(err));
} else {
- console.log("queryOsAccountLocalIdFromProcess successfully, localId: " + localId);
+ console.log("getOsAccountLocalId successfully, localId: " + localId);
}
});
} catch (err) {
- console.log("queryOsAccountLocalIdFromProcess exception: " + JSON.stringify(err));
+ console.log("getOsAccountLocalId exception: " + JSON.stringify(err));
}
```
-### queryOsAccountLocalIdFromProcess9+
+### getOsAccountLocalId9+
-queryOsAccountLocalIdFromProcess(): Promise<number>
+getOsAccountLocalId(): Promise<number>
Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result.
@@ -1035,19 +1035,19 @@ Obtains the ID of the OS account to which the current process belongs. This API
```js
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.queryOsAccountLocalIdFromProcess().then((localId) => {
- console.log("queryOsAccountLocalIdFromProcess successfully, localId: " + localId);
+ accountManager.getOsAccountLocalId().then((localId) => {
+ console.log("getOsAccountLocalId successfully, localId: " + localId);
}).catch((err) => {
- console.log("queryOsAccountLocalIdFromProcess failed, error: " + JSON.stringify(err));
+ console.log("getOsAccountLocalId failed, error: " + JSON.stringify(err));
});
} catch (err) {
- console.log('queryOsAccountLocalIdFromProcess exception: ' + JSON.stringify(err));
+ console.log('getOsAccountLocalId exception: ' + JSON.stringify(err));
}
```
-### queryOsAccountLocalIdFromUid9+
+### getOsAccountLocalIdForUid9+
-queryOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void
+getOsAccountLocalIdForUid(uid: number, callback: AsyncCallback<number>): void
Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result.
@@ -1073,20 +1073,20 @@ Obtains the OS account ID based on the process UID. This API uses an asynchronou
let accountManager = account_osAccount.getAccountManager();
let uid = 12345678;
try {
- accountManager.queryOsAccountLocalIdFromUid(uid, (err, localId) => {
+ accountManager.getOsAccountLocalIdForUid(uid, (err, localId) => {
if (err) {
- console.log("queryOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err));
+ console.log("getOsAccountLocalIdForUid failed, error: " + JSON.stringify(err));
}
- console.log("queryOsAccountLocalIdFromUid successfully, localId: " + localId);
+ console.log("getOsAccountLocalIdForUid successfully, localId: " + localId);
});
} catch (err) {
- console.log("queryOsAccountLocalIdFromUid exception: " + JSON.stringify(err));
+ console.log("getOsAccountLocalIdForUid exception: " + JSON.stringify(err));
}
```
-### queryOsAccountLocalIdFromUid9+
+### getOsAccountLocalIdForUid9+
-queryOsAccountLocalIdFromUid(uid: number): Promise<number>
+getOsAccountLocalIdForUid(uid: number): Promise<number>
Obtains the OS account ID based on the process UID. This API uses a promise to return the result.
@@ -1117,19 +1117,19 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r
let accountManager = account_osAccount.getAccountManager();
let uid = 12345678;
try {
- accountManager.queryOsAccountLocalIdFromUid(uid).then((localId) => {
- console.log("queryOsAccountLocalIdFromUid successfully, localId: " + localId);
+ accountManager.getOsAccountLocalIdForUid(uid).then((localId) => {
+ console.log("getOsAccountLocalIdForUid successfully, localId: " + localId);
}).catch((err) => {
- console.log("queryOsAccountLocalIdFromUid failed, error: " + JSON.stringify(err));
+ console.log("getOsAccountLocalIdForUid failed, error: " + JSON.stringify(err));
});
} catch (err) {
- console.log('queryOsAccountLocalIdFromUid exception: ' + JSON.stringify(err));
+ console.log('getOsAccountLocalIdForUid exception: ' + JSON.stringify(err));
}
```
-### queryOsAccountLocalIdFromDomain9+
+### getOsAccountLocalIdForDomain9+
-queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void
+getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void
Obtains the OS account ID based on the domain account information. This API uses an asynchronous callback to return the result.
@@ -1157,21 +1157,21 @@ Obtains the OS account ID based on the domain account information. This API uses
let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'};
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.queryOsAccountLocalIdFromDomain(domainInfo, (err, localId) => {
+ accountManager.getOsAccountLocalIdForDomain(domainInfo, (err, localId) => {
if (err) {
- console.log("queryOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err));
+ console.log("getOsAccountLocalIdForDomain failed, error: " + JSON.stringify(err));
} else {
- console.log("queryOsAccountLocalIdFromDomain successfully, localId: " + localId);
+ console.log("getOsAccountLocalIdForDomain successfully, localId: " + localId);
}
});
} catch (err) {
- console.log('queryOsAccountLocalIdFromDomain exception: ' + JSON.stringify(err));
+ console.log('getOsAccountLocalIdForDomain exception: ' + JSON.stringify(err));
}
```
-### queryOsAccountLocalIdFromDomain9+
+### getOsAccountLocalIdForDomain9+
-queryOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number>
+getOsAccountLocalIdForDomain(domainInfo: DomainAccountInfo): Promise<number>
Obtains the OS account ID based on the domain account information. This API uses a promise to return the result.
@@ -1204,13 +1204,13 @@ Obtains the OS account ID based on the domain account information. This API uses
let accountManager = account_osAccount.getAccountManager();
let domainInfo = {domain: 'testDomain', accountName: 'testAccountName'};
try {
- accountManager.queryOsAccountLocalIdFromDomain(domainInfo).then((localId) => {
- console.log("queryOsAccountLocalIdFromDomain successfully, localId: " + localId);
+ accountManager.getOsAccountLocalIdForDomain(domainInfo).then((localId) => {
+ console.log("getOsAccountLocalIdForDomain successfully, localId: " + localId);
}).catch((err) => {
- console.log("queryOsAccountLocalIdFromDomain failed, error: " + JSON.stringify(err));
+ console.log("getOsAccountLocalIdForDomain failed, error: " + JSON.stringify(err));
});
} catch (err) {
- console.log("queryOsAccountLocalIdFromDomain exception: " + JSON.stringify(err));
+ console.log("getOsAccountLocalIdForDomain exception: " + JSON.stringify(err));
}
```
@@ -1456,9 +1456,9 @@ Obtains information about all the OS accounts created. This API uses a promise t
}
```
-### getActivatedOsAccountIds9+
+### getActivatedOsAccountLocalIds9+
-getActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void
+getActivatedOsAccountLocalIds(callback: AsyncCallback<Array<number>>): void
Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result.
@@ -1481,21 +1481,21 @@ Obtains information about all activated OS accounts. This API uses an asynchrono
```js
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.getActivatedOsAccountIds((err, idArray)=>{
- console.log('getActivatedOsAccountIds err:' + JSON.stringify(err));
- console.log('getActivatedOsAccountIds idArray length:' + idArray.length);
+ accountManager.getActivatedOsAccountLocalIds((err, idArray)=>{
+ console.log('getActivatedOsAccountLocalIds err:' + JSON.stringify(err));
+ console.log('getActivatedOsAccountLocalIds idArray length:' + idArray.length);
for(let i=0;i9+
+### getActivatedOsAccountLocalIds9+
-getActivatedOsAccountIds(): Promise<Array<number>>
+getActivatedOsAccountLocalIds(): Promise<Array<number>>
Obtains information about all activated OS accounts. This API uses a promise to return the result.
@@ -1518,13 +1518,13 @@ Obtains information about all activated OS accounts. This API uses a promise to
```js
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.getActivatedOsAccountIds().then((idArray) => {
- console.log('getActivatedOsAccountIds, idArray: ' + idArray);
+ accountManager.getActivatedOsAccountLocalIds().then((idArray) => {
+ console.log('getActivatedOsAccountLocalIds, idArray: ' + idArray);
}).catch((err) => {
- console.log('getActivatedOsAccountIds err: ' + JSON.stringify(err));
+ console.log('getActivatedOsAccountLocalIds err: ' + JSON.stringify(err));
});
} catch (e) {
- console.log('getActivatedOsAccountIds exception:' + JSON.stringify(e));
+ console.log('getActivatedOsAccountLocalIds exception:' + JSON.stringify(e));
}
```
@@ -2214,9 +2214,9 @@ Sets a profile photo for an OS account. This API uses a promise to return the re
}
```
-### queryOsAccountLocalIdBySerialNumber9+
+### getOsAccountLocalIdForSerialNumber9+
-queryOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void
+getOsAccountLocalIdForSerialNumber(serialNumber: number, callback: AsyncCallback<number>): void
Obtains the OS account ID based on the serial number (SN). This API uses an asynchronous callback to return the result.
@@ -2243,7 +2243,7 @@ Obtains the OS account ID based on the serial number (SN). This API uses an asyn
let accountManager = account_osAccount.getAccountManager();
let serialNumber = 12345;
try {
- accountManager.queryOsAccountLocalIdBySerialNumber(serialNumber, (err, localId)=>{
+ accountManager.getOsAccountLocalIdForSerialNumber(serialNumber, (err, localId)=>{
console.log('ger localId err:' + JSON.stringify(err));
console.log('get localId:' + localId + ' by serialNumber: ' + serialNumber);
});
@@ -2252,9 +2252,9 @@ Obtains the OS account ID based on the serial number (SN). This API uses an asyn
}
```
-### queryOsAccountLocalIdBySerialNumber9+
+### getOsAccountLocalIdForSerialNumber9+
-queryOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number>
+getOsAccountLocalIdForSerialNumber(serialNumber: number): Promise<number>
Obtains the OS account ID based on the SN. This API uses a promise to return the result.
@@ -2286,19 +2286,19 @@ Obtains the OS account ID based on the SN. This API uses a promise to return the
let accountManager = account_osAccount.getAccountManager();
let serialNumber = 12345;
try {
- accountManager.queryOsAccountLocalIdBySerialNumber(serialNumber).then((localId) => {
- console.log('queryOsAccountLocalIdBySerialNumber localId: ' + localId);
+ accountManager.getOsAccountLocalIdForSerialNumber(serialNumber).then((localId) => {
+ console.log('getOsAccountLocalIdForSerialNumber localId: ' + localId);
}).catch((err) => {
- console.log('queryOsAccountLocalIdBySerialNumber err: ' + JSON.stringify(err));
+ console.log('getOsAccountLocalIdForSerialNumber err: ' + JSON.stringify(err));
});
} catch (e) {
- console.log('queryOsAccountLocalIdBySerialNumber exception: ' + JSON.stringify(e));
+ console.log('getOsAccountLocalIdForSerialNumber exception: ' + JSON.stringify(e));
}
```
-### querySerialNumberByOsAccountLocalId9+
+### getSerialNumberForOsAccountLocalId9+
-querySerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void
+getSerialNumberForOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void
Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result.
@@ -2325,7 +2325,7 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch
let accountManager = account_osAccount.getAccountManager();
let localId = 100;
try {
- accountManager.querySerialNumberByOsAccountLocalId(localId, (err, serialNumber)=>{
+ accountManager.getSerialNumberForOsAccountLocalId(localId, (err, serialNumber)=>{
console.log('ger serialNumber err:' + JSON.stringify(err));
console.log('get serialNumber:' + serialNumber + ' by localId: ' + localId);
});
@@ -2334,9 +2334,9 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch
}
```
-### querySerialNumberByOsAccountLocalId9+
+### getSerialNumberForOsAccountLocalId9+
-querySerialNumberByOsAccountLocalId(localId: number): Promise<number>
+getSerialNumberForOsAccountLocalId(localId: number): Promise<number>
Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result.
@@ -2368,13 +2368,13 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise
let accountManager = account_osAccount.getAccountManager();
let localId = 100;
try {
- accountManager.querySerialNumberByOsAccountLocalId(localId).then((serialNumber) => {
- console.log('querySerialNumberByOsAccountLocalId serialNumber: ' + serialNumber);
+ accountManager.getSerialNumberForOsAccountLocalId(localId).then((serialNumber) => {
+ console.log('getSerialNumberForOsAccountLocalId serialNumber: ' + serialNumber);
}).catch((err) => {
- console.log('querySerialNumberByOsAccountLocalId err: ' + JSON.stringify(err));
+ console.log('getSerialNumberForOsAccountLocalId err: ' + JSON.stringify(err));
});
} catch (e) {
- console.log('querySerialNumberByOsAccountLocalId exception:' + JSON.stringify(e));
+ console.log('getSerialNumberForOsAccountLocalId exception:' + JSON.stringify(e));
}
```
@@ -2462,9 +2462,9 @@ Unsubscribes from the OS account activation states, including the states of the
}
```
-### getBundleIdFromUid9+
+### getBundleIdForUid9+
-getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void;
+getBundleIdForUid(uid: number, callback: AsyncCallback<number>): void;
Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result.
@@ -2492,17 +2492,17 @@ Obtains the bundle ID based on the UID. This API uses an asynchronous callback t
let accountManager = account_osAccount.getAccountManager();
let testUid = 1000000;
try {
- accountManager.getBundleIdFromUid(testUid, (err, bundleId) => {
- console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err));
- console.info('getBundleIdFromUid bundleId:' + JSON.stringify(bundleId));
+ accountManager.getBundleIdForUid(testUid, (err, bundleId) => {
+ console.info('getBundleIdForUid errInfo:' + JSON.stringify(err));
+ console.info('getBundleIdForUid bundleId:' + JSON.stringify(bundleId));
});
} catch (e) {
- console.info('getBundleIdFromUid exception:' + JSON.stringify(e));
+ console.info('getBundleIdForUid exception:' + JSON.stringify(e));
}
```
-### getBundleIdFromUid9+
+### getBundleIdForUid9+
-getBundleIdFromUid(uid: number): Promise<number>;
+getBundleIdForUid(uid: number): Promise<number>;
Obtains the bundle ID based on the UID. This API uses a promise to return the result.
@@ -2535,13 +2535,13 @@ Obtains the bundle ID based on the UID. This API uses a promise to return the re
let accountManager = account_osAccount.getAccountManager();
let testUid = 1000000;
try {
- accountManager.getBundleIdFromUid(testUid).then((result) => {
- console.info('getBundleIdFromUid bundleId:' + JSON.stringify(result));
+ accountManager.getBundleIdForUid(testUid).then((result) => {
+ console.info('getBundleIdForUid bundleId:' + JSON.stringify(result));
}).catch((err)=>{
- console.info('getBundleIdFromUid errInfo:' + JSON.stringify(err));
+ console.info('getBundleIdForUid errInfo:' + JSON.stringify(err));
});
} catch (e) {
- console.info('getBundleIdFromUid exception:' + JSON.stringify(e));
+ console.info('getBundleIdForUid exception:' + JSON.stringify(e));
}
```
@@ -2620,9 +2620,9 @@ Checks whether the current process belongs to the main OS account. This API uses
console.info('isMainOsAccount exception:' + JSON.stringify(e));
}
```
-### queryOsAccountConstraintSourceTypes9+
+### getOsAccountConstraintSourceTypes9+
-queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void;
+getOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void;
Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result.
@@ -2653,18 +2653,18 @@ Obtains the constraint source information of an OS account. This API uses an asy
```js
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{
- console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err));
- console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(sourceTypeInfos));
+ accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi',(err,sourceTypeInfos)=>{
+ console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err));
+ console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(sourceTypeInfos));
});
} catch (e) {
- console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e));
+ console.info('getOsAccountConstraintSourceTypes exception:' + JSON.stringify(e));
}
```
-### queryOsAccountConstraintSourceTypes9+
+### getOsAccountConstraintSourceTypes9+
-queryOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>;
+getOsAccountConstraintSourceTypes(localId: number, constraint: string): Promise<Array<ConstraintSourceTypeInfo>>;
Obtains the constraint source information of an OS account. This API uses a promise to return the result.
@@ -2700,13 +2700,13 @@ Obtains the constraint source information of an OS account. This API uses a prom
```js
let accountManager = account_osAccount.getAccountManager();
try {
- accountManager.queryOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => {
- console.info('queryOsAccountConstraintSourceType sourceTypeInfos:' + JSON.stringify(result));
+ accountManager.getOsAccountConstraintSourceTypes(100, 'constraint.wifi').then((result) => {
+ console.info('getOsAccountConstraintSourceTypes sourceTypeInfos:' + JSON.stringify(result));
}).catch((err)=>{
- console.info('queryOsAccountConstraintSourceType errInfo:' + JSON.stringify(err));
+ console.info('getOsAccountConstraintSourceTypes errInfo:' + JSON.stringify(err));
});
} catch (e) {
- console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e));
+ console.info('getOsAccountConstraintSourceTypes exception:' + JSON.stringify(e));
}
```
@@ -2852,7 +2852,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u
> **NOTE**
>
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkConstraintEnabled](#checkconstraintenabled9).
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountConstraintEnabled](#checkosaccountconstraintenabled9).
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
@@ -2889,7 +2889,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u
> **NOTE**
>
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkConstraintEnabled](#checkconstraintenabled9-1).
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [checkOsAccountConstraintEnabled](#checkosaccountconstraintenabled9-1).
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
@@ -3158,7 +3158,7 @@ Obtains the ID of the OS account to which the current process belongs. This API
> **NOTE**
>
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromProcess](#queryosaccountlocalidfromprocess9).
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalId](#getosaccountlocalid9).
**System capability**: SystemCapability.Account.OsAccount
@@ -3189,7 +3189,7 @@ Obtains the ID of the OS account to which the current process belongs. This API
> **NOTE**
>
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromProcess](#queryosaccountlocalidfromprocess9-1).
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalId](#getosaccountlocalid9-1).
**System capability**: SystemCapability.Account.OsAccount
@@ -3218,7 +3218,7 @@ Obtains the OS account ID based on the process UID. This API uses an asynchronou
> **NOTE**
>
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromUid](#queryosaccountlocalidfromuid9).
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForUid](#getosaccountlocalidforuid9).
**System capability**: SystemCapability.Account.OsAccount
@@ -3251,7 +3251,7 @@ Obtains the OS account ID based on the process UID. This API uses a promise to r
> **NOTE**
>
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromUid](#queryosaccountlocalidfromuid9-1).
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForUid](#getosaccountlocalidforuid9-1).
**System capability**: SystemCapability.Account.OsAccount
@@ -3287,7 +3287,7 @@ Obtains the OS account ID based on the domain account information. This API uses
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromDomain](#queryosaccountlocalidfromdomain9).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForDomain](#getosaccountlocalidfordomain9).
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
@@ -3322,7 +3322,7 @@ Obtains the OS account ID based on the domain account information. This API uses
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdFromDomain](#queryosaccountlocalidfromdomain9-1).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForDomain](#getosaccountlocalidfordomain9-1).
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
@@ -3430,7 +3430,7 @@ Obtains information about all activated OS accounts. This API uses an asynchrono
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountIds](#getactivatedosaccountids9).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountLocalIds](#getactivatedosaccountlocalids9).
**System capability**: SystemCapability.Account.OsAccount
@@ -3459,7 +3459,7 @@ queryActivatedOsAccountIds(): Promise<Array<number>>
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountIds](#getactivatedosaccountids9-1).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getActivatedOsAccountLocalIds](#getactivatedosaccountlocalids9-1).
Obtains information about all activated OS accounts. This API uses a promise to return the result.
@@ -3669,7 +3669,7 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [queryOsAccountLocalIdBySerialNumber](#queryosaccountlocalidbyserialnumber9).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForSerialNumber](#getosaccountlocalidforserialnumber9).
**System capability**: SystemCapability.Account.OsAccount
@@ -3695,11 +3695,11 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac
getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number>
-Obtains the OS account ID based on the serial number. This API uses a promise to return the result.
+Obtains the OS account ID based on the SN. 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 [queryOsAccountLocalIdBySerialNumber](#queryosaccountlocalidbyserialnumber9-1).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getOsAccountLocalIdForSerialNumber](#getosaccountlocalidforserialnumber9-1).
**System capability**: SystemCapability.Account.OsAccount
@@ -3735,7 +3735,7 @@ Obtains the SN of an OS account based on the account ID. This API uses an asynch
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [querySerialNumberByOsAccountLocalId](#queryserialnumberbyosaccountlocalid9).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getSerialNumberForOsAccountLocalId](#getserialnumberforosaccountlocalid9).
**System capability**: SystemCapability.Account.OsAccount
@@ -3765,7 +3765,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise
> **NOTE**
>
-> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [querySerialNumberByOsAccountLocalId](#queryserialnumberbyosaccountlocalid9-1).
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getSerialNumberForOsAccountLocalId](#getserialnumberforosaccountlocalid9-1).
**System capability**: SystemCapability.Account.OsAccount
diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md
index 03e049e9a1bb1076f770bd2d89dc25455c453ee6..0a0a8ec3833247e78fe5ea513ab7d9383ebe92ac 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|Result 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-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md
index 8ccc7d7fb4bc1a5f876b8da75c181f8547e32f51..387577bb2409ae399f46a225e53e3d00db9035e6 100644
--- a/en/application-dev/reference/apis/js-apis-plainarray.md
+++ b/en/application-dev/reference/apis/js-apis-plainarray.md
@@ -621,7 +621,7 @@ let plainArray = new PlainArray();
plainArray.add(1, "squirrel");
plainArray.add(2, "sparrow");
plainArray.forEach((value, index) => {
- console.log("value:" + value, index);
+ console.log("value:" + value, "index:" + index);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md
index 318ba307995a44950461ae3b9a43e92743c37364..02dbfe617a26b98d8c0d5b5d533fa16e2bcede04 100755
--- a/en/application-dev/reference/apis/js-apis-process.md
+++ b/en/application-dev/reference/apis/js-apis-process.md
@@ -18,139 +18,117 @@ import process from '@ohos.process';
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
-| egid | number | Yes| No| Effective group identifier (EGID) of a process. **System API**: This is a system API. It is used only to test applications.|
-| euid | number | Yes| No| Effective user identifier (EUID) of a process. **System API**: This is a system API. It is used only to test applications.|
-| gid | number | Yes| No| Group identifier (GID) of a process. **System API**: This is a system API. It is used only to test applications.|
-| uid | number | Yes| No| User identifier (UID) of a process.|
+| egid | number | Yes| No| Effective group identifier (EGID) of the process. **System API**: This is a system API. It is used only to test applications.|
+| euid | number | Yes| No| Effective user identifier (EUID) of the process. **System API**: This is a system API. It is used only to test applications.|
+| gid | number | Yes| No| Group identifier (GID) of the process. **System API**: This is a system API. It is used only to test applications.|
+| uid | number | Yes| No| User identifier (UID) of the process.|
| groups | number[] | Yes| No| Array with supplementary group IDs. **System API**: This is a system API. It is used only to test applications.|
-| pid | number | Yes| No| Process ID (PID) of a process.|
-| ppid | number | Yes| No| Parent process ID (PPID) of a process. **System API**: This is a system API. It is used only to test applications.|
-| tid8+ | number | Yes| No| Thread ID (TID) of a process.|
+| pid | number | Yes| No| Process ID (PID) of the process.|
+| ppid | number | Yes| No| Parent process ID (PPID) of the process. **System API**: This is a system API. It is used only to test applications.|
+| tid8+ | number | Yes| No| Thread ID (TID) of the thread.|
-## ProcessManager9+
+## EventListener
-Provides APIs for throwing exceptions during the addition of a process.
+**System capability**: SystemCapability.Utils.Lang
-### isAppUid9+
+| Name| Description|
+| -------- | -------- |
+| EventListener = (evt: Object) => void | Event to store.|
-isAppUid(v: number): boolean
-Checks whether a UID belongs to this application.
+## process.isIsolatedProcess8+
-**System capability**: SystemCapability.Utils.Lang
+isIsolatedProcess(): boolean
-**Parameters**
+Checks whether this process is isolated.
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| v | number | Yes| UID.|
+**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
-| boolean | Returns **true** if the UID is the application's UID; returns **false** otherwise.|
+| boolean | Returns **true** if the process is isolated; returns **false** otherwise.|
**Example**
```js
-let pro = new process.ProcessManager();
-let result = pro.isAppUid(688);
+let result = process.isIsolatedProcess();
```
-### getUidForName9+
+## process.is64Bit8+
-getUidForName(v: string): number
+is64Bit(): boolean
-Obtains the process UID based on the process name.
+Checks whether this process is running in a 64-bit environment.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| v | string | Yes| Name of a process.|
-
**Return value**
| Type| Description|
| -------- | -------- |
-| number | Process UID.|
+| boolean | Returns **true** if the process is running in a 64-bit environment; returns **false** otherwise.|
**Example**
```js
-let pro = new process.ProcessManager();
-let pres = pro .getUidForName("tool");
+let result = process.is64Bit();
```
-### getThreadPriority9+
+## process.getStartRealtime8+
-getThreadPriority(v: number): number
+getStartRealtime(): number
-Obtains the thread priority based on the specified TID.
+Obtains the duration, in milliseconds, from the time the system starts to the time the process starts.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| v | number | Yes| TID.|
-
**Return value**
| Type| Description|
| -------- | -------- |
-| number | Priority of the thread.|
+| number | Duration obtained, in millisecond.|
**Example**
```js
-let pro = new process.ProcessManager();
-let tid = process.tid;
-let pres = pro.getThreadPriority(tid);
+let realtime = process.getStartRealtime();
```
+## process.getPastCpuTime8+
-### getSystemConfig9+
-
-getSystemConfig(name: number): number
+getPastCpuTime(): number
-Obtains the system configuration.
+Obtains the CPU time (in milliseconds) from the time the process starts to the current time.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| name | number | Yes| System configuration parameter name.|
-
**Return value**
| Type| Description|
| -------- | -------- |
-| number | System configuration obtained.|
+| number | CPU time obtained, in millisecond.|
**Example**
```js
-let pro = new process.ProcessManager();
-let _SC_ARG_MAX = 0;
-let pres = pro.getSystemConfig(_SC_ARG_MAX);
+let result = process.getPastCpuTime() ;
```
-### getEnvironmentVar9+
+## process.runCmd
-getEnvironmentVar(name: string): string
+runCmd(command: string, options?: { timeout?: number, killSignal?: number | string, maxBuffer?: number }): ChildProcess
-Obtains the value of an environment variable.
+Forks a new process to run a shell command and returns the **ChildProcess** object.
+
+**System API**: This is a system API.
+
+It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
@@ -158,29 +136,58 @@ Obtains the value of an environment variable.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| name | string | Yes| Environment variable name.|
+| command | string | Yes| Shell command to run.|
+| options | Object | No| Related parameters.|
+
+**Table 1** options
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| timeout | number | No| Maximum running time (in milliseconds) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.|
+| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.|
+| maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.|
**Return value**
| Type| Description|
| -------- | -------- |
-| string | Value of the environment variable.|
+| [ChildProcess](#childprocess) | **ChildProcess** object.|
**Example**
```js
-let pro = new process.ProcessManager();
-let pres = pro.getEnvironmentVar("PATH");
+let child = process.runCmd('ls', { maxBuffer : 2 });
+let result = child.wait();
+child.getOutput.then(val=>{
+ console.log("child.getOutput = " + val);
+})
```
-### exit9+
+## process.abort
-exit(code: number): void
+abort(): void
-Terminates this process.
+Aborts a process and generates a core file. This method will cause a process to exit immediately. Exercise caution when using this method.
+
+**System capability**: SystemCapability.Utils.Lang
-Exercise caution when using this API.
+**Example**
+
+```js
+process.abort();
+```
+
+
+## process.on
+
+on(type: string, listener: EventListener): void
+
+Stores the events triggered by the user.
+
+**System API**: This is a system API.
+
+It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
@@ -188,21 +195,27 @@ Exercise caution when using this API.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| code | number | Yes| Exit code of the process.|
+| type | string | Yes| Type of the events to store. |
+| listener | [EventListener](#eventlistener) | Yes| Callback invoked to return the event.|
**Example**
```js
-let pro = new process.ProcessManager();
-pro.exit(0);
+process.on("data", (e)=>{
+ console.log("data callback");
+})
```
-### kill9+
+## process.off
-kill(signal: number, pid: number): boolean
+off(type: string): boolean
-Sends a signal to the specified process to terminate it.
+Deletes the event stored by the user.
+
+**System API**: This is a system API.
+
+It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
@@ -210,45 +223,29 @@ Sends a signal to the specified process to terminate it.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| pid | number | Yes| PID of the process, to which the signal will be sent.|
-| signal | number | Yes| Signal to send.|
+| type | string | Yes| Type of the event to delete.|
**Return value**
| Type| Description|
| -------- | -------- |
-| boolean | Returns **true** if the signal is sent successfully; returns **false** otherwise.|
+| boolean | Returns **true** if the event is deleted; returns **false** otherwise.|
**Example**
```js
-let pro = new process.ProcessManager();
-let pres = process.pid;
-let result = pro.kill(28, pres);
+process.on("data", (e)=>{
+ console.log("data callback");
+})
+let result = process.off("data");
```
-## ChildProcess
-
-Allows a process to obtain the standard input and output of its child processes, send signals, and close its child processes.
-
-### Attributes
-
-**System capability**: SystemCapability.Utils.Lang
-
-| Name| Type| Readable| Writable| Description|
-| -------- | -------- | -------- | -------- | -------- |
-| pid | number | Yes| No| PID of the child process. **System API**: This is a system API. It is used only to test applications.|
-| ppid | number | Yes| No| PPID of the child process. **System API**: This is a system API. It is used only to test applications.|
-| exitCode | number | Yes| No| Exit code of the child process. **System API**: This is a system API. It is used only to test applications.|
-| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it. **System API**: This is a system API. It is used only to test applications.|
-
-
-### wait
+## process.cwd
-wait(): Promise<number>
+cwd(): string
-Waits until the child process ends. This method uses a promise to return the exit code of the child process.
+Obtains the working directory of this process.
**System API**: This is a system API.
@@ -260,24 +257,20 @@ It is used only to test applications.
| Type| Description|
| -------- | -------- |
-| Promise<number> | Promise used to return the exit code of the child process.|
+| string| Working directory obtained.|
**Example**
```js
-let child = process.runCmd('ls');
-let result = child.wait();
-result.then(val=>{
- console.log("result = " + val);
-})
+let path = process.cwd();
```
-### getOutput
+## process.chdir
-getOutput(): Promise<Uint8Array>
+chdir(dir: string): void
-Obtains the standard output of the child process.
+Changes the working directory of this process.
**System API**: This is a system API.
@@ -285,81 +278,109 @@ It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| dir | string | Yes| Path|
+
+**Example**
+
+```js
+process.chdir('/system');
+```
+
+
+## process.uptime
+
+uptime(): number
+
+Obtains the running time of this process.
+
+**System capability**: SystemCapability.Utils.Lang
+
**Return value**
| Type| Description|
| -------- | -------- |
-| Promise<Uint8Array> | Promise used to return the standard output in a Uint8Array.|
+| number | Running time of the process, in seconds.|
**Example**
```js
-let child = process.runCmd('ls');
-let result = child.wait();
-child.getOutput().then(val=>{
- console.log("child.getOutput = " + val);
-})
+let time = process.uptime();
```
-### getErrorOutput
+## process.kill(deprecated)
-getErrorOutput(): Promise<Uint8Array>
-
-Obtains the standard error output of the child process.
+kill(signal: number, pid: number): boolean
-**System API**: This is a system API.
+Sends a signal to the specified process to terminate it.
-It is used only to test applications.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [kill9+](#kill9) instead.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| pid | number | Yes| PID of the process, to which the signal will be sent.|
+| signal | number | Yes| Signal to send.|
+
**Return value**
| Type| Description|
| -------- | -------- |
-| Promise<Uint8Array> | Promise used to return the standard error output in a Uint8Array.|
+| boolean | Returns **true** if the signal is sent successfully; returns **false** otherwise.|
**Example**
```js
-let child = process.runCmd('madir test.text');
-let result = child.wait();
-child.getErrorOutput().then(val=>{
- console.log("child.getErrorOutput= " + val);
-})
+let pres = process.pid
+let result = process.kill(28, pres)
```
-### close
+## process.exit(deprecated)
-close(): void
+exit(code: number): void
-Closes the child process in running.
+Terminates this process.
-**System API**: This is a system API.
+Exercise caution when using this API. After this API is called, the application exits. If the input parameter is not 0, data loss or exceptions may occur.
-It is used only to test applications.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [exit9+](#exit9) instead.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| code | number | Yes| Exit code of the process.|
+
**Example**
```js
-let child = process.runCmd('sleep 5; ls');
-child.close();
+process.exit(0);
```
-### kill
-
-kill(signal: number | string): void
+## process.getUidForName(deprecated)
-Sends a signal to the specified child process to terminate it.
+getUidForName(v: string): number
-**System API**: This is a system API.
+Obtains the process UID based on the process name.
-It is used only to test applications.
+> **NOTE**
+>
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUidForName9+](#getuidforname9) instead.
**System capability**: SystemCapability.Utils.Lang
@@ -367,43 +388,63 @@ It is used only to test applications.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| signal | number \| string | Yes| Number or string to send.|
+| v | string | Yes| Name of a process.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| number | Process UID.|
**Example**
```js
-let child = process.runCmd('sleep 5; ls');
-child.kill(9);
+let pres = process.getUidForName("tool")
```
-## process.isIsolatedProcess8+
+## process.getThreadPriority(deprecated)
-isIsolatedProcess(): boolean
+getThreadPriority(v: number): number
-Checks whether this process is isolated.
+Obtains the thread priority based on the specified TID.
+
+> **NOTE**
+>
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getThreadPriority9+](#getthreadpriority9) instead.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| v | number | Yes| TID.|
+
**Return value**
| Type| Description|
| -------- | -------- |
-| boolean | Returns **true** if the process is isolated; returns **false** otherwise.|
+| number | Priority of the thread.|
**Example**
```js
-let result = process.isIsolatedProcess();
+let tid = process.tid;
+let pres = process.getThreadPriority(tid);
```
-## process.isAppUid8+
+## process.isAppUid(deprecated)
isAppUid(v: number): boolean
Checks whether a UID belongs to this application.
+> **NOTE**
+>
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isAppUid9+](#isappuid9) instead.
+
**System capability**: SystemCapability.Utils.Lang
**Parameters**
@@ -416,7 +457,7 @@ Checks whether a UID belongs to this application.
| Type| Description|
| -------- | -------- |
-| boolean | Returns **true** if the UID is the application's UID; returns **false** otherwise.|
+| boolean | Returns **true** if the UID belongs to the application; returns **false** otherwise.|
**Example**
@@ -425,32 +466,47 @@ let result = process.isAppUid(688);
```
-## process.is64Bit8+
+## process.getSystemConfig(deprecated)
-is64Bit(): boolean
+getSystemConfig(name: number): number
-Checks whether this process is running in a 64-bit environment.
+Obtains the system configuration.
+
+> **NOTE**
+>
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getSystemConfig9+](#getsystemconfig9) instead.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| name | number | Yes| System configuration parameter name.|
+
**Return value**
| Type| Description|
| -------- | -------- |
-| boolean | Returns **true** if the process is running in a 64-bit environment; returns **false** otherwise.|
+| number | System configuration obtained.|
**Example**
```js
-let result = process.is64Bit();
+let _SC_ARG_MAX = 0
+let pres = process.getSystemConfig(_SC_ARG_MAX)
```
-## process.getUidForName8+
+## process.getEnvironmentVar(deprecated)
-getUidForName(v: string): number
+getEnvironmentVar(name: string): string
-Obtains the process UID based on the process name.
+Obtains the value of an environment variable.
+
+> **NOTE**
+>
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getEnvironmentVar9+](#getenvironmentvar9) instead.
**System capability**: SystemCapability.Utils.Lang
@@ -458,26 +514,32 @@ Obtains the process UID based on the process name.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| v | string | Yes| Name of a process.|
+| name | string | Yes| Environment variable name.|
**Return value**
| Type| Description|
| -------- | -------- |
-| number | Process UID.|
+| string | Value of the environment variable.|
**Example**
```js
-let pres = process.getUidForName("tool")
+let pres = process.getEnvironmentVar("PATH")
```
-## process.getThreadPriority8+
+## ProcessManager9+
+
+Provides APIs for throwing exceptions during the addition of a process.
+
+A **ProcessManager** object is obtained through its own constructor.
+
+### isAppUid9+
-getThreadPriority(v: number): number
+isAppUid(v: number): boolean
-Obtains the thread priority based on the specified TID.
+Checks whether a UID belongs to this application.
**System capability**: SystemCapability.Utils.Lang
@@ -485,64 +547,80 @@ Obtains the thread priority based on the specified TID.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| v | number | Yes| TID.|
+| v | number | Yes| UID.|
**Return value**
| Type| Description|
| -------- | -------- |
-| number | Priority of the thread.|
+| boolean | Returns **true** if the UID belongs to the application; returns **false** otherwise.|
**Example**
```js
-let tid = process.tid;
-let pres = process.getThreadPriority(tid);
+let pro = new process.ProcessManager();
+let result = pro.isAppUid(688);
```
-## process.getStartRealtime8+
+### getUidForName9+
-getStartRealtime(): number
+getUidForName(v: string): number
-Obtains the duration, in milliseconds, from the time the system starts to the time the process starts.
+Obtains the process UID based on the process name.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| v | string | Yes| Name of a process.|
+
**Return value**
| Type| Description|
| -------- | -------- |
-| number | Duration obtained.|
+| number | Process UID.|
**Example**
```js
-let realtime = process.getStartRealtime();
+let pro = new process.ProcessManager();
+let pres = pro .getUidForName("tool");
```
-## process.getPastCpuTime8+
-getPastCpuTime(): number
+### getThreadPriority9+
-Obtains the CPU time (in milliseconds) from the time the process starts to the current time.
+getThreadPriority(v: number): number
+
+Obtains the thread priority based on the specified TID.
**System capability**: SystemCapability.Utils.Lang
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| v | number | Yes| TID.|
+
**Return value**
| Type| Description|
| -------- | -------- |
-| number | CPU time obtained.|
+| number | Priority of the thread.|
**Example**
```js
-let result = process.getPastCpuTime() ;
+let pro = new process.ProcessManager();
+let tid = process.tid;
+let pres = pro.getThreadPriority(tid);
```
-## process.getSystemConfig8+
+### getSystemConfig9+
getSystemConfig(name: number): number
@@ -565,12 +643,13 @@ Obtains the system configuration.
**Example**
```js
-let _SC_ARG_MAX = 0
-let pres = process.getSystemConfig(_SC_ARG_MAX)
+let pro = new process.ProcessManager();
+let _SC_ARG_MAX = 0;
+let pres = pro.getSystemConfig(_SC_ARG_MAX);
```
-## process.getEnvironmentVar8+
+### getEnvironmentVar9+
getEnvironmentVar(name: string): string
@@ -593,19 +672,18 @@ Obtains the value of an environment variable.
**Example**
```js
-let pres = process.getEnvironmentVar("PATH")
+let pro = new process.ProcessManager();
+let pres = pro.getEnvironmentVar("PATH");
```
-## process.runCmd
-
-runCmd(command: string, options?: { timeout?: number, killSignal?: number | string, maxBuffer?: number }): ChildProcess
+### exit9+
-Forks a new process to run a shell command and returns the **ChildProcess** object.
+exit(code: number): void
-**System API**: This is a system API.
+Terminates this process.
-It is used only to test applications.
+Exercise caution when using this API. After this API is called, the application exits. If the input parameter is not 0, data loss or exceptions may occur.
**System capability**: SystemCapability.Utils.Lang
@@ -613,54 +691,71 @@ It is used only to test applications.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| command | string | Yes| Shell command to run.|
-| options | Object | No| Related parameters.|
+| code | number | Yes| Exit code of the process.|
-**Table 1** options
+**Example**
+
+```js
+let pro = new process.ProcessManager();
+pro.exit(0);
+```
+
+
+### kill9+
+
+kill(signal: number, pid: number): boolean
+
+Sends a signal to the specified process to terminate it.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.|
-| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.|
-| maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.|
+| pid | number | Yes| PID of the process, to which the signal will be sent.|
+| signal | number | Yes| Signal to send.|
**Return value**
| Type| Description|
| -------- | -------- |
-| [ChildProcess](#childprocess) | **ChildProcess** object.|
+| boolean | Returns **true** if the signal is sent successfully; returns **false** otherwise.|
**Example**
```js
-let child = process.runCmd('ls', { maxBuffer : 2 });
-let result = child.wait();
-child.getOutput.then(val=>{
- console.log("child.getOutput = " + val);
-})
+let pro = new process.ProcessManager();
+let pres = process.pid;
+let result = pro.kill(28, pres);
```
-## process.abort
+## ChildProcess
-abort(): void
+The **ChildProcess** object is a new child process and can be obtained by calling [process.runCmd](#processruncmd). The main process can obtain the standard input and output of the child process, send signals to the child process, and close the child process.
-Aborts a process and generates a core file. This method will cause a process to exit immediately. Exercise caution when using this method.
+**System API**: This is a system API.
-**System capability**: SystemCapability.Utils.Lang
+### Attributes
-**Example**
+**System API**: This is a system API.
-```js
-process.abort();
-```
+**System capability**: SystemCapability.Utils.Lang
+
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| pid | number | Yes| No| PID of the child process. **System API**: This is a system API. It is used only to test applications.|
+| ppid | number | Yes| No| PPID of the child process. **System API**: This is a system API. It is used only to test applications.|
+| exitCode | number | Yes| No| Exit code of the child process. **System API**: This is a system API. It is used only to test applications.|
+| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it. **System API**: This is a system API. It is used only to test applications.|
-## process.on
+### wait
-on(type: string, listener: EventListener): void
+wait(): Promise<number>
-Stores the events triggered by the user.
+Waits until the child process ends. This method uses a promise to return the exit code of the child process.
**System API**: This is a system API.
@@ -668,33 +763,28 @@ It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| type | string | Yes| Type of the events to store. |
-| listener | EventListener | Yes| Callback invoked to return the event.|
-
-**Table 2** EventListener
+**Return value**
-| Name| Description|
+| Type| Description|
| -------- | -------- |
-| EventListener = (evt: Object) => void | Event to store.|
+| Promise<number> | Promise used to return the exit code of the child process.|
**Example**
```js
-process.on("data", (e)=>{
- console.log("data callback");
+let child = process.runCmd('ls');
+let result = child.wait();
+result.then(val=>{
+ console.log("result = " + val);
})
```
-## process.off
+### getOutput
-off(type: string): boolean
+getOutput(): Promise<Uint8Array>
-Deletes the event stored by the user.
+Obtains the standard output of the child process.
**System API**: This is a system API.
@@ -702,56 +792,57 @@ It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| type | string | Yes| Type of the event to delete.|
-
**Return value**
| Type| Description|
| -------- | -------- |
-| boolean | Returns **true** if the event is deleted; returns **false** otherwise.|
+| Promise<Uint8Array> | Promise used to return the standard output in a Uint8Array.|
**Example**
```js
-process.on("data", (e)=>{
- console.log("data callback");
+let child = process.runCmd('ls');
+let result = child.wait();
+child.getOutput().then(val=>{
+ console.log("child.getOutput = " + val);
})
-let result = process.off("data");
```
-## process.exit
+### getErrorOutput
-exit(code: number): void
+getErrorOutput(): Promise<Uint8Array>
-Terminates this process.
+Obtains the standard error output of the child process.
+
+**System API**: This is a system API.
-Exercise caution when using this API.
+It is used only to test applications.
**System capability**: SystemCapability.Utils.Lang
-**Parameters**
+**Return value**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| code | number | Yes| Exit code of the process.|
+| Type| Description|
+| -------- | -------- |
+| Promise<Uint8Array> | Promise used to return the standard error output in a Uint8Array.|
**Example**
```js
-process.exit(0);
+let child = process.runCmd('madir test.text');
+let result = child.wait();
+child.getErrorOutput().then(val=>{
+ console.log("child.getErrorOutput= " + val);
+})
```
-## process.cwd
+### close
-cwd(): string
+close(): void
-Obtains the working directory of this process.
+Closes the child process in running.
**System API**: This is a system API.
@@ -762,15 +853,16 @@ It is used only to test applications.
**Example**
```js
-let path = process.cwd();
+let child = process.runCmd('sleep 5; ls');
+child.close();
```
-## process.chdir
+### kill
-chdir(dir: string): void
+kill(signal: number | string): void
-Changes the working directory of this process.
+Sends a signal to the specified child process to terminate it.
**System API**: This is a system API.
@@ -782,60 +874,11 @@ It is used only to test applications.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| dir | string | Yes| Path|
-
-**Example**
-
-```js
-process.chdir('/system');
-```
-
-
-## process.uptime
-
-uptime(): number
-
-Obtains the running time of this process.
-
-**System capability**: SystemCapability.Utils.Lang
-
-**Return value**
-
-| Type| Description|
-| -------- | -------- |
-| number | Running time of the process, in seconds.|
-
-**Example**
-
-```js
-let time = process.uptime();
-```
-
-
-## process.kill
-
-kill(signal: number, pid: number): boolean
-
-Sends a signal to the specified process to terminate it.
-
-**System capability**: SystemCapability.Utils.Lang
-
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| pid | number | Yes| PID of the process, to which the signal will be sent.|
-| signal | number | Yes| Signal to send.|
-
-**Return value**
-
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the signal is sent successfully; returns **false** otherwise.|
+| signal | number \| string | Yes| Number or string to send.|
**Example**
```js
-let pres = process.pid
-let result = process.kill(28, pres)
+let child = process.runCmd('sleep 5; ls');
+child.kill(9);
```
diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md
index e4adf559e862ddc954b7e75c3253fb8aa95b6b2a..56bb71d5b88e93c2364c23176543f131d134e9f2 100644
--- a/en/application-dev/reference/apis/js-apis-queue.md
+++ b/en/application-dev/reference/apis/js-apis-queue.md
@@ -201,7 +201,7 @@ queue.add(4);
queue.add(5);
queue.add(4);
queue.forEach((value, index) => {
- console.log("value:" + value, index);
+ console.log("value:" + value, "index:" + index);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md
index f443c028e40072e8b402f93b54be1e9ecfdc0842..7d56973be54adf176ce6c22519cb125079f19df3 100644
--- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md
+++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md
@@ -1,4 +1,4 @@
-# @ohos.reminderAgentManager (Reminder Agent Management)
+# @ohos.reminderAgentManager (reminderAgentManager)
The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent.
@@ -696,8 +696,8 @@ Sets the time information for a calendar reminder.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| year | number | Yes| Year.|
-| month | number | Yes| Month.|
-| day | number | Yes| Date.|
-| hour | number | Yes| Hour.|
-| minute | number | Yes| Minute.|
-| second | number | No| Second.|
+| month | number | Yes| Month. The value ranges from 1 to 12.|
+| day | number | Yes| Day. The value ranges from 1 to 31.|
+| hour | number | Yes| Hour. The value ranges from 0 to 23.|
+| minute | number | Yes| Minute. The value ranges from 0 to 59.|
+| second | number | No| Second. The value ranges from 0 to 59.|
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-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
index 0e7ad7e7c38f32e85af6ab3504252da38afb32eb..eb4c8609bbec28c19d441f065d94c716e13c2e31 100644
--- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
+++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
@@ -430,7 +430,7 @@ Provides detailed information about the task. For details about the constraints
| isPersisted | boolean | No | Whether to enable persistent storage for the task. |
| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. |
| idleWaitTime | number | No | Time to wait in the idle state. |
-| parameters | {[key: string]: any} | No | Carried parameters. |
+| parameters | {[key: string]: number | string | boolean} | No | Carried parameters. |
## NetworkType
Enumerates the network types that can trigger the task.
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-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md
index 309a1bc64491497bf61aaf6f2695a9d5c4fbd9d4..8b760e7cb48b3031e728ec80cc2c178501abb677 100644
--- a/en/application-dev/reference/apis/js-apis-screenshot.md
+++ b/en/application-dev/reference/apis/js-apis-screenshot.md
@@ -37,10 +37,10 @@ Describes the region of the screen to capture.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
-| left | number | Yes | Left boundary of the screen region to capture.|
-| top | number | Yes | Top boundary of the screen region to capture.|
-| width | number | Yes | Width of the screen region to capture.|
-| height | number | Yes | Height of the screen region to capture.|
+| left | number | Yes | Left boundary of the screen region to capture, in pixels.|
+| top | number | Yes | Top boundary of the screen region to capture, in pixels.|
+| width | number | Yes | Width of the screen region to capture, in pixels.|
+| height | number | Yes | Height of the screen region to capture, in pixels.|
## Size
@@ -51,8 +51,8 @@ Describes the size of the screen region to capture.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
-| width | number | Yes | Width of the screen region to capture.|
-| height | number | Yes | Height of the screen region to capture.|
+| width | number | Yes | Width of the screen region to capture, in pixels.|
+| height | number | Yes | Height of the screen region to capture, in pixels.|
## screenshot.save
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-stack.md b/en/application-dev/reference/apis/js-apis-stack.md
index ff8551cad86f3f4c448e08d267548657305c5c9d..46b06f608af9615bbb138bc54d82cab7f566c0fa 100644
--- a/en/application-dev/reference/apis/js-apis-stack.md
+++ b/en/application-dev/reference/apis/js-apis-stack.md
@@ -239,7 +239,7 @@ stack.push(4);
stack.push(5);
stack.push(4);
stack.forEach((value, index) => {
- console.log("value:" + value, index);
+ console.log("value:" + value, "index:" + index);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-system-configuration.md b/en/application-dev/reference/apis/js-apis-system-configuration.md
index 934ceb020412a18c64499de1cb0ef1593ace2e50..ddc277722b452b8dca63eb50972d9d1f4448726d 100644
--- a/en/application-dev/reference/apis/js-apis-system-configuration.md
+++ b/en/application-dev/reference/apis/js-apis-system-configuration.md
@@ -50,4 +50,3 @@ Defines attributes of the current locale.
| language | string | Yes | No | Language, for example, **zh**.|
| countryOrRegion | string | Yes | No | Country or region, for example, **CN** or **US**.|
| dir | string | Yes | No | Text layout direction. The value can be: - **ltr**: from left to right - **rtl**: from right to left|
-| unicodeSetting5+ | string | Yes | No | Unicode language key set determined by the locale. If current locale does not have a specific key set, an empty set is returned. For example, **{"nu":"arab"}** indicates that current locale uses Arabic numerals.|
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 5c562892d8f5d5a99423cb79a19478609612aed6..9644d0fa26cda69a6b035c0ba1e2bcbbc9f933dc 100644
--- a/en/application-dev/reference/apis/js-apis-system-package.md
+++ b/en/application-dev/reference/apis/js-apis-system-package.md
@@ -23,8 +23,6 @@ hasInstalled(options: CheckPackageHasInstalledOptions): void
Checks whether an application exists, or whether a native application has been installed.
-**Required permissions**: none
-
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
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-taskpool.md b/en/application-dev/reference/apis/js-apis-taskpool.md
index a441a39e8bb232fd589a0b03e473890ef6bbbc5f..8773e4c9df7945a5b686601b7ad8f3de3694d2f4 100644
--- a/en/application-dev/reference/apis/js-apis-taskpool.md
+++ b/en/application-dev/reference/apis/js-apis-taskpool.md
@@ -64,6 +64,7 @@ function func(args) {
console.log("func: " + args);
return args;
}
+
let task = new taskpool.Task(func, "this is my first Task");
```
@@ -116,7 +117,12 @@ function func(args) {
return args;
}
-let value = taskpool.execute(func, 100);
+async function taskpoolTest() {
+ let value = await taskpool.execute(func, 100);
+ console.log("taskpool result: " + value);
+}
+
+taskpoolTest();
```
## taskpool.execute
@@ -158,8 +164,14 @@ function func(args) {
console.log("func: " + args);
return args;
}
-let task = new taskpool.Task(func, "this is my first Task");
-let value = taskpool.execute(task);
+
+async function taskpoolTest() {
+ let task = new taskpool.Task(func, 100);
+ let value = await taskpool.execute(task);
+ console.log("taskpool result: " + value);
+}
+
+taskpoolTest();
```
## taskpool.cancel
@@ -193,9 +205,14 @@ function func(args) {
console.log("func: " + args);
return args;
}
-let task = new taskpool.Task(func, "this is first Task");
-let value = taskpool.execute(task);
-taskpool.cancel(task);
+
+async function taskpoolTest() {
+ let task = new taskpool.Task(func, 100);
+ let value = await taskpool.execute(task);
+ taskpool.cancel(task);
+}
+
+taskpoolTest();
```
## Additional Information
@@ -214,10 +231,18 @@ function func(args) {
return args;
}
-let task = new taskpool.Task(func, "create task, then execute");
-let val1 = taskpool.execute(task);
+async function taskpoolTest() {
+ // taskpool.execute(task)
+ let task = new taskpool.Task(func, "create task, then execute");
+ let val1 = await taskpool.execute(task);
+ console.log("taskpool.execute(task) result: " + val1);
-let val2 = taskpool.execute(func, "execute task by func");
+ // taskpool.execute(function)
+ let val2 = await taskpool.execute(func, "execute task by func");
+ console.log("taskpool.execute(function) result: " + val2);
+}
+
+taskpoolTest();
```
```js
@@ -226,7 +251,7 @@ let val2 = taskpool.execute(func, "execute task by func");
// b.ts
export var c = 2000;
-// a.ts
+// a.ts (in the same directory as b.ts)
import { c } from './b'
function test(a) {
@@ -236,8 +261,16 @@ function test(a) {
return a;
}
-let task = new taskpool.Task(test, "create task, then execute");
-let val1 = taskpool.execute(task);
+async function taskpoolTest() {
+ // taskpool.execute(task)
+ let task = new taskpool.Task(test, "create task, then execute");
+ let val1 = await taskpool.execute(task);
+ console.log("taskpool.execute(task) result: " + val1);
+
+ // taskpool.execute(function)
+ let val2 = await taskpool.execute(test, "execute task by func");
+ console.log("taskpool.execute(function) result: " + val2);
+}
-let val2 = taskpool.execute(test, "execute task by func");
+taskpoolTest();
```
diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md
index eb874f0abd94f72f56f0e1e13a23883e1ae14ce8..473b5cb99e94c1ab84069d23591b63555bfcb7d5 100644
--- a/en/application-dev/reference/apis/js-apis-treemap.md
+++ b/en/application-dev/reference/apis/js-apis-treemap.md
@@ -1,8 +1,5 @@
# @ohos.util.TreeMap (Nonlinear Container TreeMap)
-> **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.
-
**TreeMap** stores key-value (KV) pairs. Each key must be unique and have only one value.
**TreeMap** is implemented using a red-black tree, which is a binary search tree where keys are stored in sorted order for efficient insertion and removal.
@@ -12,9 +9,15 @@
Recommended use case: Use **TreeMap** when you need to store KV pairs in sorted order.
This topic uses the following to identify the use of generics:
+
- K: Key
+
- V: Value
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
## Modules to Import
```ts
@@ -609,7 +612,7 @@ Uses a callback to traverse the elements in this container and obtain their posi
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.|
-| thisArg | Object | No| Value to use when the callback is invoked.|
+| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.|
callbackfn
| Name| Type| Mandatory| Description|
@@ -633,7 +636,7 @@ let treeMap = new TreeMap();
treeMap.set("sparrow", 123);
treeMap.set("gull", 357);
treeMap.forEach((value, key) => {
- console.log("value:" + value, key);
+ console.log("value:" + value, "key:" + key);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md
index 4aaaac1861ceffdfda3d7adc53b16181c42cc9c3..5ca493adcae4ff144341f04d9d1641035ae98db8 100644
--- a/en/application-dev/reference/apis/js-apis-treeset.md
+++ b/en/application-dev/reference/apis/js-apis-treeset.md
@@ -1,8 +1,5 @@
# @ohos.util.TreeSet (Nonlinear Container TreeSet)
-> **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.
-
**TreeSet** is implemented based on **[TreeMap](js-apis-treemap.md)**. In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique.
**[HashSet](js-apis-hashset.md)** stores data in a random order, whereas **TreeSet** stores data in sorted order. Both of them allows only unique elements. However, null values are allowed in **HashSet**, but not allowed in **TreeSet**.
@@ -10,8 +7,13 @@
Recommended use case: Use **TreeSet** when you need to store data in sorted order.
This topic uses the following to identify the use of generics:
+
- T: Type
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+
## Modules to Import
```ts
@@ -482,13 +484,13 @@ Uses a callback to traverse the elements in this container and obtain their posi
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.|
-| thisArg | Object | No| Value to use when the callback is invoked.|
+| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.|
callbackfn
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | T | No| Value of the element that is currently traversed.|
-| key | T | No| Key of the element that is currently traversed (same as **value**).|
+| key | T | No| Key of the element that is currently traversed.|
| set | TreeSet<T> | No| Instance that invokes the **forEach** method.|
**Error codes**
@@ -506,7 +508,7 @@ let treeSet = new TreeSet();
treeSet.add("sparrow");
treeSet.add("gull");
treeSet.forEach((value, key) => {
- console.log("value:" + value, key)
+ console.log("value:" + value, "key:" + key);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md
index b3fb6f7a3ea58550cfa93a514591715952c52ad6..a8aed60f4a0bf23080f223eec440742847a258aa 100644
--- a/en/application-dev/reference/apis/js-apis-uri.md
+++ b/en/application-dev/reference/apis/js-apis-uri.md
@@ -226,9 +226,9 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi
```js
const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp');
-console.log(uriInstance.checkIsAbsolute()); // true
+console.log(`${uriInstance.checkIsAbsolute()}`); // true
const uriInstance1 = new uri.URI('xxx.com/suppliers.htm');
-console.log(uriInstance1.checkIsAbsolute()); // false
+console.log(`${uriInstance1.checkIsAbsolute()}`); // false
```
diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md
index 21ac9df11df7cabdf260edf97fc5fe17f83871b8..ea60b649da3f2d73dfb9cba42dab8ccdee16cde0 100755
--- a/en/application-dev/reference/apis/js-apis-util.md
+++ b/en/application-dev/reference/apis/js-apis-util.md
@@ -26,7 +26,7 @@ Formats the specified values and inserts them into the string by replacing the w
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | -------------- |
| format | string | Yes | String.|
-| ...args | Object[] | No | Values to format. The formatted values will be replaced the wildcard in the string. |
+| ...args | Object[] | No | Values to format. The formatted values will replace the wildcard in the string. If this parameter is not set, the first parameter is returned by default.|
**Return value**
@@ -69,6 +69,20 @@ let result = util.errnoToString(errnum);
console.log("result = " + result);
```
+**Some error code and message examples**
+
+| Error Code| Message |
+| ------ | -------------------------------- |
+| -1 | operation not permitted |
+| -2 | no such file or directory |
+| -3 | no such process |
+| -4 | interrupted system call |
+| -5 | i/o error |
+| -11 | resource temporarily unavailable |
+| -12 | not enough memory |
+| -13 | permission denied |
+| -100 | network is down |
+
## util.callbackWrapper
callbackWrapper(original: Function): (err: Object, value: Object )=>void
@@ -92,15 +106,14 @@ Calls back an asynchronous function. In the callback, the first parameter indica
**Example**
```js
- async function promiseFn() {
- return Promise.reject('value');
- }
- let err = "type err";
- let cb = util.callbackWrapper(promiseFn);
- cb((err, ret) => {
- console.log(err);
- console.log(ret);
- }, err)
+async function fn() {
+ return 'hello world';
+}
+let cb = util.callbackWrapper(fn);
+cb((err, ret) => {
+ if (err) throw err;
+ console.log(ret);
+});
```
## util.promisify9+
@@ -126,24 +139,30 @@ Processes an asynchronous function and returns a promise.
**Example**
```js
- function aysnFun(str1, str2) {
- if (typeof str1 === 'object' && typeof str2 === 'object') {
- return str2
- } else {
- return str1
- }
- }
- let newPromiseObj = util.promisify(aysnFun);
- newPromiseObj({ err: "type error" }, {value:'HelloWorld'}).then(res => {
- console.log(res);
- })
+function fun(num, callback) {
+ if (typeof num === 'number') {
+ callback(null, num + 3);
+ } else {
+ callback("type err");
+ }
+}
+
+const addCall = util.promisify(fun);
+(async () => {
+ try {
+ let res = await addCall(2);
+ console.log(res);
+ } catch (err) {
+ console.log(err);
+ }
+})();
```
-## util.randomUUID9+
+## util.generateRandomUUID9+
-randomUUID(entropyCache?: boolean): string
+generateRandomUUID(entropyCache?: boolean): string
-Uses a secure random number generator to generate a random universally unique identifier (UUID) of RFC 4122 version 4.
+Uses a secure random number generator to generate a random universally unique identifier (UUID) of the string type in RFC 4122 version 4.
**System capability**: SystemCapability.Utils.Lang
@@ -162,17 +181,17 @@ Uses a secure random number generator to generate a random universally unique id
**Example**
```js
- let uuid = util.randomUUID(true);
+ let uuid = util.generateRandomUUID(true);
console.log("RFC 4122 Version 4 UUID:" + uuid);
// Output:
// RFC 4122 Version 4 UUID:88368f2a-d5db-47d8-a05f-534fab0a0045
```
-## util.randomBinaryUUID9+
+## util.generateRandomBinaryUUID9+
-randomBinaryUUID(entropyCache?: boolean): Uint8Array
+generateRandomBinaryUUID(entropyCache?: boolean): Uint8Array
-Uses a secure random number generator to generate a random binary UUID of RFC 4122 version 4.
+Uses a secure random number generator to generate a random UUID of the Uint8Array type in RFC 4122 version 4.
**System capability**: SystemCapability.Utils.Lang
@@ -191,7 +210,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41
**Example**
```js
- let uuid = util.randomBinaryUUID(true);
+ let uuid = util.generateRandomBinaryUUID(true);
console.log(JSON.stringify(uuid));
// Output:
// 138,188,43,243,62,254,70,119,130,20,235,222,199,164,140,150
@@ -201,7 +220,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41
parseUUID(uuid: string): Uint8Array
-Parses a UUID from a string, as described in RFC 4122 version 4.
+Converts the UUID of the string type generated by **generateRandomUUID** to the UUID of the **Uint8Array** type generated by **generateRandomBinaryUUID**, as described in RFC 4122 version 4.
**System capability**: SystemCapability.Utils.Lang
@@ -243,7 +262,7 @@ Formats the specified values and inserts them into the string by replacing the w
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| format | string | Yes| String.|
-| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.|
+| ...args | Object[] | No| Values to format. The formatted values will replace the wildcard in the string. If this parameter is not set, the first parameter is returned by default.|
**Return value**
@@ -361,8 +380,8 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate
**Example**
```js
-let textDecoder = new util.TextDecoder()
-textDecoder.create('utf-8', { ignoreBOM : true });
+let result = util.TextDecoder.create('utf-8', { ignoreBOM : true })
+let retStr = result.encoding
```
### decodeWithStream9+
diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md
index 302b8223c0b720390c82cb28afa921b439fef7fd..7e59a7685b38a014a76065ee04255b106c9d8133 100644
--- a/en/application-dev/reference/apis/js-apis-vector.md
+++ b/en/application-dev/reference/apis/js-apis-vector.md
@@ -1,9 +1,5 @@
# @ohos.util.Vector (Linear Container Vector)
-> **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.
-
**Vector** is a linear data structure that is implemented based on arrays. When the memory of a vector is used up, a larger contiguous memory area is automatically allocated, all the elements are copied to the new memory area, and the current memory area is reclaimed. **Vector** can be used to efficiently access elements.
Both **Vector** and **[ArrayList](js-apis-arraylist.md)** are implemented based on arrays, but **Vector** provides more interfaces for operating the arrays. Both of them can dynamically adjust the capacity. **Vector** doubles the capacity each time, whereas **ArrayList** increases the capacity by 50%.
@@ -13,6 +9,12 @@ Both **Vector** and **[ArrayList](js-apis-arraylist.md)** are implemented based
This topic uses the following to identify the use of generics:
- T: Type
+> **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 provided by this module are deprecated since API version 9. You are advised to use [@ohos.util.ArrayList](js-apis-arraylist.md).
+
## Modules to Import
```ts
@@ -251,7 +253,7 @@ Removes the first occurrence of the specified element from this container.
| -------- | -------- |
| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.|
-**Return value**
+**Example**
```ts
let vector = new Vector();
@@ -320,11 +322,9 @@ vector.add(2);
vector.add(4);
vector.add(5);
vector.add(4);
-vector.replaceAllElements((value: number, index: number) => {
- return value = 2 * value;
-});
-vector.replaceAllElements((value: number, index: number) => {
- return value = value - 2;
+vector.replaceAllElements((value) => {
+ // Add the user operation logic based on the actual scenario.
+ return value;
});
```
@@ -361,7 +361,7 @@ vector.add(4);
vector.add(5);
vector.add(4);
vector.forEach((value, index) => {
- console.log("value:" + value, index)
+ console.log("value:" + value, "index:" + index);
});
```
@@ -421,7 +421,7 @@ Obtains elements within a range in this container, including the element at the
| -------- | -------- |
| Vector<T> | New **Vector** instance obtained.|
-**Return value**
+**Example**
```ts
let vector = new Vector();
@@ -444,7 +444,7 @@ Clears all elements in this container and sets its length to **0**.
**System capability**: SystemCapability.Utils.Lang
-**Return value**
+**Example**
```ts
let vector = new Vector();
@@ -639,18 +639,6 @@ Copies elements in this container into an array to overwrite elements of the sam
| -------- | -------- | -------- | -------- |
| array | Array<T> | Yes| Array to which the elements in the container will be copied.|
-**Example**
-
-```ts
-let vector = new Vector();
-vector.add(2);
-vector.add(4);
-vector.add(5);
-vector.add(4);
-let array = ["a", "b", "c", "d", "e", "f"];
-let result = vector.copyToArray(array);
-```
-
### getFirstElement
getFirstElement(): T
@@ -803,15 +791,15 @@ Obtains an element at the specified position in this container.
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| index | number | Yes| Position index of the target element.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | index | number | Yes| Position index of the target element.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| T | Element obtained.|
+ | Type| Description|
+ | -------- | -------- |
+ | T | Element obtained.|
**Example**
@@ -840,20 +828,9 @@ Replaces an element at the specified position in this container with a given ele
**Return value**
-| Type| Description|
-| -------- | -------- |
-| T | New element.|
-
-**Example**
-
- ```ts
- let vector = new Vector();
- vector.add(2);
- vector.add(4);
- vector.add(5);
- vector.add(4);
- let result = vector.set(2, "A");
- ```
+ | Type| Description|
+ | -------- | -------- |
+ | T | New element.|
### [Symbol.iterator]
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 **