diff --git a/CODEOWNERS b/CODEOWNERS index e9503e13f3c5ba3f95847fc264284eb6feca9c9f..1e61b5d70d7ea0768b8683ea7956a4b34e212a5c 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -517,6 +517,7 @@ zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @jayleehw @Ra 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-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 diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index dba77cf37aab62a7bb4d33b367839a0c0c88bc4e..8484845fb47d82c6de79664c00d0d1c234b0e167 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -2,52 +2,87 @@ - [Application Development Overview](application-dev-guide.md) - About OpenHarmony - - [OpenHarmony Project](../OpenHarmony-Overview.md) - - [Glossary](../glossary.md) - - [OpenHarmony Release Notes](../release-notes/Readme.md) + - [OpenHarmony Project](../OpenHarmony-Overview.md) + - [Glossary](../glossary.md) + - [OpenHarmony Release Notes](../release-notes/Readme.md) - Quick Start - - Getting Started - - [Preparations](quick-start/start-overview.md) - - [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md) - - [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md) - - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md) - - Development Fundamentals - - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - - [SysCap](quick-start/syscap.md) - + - Getting Started + - [Before You Start](quick-start/start-overview.md) + - [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md) + - [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md) + - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md) + - Development Fundamentals + - Application Package Fundamentals + - [Application Package Overview](quick-start/application-package-overview.md) + - Application Package Structure + - [Application Package Structure in Stage Model)](quick-start/application-package-structure-stage.md) + - [Application Package Structure in FA Model](quick-start/application-package-structure-fa.md) + - [HAR File Structure](quick-start/har-structure.md) + - Multi-HAP Mechanism + - [Multi-HAP Design Objectives](quick-start/multi-hap-objective.md) + - [Multi-HAP Build View](quick-start/multi-hap-build-view.md) + - [Multi-HAP Development, Debugging, Release, and Deployment Process](quick-start/multi-hap-release-deployment.md) + - [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md) + - [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md) + - [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md) + - Application Configuration Files in Stage Model + - [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md) + - [app.json5 Configuration File](quick-start/app-configuration-file.md) + - [module.json5 Configuration File](quick-start/module-configuration-file.md) + - Application Configuration Files in FA Model + - [Application Configuration File Overview (FA Model)](quick-start/application-configuration-file-overview-fa.md) + - [Internal Structure of the app Tag](quick-start/app-structure.md) + - [Internal structure of deviceConfig Tag](quick-start/deviceconfig-structure.md) + - [Internal Structure of the module Tag](quick-start/module-structure.md) + - [Resource Categories and Access](quick-start/resource-categories-and-access.md) + - Learning ArkTS + - [Getting Started with ArkTS](quick-start/arkts-get-started.md) + - ArkTS Syntax (Declarative UI) + - [Basic UI Description](quick-start/arkts-basic-ui-description.md) + - State Management + - [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md) + - [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md) + - [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md) + - [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md) + - [Rendering Control](quick-start/arkts-rendering-control.md) + - [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md) - Development - - [Ability Development](ability/Readme-EN.md) - - [UI Development](ui/Readme-EN.md) - - [Common Event and Notification](notification/Readme-EN.md) - - [Window Manager](windowmanager/Readme-EN.md) - - [WebGL](webgl/Readme-EN.md) - - [Media](media/Readme-EN.md) - - [Security](security/Readme-EN.md) - - [Connectivity](connectivity/Readme-EN.md) - - [Data Management](database/Readme-EN.md) - - [File Management](file-management/Readme-EN.md) - - [Telephony](telephony/Readme-EN.md) - - [Task Management](task-management/Readme-EN.md) - - [Device Management](device/Readme-EN.md) - - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - - [DFX](dfx/Readme-EN.md) - - [Internationalization](internationalization/Readme-EN.md) - - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - - [Using Native APIs in Application Projects](napi/Readme-EN.md) + - [Application Models](application-models/Readme-EN.md) + - [UI Development](ui/Readme-EN.md) + - [Common Event and Notification](notification/Readme-EN.md) + - [Window Manager](windowmanager/Readme-EN.md) + - [WebGL](webgl/Readme-EN.md) + - [Media](media/Readme-EN.md) + - [Security](security/Readme-EN.md) + - [Connectivity](connectivity/Readme-EN.md) + - [Data Management](database/Readme-EN.md) + - [File Management](file-management/Readme-EN.md) + - [Telephony](telephony/Readme-EN.md) + - [Task Management](task-management/Readme-EN.md) + - [Device Management](device/Readme-EN.md) + - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) + - [DFX](dfx/Readme-EN.md) + - [Internationalization](internationalization/Readme-EN.md) + - [Application Test](application-test/Readme-EN.md) + - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) + - [Using Native APIs in Application Projects](napi/Readme-EN.md) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs) - API References - - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - - APIs - - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs - - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - - [Node_API](reference/native-lib/third_party_napi/napi.md) + - [SystemCapability](reference/syscap.md) + - [SystemCapability List](reference/syscap-list.md) + - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) + - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) + - [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) + - APIs + - [ArkTS and JS APIs](reference/apis/Readme-EN.md) + - [Error Codes](reference/errorcodes/Readme-EN.md) + - Native APIs + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) + - [Node_API](reference/native-lib/third_party_napi/napi.md) - [FAQs](faqs/Readme-EN.md) - Contribution - - [How to Contribute](../contribute/documentation-contribution.md) + - [How to Contribute](../contribute/documentation-contribution.md) diff --git a/en/application-dev/ability-deprecated/ability-delegator.md b/en/application-dev/ability-deprecated/ability-delegator.md index b32d472176a5b6270fece94ae4bd8ae9a7bd73fa..f72a192dc510c28104511fb1530a915c9f9827cc 100644 --- a/en/application-dev/ability-deprecated/ability-delegator.md +++ b/en/application-dev/ability-deprecated/ability-delegator.md @@ -63,7 +63,7 @@ For details about how to use DevEco Studio to start the test framework, see [Ope **Example** ```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); @@ -87,11 +87,11 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { **Modules to Import** ```javascript -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` ```javascript -var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ### Starting an Ability and Listening for the Ability State diff --git a/en/application-dev/ability-deprecated/context-userguide.md b/en/application-dev/ability-deprecated/context-userguide.md index ac65d92cb9422d040ff16cab1640cd1f9bed5d5c..1340e72918e141dd3b95b5ddc8dbc11258f83493 100644 --- a/en/application-dev/ability-deprecated/context-userguide.md +++ b/en/application-dev/ability-deprecated/context-userguide.md @@ -4,11 +4,11 @@ **Context** provides the capability of obtaining contextual information of an application. - The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. +The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. -- FA model +- FA model -Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. + Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. - Stage model @@ -54,6 +54,7 @@ setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise; The methods are used to set the display orientation of the current ability. **Example** + ```javascript import featureAbility from '@ohos.ability.featureAbility' import bundle from '@ohos.bundle'; @@ -96,13 +97,13 @@ Obtain the context by calling **context.getApplicationContext()** in **Ability** **Example** ```javascript -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var lifecycleid; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate() { - console.log("MainAbility onCreate") + console.log("EntryAbility onCreate") let AbilityLifecycleCallback = { onAbilityCreate(ability){ console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); @@ -191,25 +192,25 @@ Obtain the context from the **context** attribute in **Ability**. **Example** ```javascript -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") globalThis.abilityWant = want; } onDestroy() { - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // Set the main page for this ability when the main window is created. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") // Obtain AbilityContext and print the ability information. let context = this.context; - console.log("[Demo] MainAbility bundleName " + context.abilityInfo.bundleName) + console.log("[Demo] EntryAbility bundleName " + context.abilityInfo.bundleName) windowStage.loadContent("pages/index", (err, data) => { if (err.code) { @@ -222,17 +223,17 @@ export default class MainAbility extends Ability { onWindowStageDestroy() { // Release the UI related resources when the main window is destroyed. - console.log("[Demo] MainAbility onWindowStageDestroy") + console.log("[Demo] EntryAbility onWindowStageDestroy") } onForeground() { // The ability is switched to run in the foreground. - console.log("[Demo] MainAbility onForeground") + console.log("[Demo] EntryAbility onForeground") } onBackground() { // The ability is switched to run in the background. - console.log("[Demo] MainAbility onBackground") + console.log("[Demo] EntryAbility onBackground") } }; ``` @@ -256,16 +257,16 @@ Use the API described in the table below to obtain the context associated with a **Example** ```ts -// MainAbility.ts -import Ability from '@ohos.application.Ability' +// EntryAbility.ts +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") } onDestroy() { - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { @@ -283,7 +284,7 @@ export default class MainAbility extends Ability { ```ts // pages/index.ets -import context from '@ohos.application.context' +import context from '@ohos.app.ability.context' type Context = context.Context diff --git a/en/application-dev/ability-deprecated/continuationmanager.md b/en/application-dev/ability-deprecated/continuationmanager.md index 0ba79f95acf165d604d8f854832703d7fc4af3f8..12db9781c5a5f6548be98f27a426e8a3be354ae9 100644 --- a/en/application-dev/ability-deprecated/continuationmanager.md +++ b/en/application-dev/ability-deprecated/continuationmanager.md @@ -126,7 +126,7 @@ As the entry of the ability continuation capability, **continuationManager** is if (needGrantPermission) { try { // globalThis.context is Ability.context, which must be assigned a value in the MainAbility.ts file in advance. - await globalThis.context.requestPermissionsFromUser(permissions); + await atManger.requestPermissionsFromUser(globalThis.context, permissions); } catch (err) { console.error('app permission request permissions error' + JSON.stringify(err)); } @@ -175,7 +175,7 @@ As the entry of the ability continuation capability, **continuationManager** is let want = { deviceId: remoteDeviceId, bundleName: 'ohos.samples.continuationmanager', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }; globalThis.abilityContext.startAbility(want).then((data) => { console.info('StartRemoteAbility finished, ' + JSON.stringify(data)); diff --git a/en/application-dev/ability-deprecated/fa-brief.md b/en/application-dev/ability-deprecated/fa-brief.md index 5ad79cfe259f1fb9cf865b9d6f496c0f31c47ae0..4bdbfa4d7f3c96663cad5e90b9cd0d187a1e8709 100644 --- a/en/application-dev/ability-deprecated/fa-brief.md +++ b/en/application-dev/ability-deprecated/fa-brief.md @@ -40,4 +40,4 @@ For details about the project directory structure of the FA model, see [OpenHarm For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-fa.md). - \ No newline at end of file + diff --git a/en/application-dev/ability-deprecated/fa-formability.md b/en/application-dev/ability-deprecated/fa-formability.md index a91ca4b9baf98f32bad7ea081024d74949baf726..5c08a1b0b3955472d6f3b16cf7a343a083a0116a 100644 --- a/en/application-dev/ability-deprecated/fa-formability.md +++ b/en/application-dev/ability-deprecated/fa-formability.md @@ -63,9 +63,9 @@ To create an FA widget, you need to implement lifecycle callbacks using the **Li 1. Import the required modules. ```javascript - import formBindingData from '@ohos.application.formBindingData' - import formInfo from '@ohos.application.formInfo' - import formProvider from '@ohos.application.formProvider' + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; ``` 2. Implement lifecycle callbacks for the widget. @@ -158,7 +158,7 @@ The widget configuration file is named **config.json**. Find the **config.json** | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | updateEnabled | Whether the widget can be updated periodically.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) | - | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | @@ -206,7 +206,7 @@ A widget provider is usually started when it is needed to provide information ab let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; - // Persistently store widget information for subsequent use, such as widget instance retrieval or update. + // Persistently store widget data for subsequent use, such as widget instance retrieval or update. // The storeFormInfo API is not implemented here. storeFormInfo(formId, formName, tempFlag, want); @@ -231,9 +231,9 @@ You should override **onDestroy** to implement widget data deletion. } ``` -For details about how to implement persistence data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -The **Want** passed by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. +The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. - Normal widget: a widget persistently used by the widget host @@ -254,14 +254,14 @@ onUpdate(formId) { "detail": "detailOnUpdate" }; let formData = formBindingData.createFormBindingData(obj); - // Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. + // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. formProvider.updateForm(formId, formData).catch((error) => { console.log('FormAbility updateForm, error:' + JSON.stringify(error)); }); } ``` -### Developing Widget UI Pages +### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. @@ -335,7 +335,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -353,12 +353,12 @@ Now you've got a widget shown below. You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: 1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. -2. For the router event, set the following attributes: - - **action**: **router**, which indicates a router event. - - **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model. - - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. -3. For the message event, set the following attributes: - - **action**: **message**, which indicates a message event. +2. Set the router event. + - **action**: **"router"**, which indicates a router event. + - **abilityName**: target ability name, for example, **com.example.entry.EntryAbility**, which is the default UIAbility name in DevEco Studio for the FA model. + - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. +3. Set the message event. + - **action**: **"message"**, which indicates a message event. - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. The code snippet is as follows: @@ -388,7 +388,7 @@ The code snippet is as follows: "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -401,4 +401,4 @@ The code snippet is as follows: } } } - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/ability-deprecated/fa-pageability.md b/en/application-dev/ability-deprecated/fa-pageability.md index 2f4741b80ef771c9b478d32a7713b597fb65c2d4..28b5ce36e292acc9e350f8ae96cb7bcf17f8c8c3 100644 --- a/en/application-dev/ability-deprecated/fa-pageability.md +++ b/en/application-dev/ability-deprecated/fa-pageability.md @@ -135,13 +135,13 @@ Obtain **deviceId** from **DeviceManager**. The sample code is as follows: if (typeof dmClass === 'object' && dmClass != null) { let list = dmClass.getTrustedDeviceListSync(); if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); return list[0].deviceId; } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); } } ``` diff --git a/en/application-dev/ability-deprecated/fa-serviceability.md b/en/application-dev/ability-deprecated/fa-serviceability.md index cf766f35f72c76eb738d3b168d39cbcba0f21da3..0c2a65aebf1076e739009101980633e41f77e8a7 100644 --- a/en/application-dev/ability-deprecated/fa-serviceability.md +++ b/en/application-dev/ability-deprecated/fa-serviceability.md @@ -24,8 +24,6 @@ The differences between **onCommand()** and **onConnect()** are as follows: 1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. - - ```ts export default { onStart() { @@ -47,7 +45,7 @@ The differences between **onCommand()** and **onConnect()** are as follows: } } ``` - + 2. Register a Service ability. Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**. @@ -155,7 +153,7 @@ You can use either of the following methods to connect to a Service ability: ```ts import prompt from '@system.prompt' - + var option = { onConnect: function onConnectCallback(element, proxy) { console.log(`onConnectLocalService onConnectDone`); @@ -194,7 +192,7 @@ You can use either of the following methods to connect to a Service ability: ```ts import featureAbility from '@ohos.ability.featureAbility' - + let want = { bundleName: "com.jstest.service", abilityName: "com.jstest.service.ServiceAbility" @@ -208,7 +206,7 @@ You can use either of the following methods to connect to a Service ability: ```ts import rpc from "@ohos.rpc" - + class ServiceAbilityStub extends rpc.RemoteObject { constructor(des: any) { if (typeof des === 'string') { @@ -218,7 +216,7 @@ You can use either of the following methods to connect to a Service ability: return; } } - + onRemoteRequest(code: number, data: any, reply: any, option: any) { console.log("onRemoteRequest called"); // Execute the service logic. @@ -235,7 +233,7 @@ You can use either of the following methods to connect to a Service ability: return true; } } - + export default { onStart() { console.log('ServiceAbility onStart'); diff --git a/en/application-dev/ability-deprecated/stage-ability-continuation.md b/en/application-dev/ability-deprecated/stage-ability-continuation.md index 7a11716f18f2c8b866e1fd11722ae0e07a32d4ce..b53d57d849c8c771b92d4e86a2095163aab0a395 100644 --- a/en/application-dev/ability-deprecated/stage-ability-continuation.md +++ b/en/application-dev/ability-deprecated/stage-ability-continuation.md @@ -127,7 +127,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar if (needGrantPermission) { Logger.info("app permission needGrantPermission") try { - await this.context.requestPermissionsFromUser(permissions) + await accessManger.requestPermissionsFromUser(this.context, permissions) } catch (err) { Logger.error(`app permission ${JSON.stringify(err)}`) } @@ -147,8 +147,8 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar Modules to import: ```javascript - import Ability from '@ohos.application.Ability'; - import AbilityConstant from '@ohos.application.AbilityConstant'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ``` To implement ability continuation, you must implement this API and have the value **AGREE** returned. @@ -185,14 +185,14 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar Example ```javascript - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; import distributedObject from '@ohos.data.distributedDataObject'; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { storage : LocalStorag; onCreate(want, launchParam) { - Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { // Obtain the user data from the want parameter. let workInput = want.parameters.work @@ -207,8 +207,6 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar ``` For a singleton ability, use **onNewWant()** to achieve the same implementation. - - ### Data Continuation Use distributed objects. @@ -220,12 +218,12 @@ In the ability continuation scenario, the distributed data object is used to syn - In **onContinue()**, the initiator saves the data to be migrated to the distributed object, calls the **save()** API to save the data and synchronize the data to the target device, sets the session ID, and sends the session ID to the target device through **wantParam**. ```javascript - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; import distributedObject from '@ohos.data.distributedDataObject'; var g_object = distributedObject.createDistributedObject({data:undefined}); - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { sessionId : string; onContinue(wantParam : {[key: string]: any}) { @@ -256,34 +254,33 @@ In the ability continuation scenario, the distributed data object is used to syn - The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated. ```javascript - import Ability from '@ohos.application.Ability'; - import distributedObject from '@ohos.data.distributedDataObject'; + import UIAbility from '@ohos.app.ability.UIAbility'; + import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({data:undefined}); + var g_object = distributedObject.createDistributedObject({data:undefined}); - export default class MainAbility extends Ability { - storage : LocalStorag; + export default class EntryAbility extends UIAbility { + storage : LocalStorag; + onCreate(want, launchParam) { + Logger.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the session ID of the distributed data object from the want parameter. + this.sessionId = want.parameters.session + Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) - onCreate(want, launchParam) { - Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - // Obtain the session ID of the distributed data object from the want parameter. - this.sessionId = want.parameters.session - Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) + // Before fetching data from the remote device, reset g_object.data to undefined. + g_object.data = undefined; + // Set the session ID, so the target will fetch data from the remote device. + g_object.setSessionId(this.sessionId); - // Before fetching data from the remote device, reset g_object.data to undefined. - g_object.data = undefined; - // Set the session ID, so the target will fetch data from the remote device. - g_object.setSessionId(this.sessionId); + AppStorage.SetOrCreate('ContinueStudy', g_object.data) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } - AppStorage.SetOrCreate('ContinueStudy', g_object.data) - this.storage = new LocalStorage(); - this.context.restoreWindowStage(this.storage); - } - - } - } + } + } ``` @@ -309,5 +306,3 @@ In the ability continuation scenario, the distributed data object is used to syn ### Best Practice For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-ability.md b/en/application-dev/ability-deprecated/stage-ability.md index 97ba5cff5cc083563f1d0f78c7b499bff2cd2050..60f954c78f306193e7bfefe1e6ceee2babf86da4 100644 --- a/en/application-dev/ability-deprecated/stage-ability.md +++ b/en/application-dev/ability-deprecated/stage-ability.md @@ -56,8 +56,8 @@ The table below describes the APIs provided by the **Ability** class. For detail ### Implementing AbilityStage and Ability Lifecycle Callbacks To create Page abilities for an application in the stage model, you must implement the **AbilityStage** class and ability lifecycle callbacks, and use the **Window** class to set the pages. The sample code is as follows: 1. Import the **AbilityStage** module. - ``` - import AbilityStage from "@ohos.application.AbilityStage" + ```ts + import AbilityStage from "@ohos.app.ability.AbilityStage"; ``` 2. Implement the **AbilityStage** class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**. ```ts @@ -69,41 +69,41 @@ To create Page abilities for an application in the stage model, you must impleme ``` 3. Import the **Ability** module. ```js - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; ``` -4. Implement the lifecycle callbacks of the **Ability** class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**. +4. Implement the lifecycle callbacks of the **UIAbility** class. The default relative path generated by the APIs is **entry\src\main\ets\entryability\EntryAbility.ts**. In the **onWindowStageCreate(windowStage)** API, use **loadContent** to set the application page to be loaded. For details about how to use the **Window** APIs, see [Window Development](../windowmanager/application-window-stage.md). ```ts - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("MainAbility onCreate") + console.log("EntryAbility onCreate") } - + onDestroy() { - console.log("MainAbility onDestroy") + console.log("EntryAbility onDestroy") } - + onWindowStageCreate(windowStage) { - console.log("MainAbility onWindowStageCreate") - + console.log("EntryAbility onWindowStageCreate") + windowStage.loadContent("pages/index").then(() => { - console.log("MainAbility load content succeed") + console.log("EntryAbility load content succeed") }).catch((error) => { - console.error("MainAbility load content failed with error: " + JSON.stringify(error)) + console.error("EntryAbility load content failed with error: " + JSON.stringify(error)) }) } - + onWindowStageDestroy() { - console.log("MainAbility onWindowStageDestroy") + console.log("EntryAbility onWindowStageDestroy") } - + onForeground() { - console.log("MainAbility onForeground") + console.log("EntryAbility onForeground") } - + onBackground() { - console.log("MainAbility onBackground") + console.log("EntryAbility onBackground") } } ``` @@ -113,7 +113,8 @@ Both the **AbilityStage** and **Ability** classes have the **context** attribute The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute in the **AbilityStage** class. The sample code is as follows: ```ts -import AbilityStage from "@ohos.application.AbilityStage" +import AbilityStage from "@ohos.app.ability.AbilityStage"; + export default class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage onCreate") @@ -132,52 +133,32 @@ export default class MyAbilityStage extends AbilityStage { The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute in the **Ability** class. The sample code is as follows: ```ts -import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("MainAbility onCreate") + console.log("EntryAbility onCreate") let context = this.context - console.log("MainAbility bundleCodeDir" + context.bundleCodeDir) + console.log("EntryAbility bundleCodeDir" + context.bundleCodeDir) let abilityInfo = this.context.abilityInfo; - console.log("MainAbility ability bundleName" + abilityInfo.bundleName) - console.log("MainAbility ability name" + abilityInfo.name) + console.log("EntryAbility ability bundleName" + abilityInfo.bundleName) + console.log("EntryAbility ability name" + abilityInfo.name) let config = this.context.config - console.log("MainAbility config language" + config.language) + console.log("EntryAbility config language" + config.language) } } ``` -### Requesting Permissions -If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in **module.json5**, and use the **requestPermissionsFromUser** API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example. - -Declare the required permission in the **module.json5** file. -```json -"requestPermissions": [ - { - "name": "ohos.permission.READ_CALENDAR" - } -] -``` -Request the permission from consumers in the form of a dialog box: -```ts -let context = this.context -let permissions: Array = ['ohos.permission.READ_CALENDAR'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: " + JSON.stringify(error)) -}) -``` ### Notifying of Environment Changes -Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single **Ability** instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md). +Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single **Ability** instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. Before configuring a project, define the project in the [Configuration](../reference/apis/js-apis-application-configuration.md) class. -For an application in the stage model, when the configuration changes, its abilities are not restarted, but the **onConfigurationUpdated(config: Configuration)** callback is triggered. If the application needs to perform processing based on the change, you can overwrite **onConfigurationUpdated**. Note that the **Configuration** object in the callback contains all the configurations of the current ability, not only the changed configurations. +For an application in the stage model, when the configuration changes, its abilities are not restarted, but the **onConfigurationUpdated(config: Configuration)** callback is triggered. If the application needs to perform processing based on the change, you can override **onConfigurationUpdated**. Note that the **Configuration** object in the callback contains all the configurations of the current ability, not only the changed configurations. The following example shows the implementation of the **onConfigurationUpdated** callback in the **AbilityStage** class. The callback is triggered when the system language and color mode are changed. ```ts -import AbilityStage from '@ohos.application.AbilityStage' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' +import AbilityStage from '@ohos.app.ability.AbilityStage'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; export default class MyAbilityStage extends AbilityStage { onConfigurationUpdated(config) { @@ -190,10 +171,10 @@ export default class MyAbilityStage extends AbilityStage { The following example shows the implementation of the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. ```ts -import Ability from '@ohos.application.Ability' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' +import UIAbility from '@ohos.app.ability.UIAbility'; +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { direction : number; onCreate(want, launchParam) { @@ -229,7 +210,7 @@ let context = this.context var want = { "deviceId": "", "bundleName": "com.example.MyApplication", - "abilityName": "MainAbility" + "abilityName": "EntryAbility" }; context.startAbility(want).then(() => { console.log("Succeed to start ability") @@ -246,7 +227,7 @@ let context = this.context var want = { "deviceId": getRemoteDeviceId(), "bundleName": "com.example.MyApplication", - "abilityName": "MainAbility" + "abilityName": "EntryAbility" }; context.startAbility(want).then(() => { console.log("Succeed to start remote ability") @@ -261,17 +242,17 @@ function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { var list = dmClass.getTrustedDeviceListSync(); if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); return list[0].deviceId; } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); } } ``` -Request the permission **ohos.permission.DISTRIBUTED_DATASYNC** from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](#requesting-permissions). +Request the permission **ohos.permission.DISTRIBUTED_DATASYNC** from consumers. This permission is used for data synchronization. For details about the sample code for requesting permissions, see [abilityAccessCtrl.requestPermissionsFromUse](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9). ### Starting an Ability with the Specified Page If the launch type of an ability is set to **singleton** and the ability has been started, the **onNewWant** callback is triggered when the ability is started again. You can pass start options through the **want**. For example, to start an ability with the specified page, use the **uri** or **parameters** parameter in the **want** to pass the page information. Currently, the ability in the stage model cannot directly use the **router** capability. You must pass the start options to the custom component and invoke the **router** method to display the specified page during the custom component lifecycle management. The sample code is as follows: @@ -281,7 +262,7 @@ async function reStartAbility() { try { await this.context.startAbility({ bundleName: "com.sample.MyApplication", - abilityName: "MainAbility", + abilityName: "EntryAbility", uri: "pages/second" }) console.log('start ability succeed') @@ -293,9 +274,9 @@ async function reStartAbility() { Obtain the **want** parameter that contains the page information from the **onNewWant** callback of the ability. ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onNewWant(want, launchParams) { globalThis.newWant = want } @@ -321,5 +302,3 @@ struct Index { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/ability-deprecated/stage-brief.md b/en/application-dev/ability-deprecated/stage-brief.md index 2d5474e2c2f0e8328add287481b5ea47abcb2725..190644c2c0d7e114d0e898de1a8837695bdf049e 100644 --- a/en/application-dev/ability-deprecated/stage-brief.md +++ b/en/application-dev/ability-deprecated/stage-brief.md @@ -111,4 +111,4 @@ For details about the project directory structure of the stage model, see [OpenH For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File](../quick-start/application-configuration-file-overview-stage.md). - \ No newline at end of file + diff --git a/en/application-dev/ability-deprecated/stage-call.md b/en/application-dev/ability-deprecated/stage-call.md index e447dc4fd89f99948ebb379de7010c4db9486488..71f5f6934dda385161f4adcb95837924c691c278 100644 --- a/en/application-dev/ability-deprecated/stage-call.md +++ b/en/application-dev/ability-deprecated/stage-call.md @@ -24,8 +24,10 @@ The ability call process is as follows: - The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. ![stage-call](figures/stage-call.png) -> **NOTE**
+> **NOTE** +> > The launch type of the callee ability must be **singleton**. +> > Currently, only system applications can use the ability call. ## Available APIs @@ -34,7 +36,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r **Table 2** Ability call APIs |API|Description| |:------|:------| -|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| +|startAbilityByCall(want: Want): Promise\|Starts an ability in the foreground (through the **want** configuration) or background (default) and obtains the **Caller** object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or **ServiceExtensionContext**.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.| |call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability.| @@ -210,22 +212,25 @@ function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { var list = dmClass.getTrustedDeviceListSync() if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null") + console.log("EntryAbility onButtonClick getRemoteDeviceId err: list is null") return } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) + console.log("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) return list[0].deviceId } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null") + console.log("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null") } } ``` In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows: ```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; + requestPermission() { let context = this.context let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] - context.requestPermissionsFromUser(permissions).then((data) => { + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(context, permissions).then((data) => { console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) }).catch((error) => { console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) diff --git a/en/application-dev/ability-deprecated/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md index c45b33732a4f902391eb153c9f5304b071bc4f34..bc1c54afe9d2e323f0938bca250f83737df9cbdb 100644 --- a/en/application-dev/ability-deprecated/stage-formextension.md +++ b/en/application-dev/ability-deprecated/stage-formextension.md @@ -2,32 +2,32 @@ ## Widget Overview -A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. +A widget is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. +A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. -Basic concepts: +Before you get started, it would be helpful if you have a basic understanding of the following concepts: -- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. -- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. -- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. +- Widget host: an application that displays the widget content and controls the widget location. +- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. > **NOTE** > -> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. +> The widget host and provider do not need to be running all the time. The Widget Manager will start the widget provider to obtain widget information when a widget is added, deleted, or updated. -You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. +You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. -The widget provider controls the widget content to display, component layout, and click events bound to components. +The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components. ## When to Use -Stage widget development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: +Carry out the following operations to develop the widget provider based on the [stage model](stage-brief.md): -- Develop the lifecycle callbacks in **FormExtension**. -- Create a **FormBindingData** instance. -- Update a widget through **FormProvider**. -- Develop the widget UI page. +1. Implement lifecycle callbacks by using the **FormExtension** APIs. +2. Create a **FormBindingData** instance. +3. Update a widget by using the **FormProvider** APIs. +4. Develop the widget UI page. ## Available APIs @@ -37,12 +37,12 @@ The **FormExtension** class has the following APIs. For details, see [FormExtens | API | Description | | :----------------------------------------------------------- | :------------------------------------------- | -| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | +| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created. | | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. | | onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | -| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | +| onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed. | | onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). @@ -54,7 +54,7 @@ The **FormExtension** class also has a member context, that is, the **FormExtens | startAbility(want: Want, callback: AsyncCallback<void>): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)| | startAbility(want: Want): Promise<void> | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)| -For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). +The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). **Table 3** FormProvider APIs @@ -69,18 +69,18 @@ For details, see [FormProvider](../reference/apis/js-apis-application-formProvid ### Creating a FormExtension Instance -To create a widget in the stage model, implement the lifecycle callbacks of **FormExtension**. The sample code is as follows: +To create a widget in the stage model, you need to implement lifecycle callbacks using the **FormExtension** APIs. The code snippet is as follows: 1. Import the required modules. ```javascript - import FormExtension from '@ohos.application.FormExtension' - import formBindingData from '@ohos.application.formBindingData' - import formInfo from '@ohos.application.formInfo' - import formProvider from '@ohos.application.formProvider' + import FormExtension from '@ohos.app.ability.FormExtension'; + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; ``` -2. Implement the lifecycle callbacks of **FormExtension**. +2. Implement lifecycle callbacks for the widget. ```javascript export default class FormAbility extends FormExtension { @@ -99,7 +99,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo console.log('FormAbility onCastToNormal'); } onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -132,7 +132,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo - Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows: - | Field | Description | Data Type | Default | + | Name | Description | Data Type | Default Value Allowed | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | | name | Name of the Extension ability. This field must be specified. | String | No | | srcEntrance | Path of the Extension ability lifecycle code. This field must be specified.| String | No | @@ -145,7 +145,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo For a Form Extension ability, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. - A configuration example is as follows: + Example configuration: ```json "extensionAbilities": [{ @@ -165,24 +165,24 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo The internal field structure is described as follows: - | Field | Description | Data Type | Default | + | Name | Description | Data Type | Default Value Allowed | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | - | name | Class name of a widget. The value is a string with a maximum of 127 bytes. | String | No | + | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | src | Full path of the UI code corresponding to the widget. | String | No | | window | Window-related configurations. | Object | Yes | | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | - | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | + | colorMode | Color mode of the widget.
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| + | supportDimensions | Grid styles supported by the widget.
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | - | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | - | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
This parameter has a lower priority than **updateDuration**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) | - | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.
This parameter has a higher priority than **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | + | updateEnabled | Whether the widget can be updated periodically.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean | No | + | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) | + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | - A configuration example is as follows: + Example configuration: ```json { @@ -200,7 +200,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo "defaultDimension": "2*2", "updateEnabled": true, "scheduledUpdateTime": "10:30", - "formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility" + "formConfigAbility": "ability://ohos.samples.FormApplication.EntryAbility" }] } ``` @@ -208,7 +208,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ### Persistently Storing Widget Data -Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting the widget. +A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. ```javascript onCreate(want) { @@ -230,7 +230,7 @@ Mostly, the widget provider is started only when it needs to obtain information } ``` -You should override **onDestroy** to delete widget data. +You should override **onDestroy** to implement widget data deletion. ```javascript onDestroy(formId) { @@ -242,30 +242,30 @@ You should override **onDestroy** to delete widget data. } ``` -For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). +For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. +The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. -- Normal widget: a widget that will be persistently used by the widget host +- Normal widget: a widget persistently used by the widget host -- Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget temporarily used by the widget host -Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets. +Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. ### Updating Widget Data -When a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The sample code is as follows: +When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows: ```javascript onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", "detail": "detailOnUpdate" }; let formData = formBindingData.createFormBindingData(obj); - // Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. + // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. formProvider.updateForm(formId, formData).catch((error) => { console.log('FormAbility updateForm, error:' + JSON.stringify(error)); }); @@ -278,9 +278,9 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme > **NOTE** > -> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. +> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. - - In the HML file: + - HML file: ```html
@@ -295,7 +295,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
``` - - In the CSS file: + - CSS file: ```css .container { @@ -336,7 +336,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme } ``` - - In the JSON file: + - JSON file: ```json { "data": { @@ -346,7 +346,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme "actions": { "routerEvent": { "action": "router", - "abilityName": "MainAbility", + "abilityName": "EntryAbility", "params": { "message": "add detail" } @@ -363,18 +363,18 @@ Now you've got a widget shown below. You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: -1. Set **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. -2. For the router event, set the following attributes: - - **action**: **"router"**. - - **abilityName**: target ability name, for example, **MainAbility**, which is the default main ability name in DevEco Studio for the stage model. - - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. -3. For the message event, set the following attributes: - - **action**: **"message"**. +1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. +2. Set the router event. + - **action**: **"router"**, which indicates a router event. + - **abilityName**: target ability name, for example, **EntryAbility**, which is the default UIAbility name in DevEco Studio for the stage model. + - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the stage model, you can obtain **want** and its **parameters** field. +3. Set the message event. + - **action**: **"message"**, which indicates a message event. - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. -The following is an example: +The code snippet is as follows: - - In the HML file: + - HML file: ```html
@@ -389,7 +389,7 @@ The following is an example:
``` - - In the JSON file: + - JSON file: ```json { "data": { @@ -399,7 +399,7 @@ The following is an example: "actions": { "routerEvent": { "action": "router", - "abilityName": "MainAbility", + "abilityName": "EntryAbility", "params": { "message": "add detail" } diff --git a/en/application-dev/ability-deprecated/stage-serviceextension.md b/en/application-dev/ability-deprecated/stage-serviceextension.md index 98cae5914f7afa34c916c53f6bb423b590cf5070..aee8f9c8116dffb49956a2bb9a1cad2ad263a166 100644 --- a/en/application-dev/ability-deprecated/stage-serviceextension.md +++ b/en/application-dev/ability-deprecated/stage-serviceextension.md @@ -42,9 +42,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p 2. Customize a class that inherits from `ServiceExtensionAbility` in the .ts file in the directory where the Service Extension ability is defined (`entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts` by default) and override the lifecycle callbacks of the base class. The code sample is as follows: ```js - import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility' - import rpc from '@ohos.rpc' - + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + class StubTest extends rpc.RemoteObject { constructor(des) { super(des); @@ -52,7 +52,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p onRemoteRequest(code, data, reply, option) { } } - + class ServiceExtAbility extends ServiceExtensionAbility { onCreate(want) { console.log('onCreate, want:' + want.abilityName); diff --git a/en/application-dev/ability-deprecated/wantagent.md b/en/application-dev/ability-deprecated/wantagent.md index 4b1854d1a54a36f864b3dd4215040eb24db2e5f3..0fc2036aac7d8b141310521a704570f28801f063 100644 --- a/en/application-dev/ability-deprecated/wantagent.md +++ b/en/application-dev/ability-deprecated/wantagent.md @@ -1,6 +1,6 @@ # WantAgent Development ## When to Use -The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. +The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. ## Available APIs | API | Description| @@ -12,13 +12,13 @@ The **WantAgent** class encapsulates want information that specifies a particula ## How to Develop 1. Import the **WantAgent** module. - ``` - import wantAgent from '@ohos.wantAgent'; + ```ts + import wantAgent from '@ohos.app.ability.wantAgent'; ``` 2. Create a **WantAgentInfo** object that will be used for starting an ability. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent](../reference/apis/js-apis-wantAgent.md#wantagentinfo). - ``` + ```ts private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. // wantAgentInfo @@ -27,7 +27,7 @@ The **WantAgent** class encapsulates want information that specifies a particula { deviceId: "", bundleName: "com.example.test", - abilityName: "com.example.test.MainAbility", + abilityName: "com.example.test.EntryAbility", action: "", entities: [], uri: "", @@ -42,7 +42,7 @@ The **WantAgent** class encapsulates want information that specifies a particula 3. Create a **WantAgentInfo** object for publishing a common event. - ``` + ```ts private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. // wantAgentInfo @@ -61,7 +61,7 @@ The **WantAgent** class encapsulates want information that specifies a particula 4. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. - ``` + ```ts // Create a WantAgent object. wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { if (err.code) { @@ -75,7 +75,7 @@ The **WantAgent** class encapsulates want information that specifies a particula 5. Trigger the **WantAgent** object. - ``` + ```ts // Trigger the WantAgent object. var triggerInfo = { code:0 diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index f074e1906535d708b193adea3b1ee3308fb0de4e..96e956f86e1528c5946c094b204c83e6e7d96222 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -18,7 +18,7 @@ To facilitate your application development, we provide development guidelines fo First thing first, familiarize yourself with the two cornerstone frameworks in OpenHarmony applications: -- Application framework: [Ability Development](ability/Readme-EN.md) +- Application framework: [Application Models](application-models/Readme-EN.md) - UI framework: [UI Development](ui/Readme-EN.md) All applications should be developed on top of these frameworks. @@ -37,6 +37,7 @@ Then, equip yourself for developing the key features, with the following guideli - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [DFX](dfx/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md) +- [Application Test](application-test/Readme-EN.md) - [IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/Readme-EN.md) @@ -56,11 +57,11 @@ API references encompass all components and APIs available in OpenHarmony, helpi They are organized as follows: - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - -- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) -- APIs - - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs +- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) +- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) +- APIs + - [JS and TS APIs](reference/apis/Readme-EN.md) + - Native APIs - [Standard Library](reference/native-lib/third_party_libc/musl.md) - [Node_API](reference/native-lib/third_party_napi/napi.md) diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 2b22839820539e2919f1a705595a47cc491df8d0..b9bc5bb92ed39b292ca4eede0023989364eb473c 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -18,7 +18,7 @@ To facilitate your application development, we provide development guidelines fo First thing first, familiarize yourself with the two cornerstone frameworks in OpenHarmony applications: -- Application framework: [Ability Development](ability/fa-brief.md) +- Application framework: [Application Models](application-models/application-model-composition.md) - UI framework: [UI Development](ui/arkui-overview.md) All applications should be developed on top of these frameworks. @@ -35,8 +35,9 @@ Then, equip yourself for developing the key features, with the following guideli - [Task Management](task-management/background-task-overview.md) - [Device](device/usb-overview.md) - [Device Usage Statistics](device-usage-statistics/device-usage-statistics-overview.md) -- [DFX](dfx/hiappevent-overview.md) +- [DFX](dfx/hiappevent-guidelines.md) - [Internationalization](internationalization/international-overview.md) +- [Application Test](application-test/arkxtest-guidelines.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md) @@ -59,7 +60,9 @@ They are organized as follows: - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) -- [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md) +- [JS Service Widget UI Components](reference/js-service-widget-ui/Readme-EN.md) + +- [JS and TS APIs](reference/apis/js-apis-ability-dataUriUtils.md) - Native APIs - [Standard Library](reference/native-lib/third_party_libc/musl.md) diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index a9473b7f6c2d0fb75e160cafdd1fb94b43633fa7..2a920300623358bc25f7256d6af8b957665bc600 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -1,2 +1,130 @@ # Application Models +- Application Model Overview + - [Elements of the Application Model](application-model-composition.md) + - [Interpretation of the Application Model](application-model-description.md) +- Stage Model Development + - [Stage Model Development Overview](stage-model-development-overview.md) + - Stage Mode Application Components + - [Application- or Component-Level Configuration](application-component-configuration-stage.md) + - UIAbility Component + - [UIAbility Component Overview](uiability-overview.md) + - [UIAbility Component Lifecycle](uiability-lifecycle.md) + - [UIAbility Component Launch Type](uiability-launch-type.md) + - [UIAbility Component Usage](uiability-usage.md) + - [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md) + - [Interaction Between Intra-Device UIAbility Components](uiability-intra-device-interaction.md) + - ExtensionAbility Component + - [ExtensionAbility Component Overview](extensionability-overview.md) + - [ServiceExtensionAbility](serviceextensionability.md) + - [DataShareExtensionAbility](datashareextensionability.md) + - [FormExtensionAbility (Widget)](widget-development-stage.md) + - [AbilityStage Component Container](abilitystage.md) + - [Context](application-context-stage.md) + - Want + - [Want Overview](want-overview.md) + - [Matching Rules of Explicit Want and Implicit Want](explicit-implicit-want-mappings.md) + - [Common action and entities Values](actions-entities.md) + - [Using Explicit Want to Start an Ability](ability-startup-with-explicit-want.md) + - [Using Implicit Want to Open a Website](ability-startup-with-implicit-want.md) + - [Using Want to Share Data Between Applications](data-share-via-want.md) + - [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) + - IPC + - [Process Model](process-model-stage.md) + - Common Events + - [Introduction to Common Events](common-event-overview.md) + - [Subscribing to Common Events](common-event-subscription.md) + - [Publishing Common Events](common-event-publish.md) + - [Unsubscribing from Common Events](common-event-unsubscription.md) + - [Background Services](background-services.md) + - Inter-Thread Communication + - [Thread Model](thread-model-stage.md) + - [Using Emitter for Inter-Thread Communication](itc-with-emitter.md) + - [Using Worker for Inter-Thread Communication](itc-with-worker.md) + - Mission Management + - [Mission Management Scenarios](mission-management-overview.md) + - [Mission Management and Launch Type](mission-management-launch-type.md) + - [Page Stack and MissionList](page-mission-stack.md) + - [Application Configuration File](config-file-stage.md) +- FA Model Development + - [FA Model Development Overview](fa-model-development-overview.md) + - FA Mode Application Components + - [Application- or Component-Level Configuration](application-component-configuration-fa.md) + - PageAbility Component Development + - [PageAbility Component Overview](pageability-overview.md) + - [PageAbility Component Configuration](pageability-configuration.md) + - [PageAbility Lifecycle](pageability-lifecycle.md) + - [PageAbility Launch Type](pageability-launch-type.md) + - [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 Specified Page](start-page.md) + - [Window Properties](window-properties.md) + - [Requesting Permissions](request-permissions.md) + - [Redirection Rules](redirection-rules.md) + - ServiceAbility Component Development + - [ServiceAbility Component Overview](serviceability-overview.md) + - [ServiceAbility Component Configuration](serviceability-configuration.md) + - [ServiceAbility Lifecycle](serviceability-lifecycle.md) + - [Creating a ServiceAbility](create-serviceability.md) + - [Starting a ServiceAbility](start-serviceability.md) + - [Connecting to a ServiceAbility](connect-serviceability.md) + - DataAbility Component Development + - [DataAbility Component Overview](dataability-overview.md) + - [DataAbility Component Configuration](dataability-configuration.md) + - [DataAbility Lifecycle](dataability-lifecycle.md) + - [Creating a DataAbility](create-dataability.md) + - [Starting a DataAbility](start-dataability.md) + - [Accessing a DataAbility](access-dataability.md) + - [DataAbility Permission Control](dataability-permission-control.md) + - [Widget Development](widget-development-fa.md) + - [Context](application-context-fa.md) + - [Want](want-fa.md) + - [Component Startup Rules](component-startup-rules-fa.md) + - IPC + - [Process Model](process-model-fa.md) + - [Common Events](common-event-fa.md) + - [Background Services](rpc.md) + - Inter-Thread Communication + - [Thread Model](thread-model-fa.md) + - [Inter-Thread Communication](itc-fa-overview.md) + - [Mission Management](mission-management-fa.md) + - [Application Configuration File](config-file-fa.md) +- Development of Component Interaction Between the FA Model and Stage Model + - [Component Interaction Between the FA Model and Stage Model](fa-stage-interaction-overview.md) + - [Starting a UIAbility from the FA Model](start-uiability-from-fa.md) + - [Connecting to a ServiceExtensionAbility from the FA Model](bind-serviceextensionability-from-fa.md) + - [Accessing a DataShareExtensionAbility from the FA Model](access-datashareextensionability-from-fa.md) + - [Starting a PageAbility from the Stage Model](start-pageability-from-stage.md) + - [Connecting to a ServiceAbility from the Stage Model](bind-serviceability-from-stage.md) +- Switching from the FA Model to the Stage Model + - [Model Switching Overview](model-switch-overview.md) + - Configuration File Switching + - [Differences in Configuration Files](configuration-file-diff.md) + - [Switching of app and deviceConfig](app-deviceconfig-switch.md) + - [Switching of module](module-switch.md) + - Component Switching + - [PageAbility Switching](pageability-switch.md) + - [ServiceAbility Switching](serviceability-switch.md) + - [DataAbility Switching](dataability-switch.md) + - [Widget Switching](widget-switch.md) + - API Switching + - [API Switching Overview](api-switch-overview.md) + - [Context Switching](context-switch.md) + - [featureAbility Switching](featureability-switch.md) + - [particleAbility Switching](particleability-switch.md) + - [LifecycleForm Switching](lifecycleform-switch.md) + - [LifecycleApp Switching](lifecycleapp-switch.md) + - [LifecycleService Switching](lifecycleservice-switch.md) + - [LifecycleData Switching](lifecycledata-switch.md) + - [DataAbilityHelper Switching](dataabilityhelper-switch.md) + - [mediaLibrary Switching](medialibrary-switch.md) + - [request Switching](request-switch.md) + - [resourceManager Switching](resourcemanager-switch.md) + - [window Switching](window-switch.md) + - [Storage Switching](storage-switch.md) diff --git a/en/application-dev/application-models/ability-startup-with-explicit-want.md b/en/application-dev/application-models/ability-startup-with-explicit-want.md new file mode 100644 index 0000000000000000000000000000000000000000..9186379f32299ee7a42b7f82af4fc7f464c160d1 --- /dev/null +++ b/en/application-dev/application-models/ability-startup-with-explicit-want.md @@ -0,0 +1,4 @@ +# Using Explicit Want to Start an Ability + + +When a user touches a button in an application, the application often needs to start a UIAbility component to complete a specific task. If the **abilityName** and **bundleName** parameters are specified when starting a UIAbility, the explicit Want is used. For details about how to use the explicit Want, see [Starting UIAbility in the Same Application](uiability-intra-device-interaction.md#starting-uiability-in-the-same-application). diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md new file mode 100644 index 0000000000000000000000000000000000000000..ab116c430cb7b248b947ccbee46cf5ac932f9fc9 --- /dev/null +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -0,0 +1,82 @@ +# Using Implicit Want to Open a Website + + +## Prerequisites + +One or more browsers are installed on your device. + +The **module.json5** of a browser application is as follows: + +```json +"skills": [ + { + "entities": [ + "entity.system.browsable" + // ... + ], + "actions": [ + "ohos.want.action.viewData" + // ... + ], + "uris": [ + { + "scheme": "https", + "host": "www.test.com", + "port": "8080", + // Prefix matching is used. + "pathStartWith": "query", + "type": "text/*" + }, + { + "scheme": "http", + // ... + } + // ... + ] + }, +] +``` + + +## How to Develop + +1. Use the custom function **implicitStartAbility** to start an ability. + + ```ts + async implicitStartAbility() { + try { + let want = { + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: "com.example.myapplication", + "action": "ohos.want.action.viewData", + // entities can be omitted. + "entities": [ "entity.system.browsable" ], + "uri": "https://www.test.com:8080/query/student", + "type": "text/plain" + } + let context = getContext(this) as common.UIAbilityContext; + await context.startAbility(want) + console.info(`explicit start ability succeed`) + } catch (error) { + console.info(`explicit start ability failed with ${error.code}`) + } + let context = getContext(this) as common.UIAbilityContext; + await context.startAbility(want) + console.info(`explicit start ability succeed`) + } catch (error) { + console.info(`explicit start ability failed with ${error.code}`) + } + } + ``` + + The matching process is as follows: + 1. If **action** in the passed **want** parameter is specified and is included in **actions** under **skills**, the matching is successful. + + 2. If **entities** in the passed **want** parameter is specified and is included in **entities** under **skills**, the matching is successful. + + 3. If **uri** in the passed **want** parameter is included in **uris** under **skills**, which is concatenated into `https://www.test.com:8080/query*` (where \* is a wildcard), the matching is successful. + + 4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful. + +2. When there are multiple matching applications, a dialog box is displayed for you to select one of them. +stage-want1 diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md new file mode 100644 index 0000000000000000000000000000000000000000..4e0a273f850b4919d0964580ebed89c053c273f7 --- /dev/null +++ b/en/application-dev/application-models/abilitystage.md @@ -0,0 +1,57 @@ +# AbilityStage Component Container + + +AbilityStage is a component container at the [module](../quick-start/application-package-structure-stage.md) level. When the HAP of an application is loaded for the first time, an AbilityStage instance is created. You can perform operations such as initialization on the instance. + + +An AbilityStage instance corresponds to a module. + + +AbilityStage is not automatically generated in the default project of DevEco Studio. To use AbilityStage, you can manually create an AbilityStage file. The procedure is as follows: + + +1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **myabilitystage**. + +2. In the **myabilitystage** directory, right-click and choose **New > ts File** to create a file named **MyAbilityStage.ts**. + +3. Open the **MyAbilityStage.ts** file, and import the dependency package of AbilityStage. Customize a class that inherits from AbilityStage, and add the required lifecycle callbacks. The following code snippet adds the **onCreate()** lifecycle callback. + + ```ts + import AbilityStage from '@ohos.app.ability.AbilityStage'; + + export default class MyAbilityStage extends AbilityStage { + onCreate() { + // When the HAP of the application is loaded for the first time, initialize the module. + } + onAcceptWant(want) { + // Triggered only for the ability with the specified launch type. + return "MyAbilityStage"; + } + } + ``` + + +[AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) has the lifecycle callback [onCreate()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageoncreate) and the event callbacks [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant), [onConfigurationUpdated()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonconfigurationupdate), and [onMemoryLevel()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonmemorylevel). + + +- **onCreate()** lifecycle callback: Before the first UIAbility instance of a module is loaded, an AbilityStage instance is created. This callback is invoked when the AbilityStage instance is created. The AbilityStage module notifies you of when you can perform module initialization such as resource pre-loading and thread creation during module loading. + +- **onAcceptWant()** event callback: triggered when the UIAbility is started in [specified mode](uiability-launch-type.md#specified). For details, see [UIAbility Component Launch Type](uiability-launch-type.md). + +- **onConfigurationUpdated()** event callback: triggered when the global system configuration changes. The global system configuration, such as the system language and theme, are defined in the [Configuration](../reference/apis/js-apis-app-ability-configuration.md) class before project configuration. + +- **onMemoryLevel()** event callback: triggered when the system adjusts the memory. + +When an application is switched to the background, it is cached in the background. This adversely affects the overall system performance. When system resources are insufficient, the system reclaims memory from applications in multiple ways. For example, the system may stop applications to release memory for executing key tasks. To further maintain the balance of the system memory and prevent the system from stopping application processes, you can subscribe to the system memory changes in the **onMemoryLevel()** lifecycle callback of AbilityStage to release unnecessary resources. + + + ```ts + import AbilityStage from '@ohos.app.ability.AbilityStage'; + + export default class MyAbilityStage extends AbilityStage { + onMemoryLevel(level) { + // Release unnecessary memory based on the change of available system memory. + } + } + ``` + diff --git a/en/application-dev/application-models/access-dataability.md b/en/application-dev/application-models/access-dataability.md new file mode 100644 index 0000000000000000000000000000000000000000..24dc9305f194a61c974c63db224f2e7727689f5f --- /dev/null +++ b/en/application-dev/application-models/access-dataability.md @@ -0,0 +1,204 @@ +# Accessing a DataAbility + + +To access a DataAbility, import the basic dependency packages and obtain the URI string for communicating with the DataAbility. + + +The basic dependency packages include: + + +- @ohos.ability.featureAbility + +- @ohos.data.dataAbility + +- @ohos.data.rdb + + +The sample code for accessing a DataAbility is as follows: + + +1. Create a **DataAbilityHelper** instance. + + ```ts + // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), three slashes in total. + import featureAbility from '@ohos.ability.featureAbility' + import ohos_data_ability from '@ohos.data.dataAbility' + import ohos_data_rdb from '@ohos.data.rdb' + + let urivar = "dataability:///com.ix.DataAbility" + let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); + ``` + +2. Construct RDB data. + + ```ts + let valuesBucket = {"name": "gaolu"} + let da = new ohos_data_ability.DataAbilityPredicates() + let valArray =new Array("value1"); + let cars = new Array({"batchInsert1" : "value1",}); + ``` + + For details about DataAbilityPredicates, see [DataAbility Predicates](../reference/apis/js-apis-data-ability.md). + +3. Use **insert** to insert data to the DataAbility. + + ```ts + // Callback mode: + DAHelper.insert( + urivar, + valuesBucket, + (error, data) => { + console.info("DAHelper insert result: " + data) + } + ); + ``` + + + ```ts + // Promise mode (await needs to be used in the asynchronous method): + let datainsert = await DAHelper.insert(urivar, valuesBucket).then((data) => { + console.info("insert success."); + }).catch((error) => { + console.error("insert failed."); + }); + ``` + +4. Use **delete** to delete data from the DataAbility. + + ```ts + // Callback mode: + DAHelper.delete( + urivar, + da, + (error, data) => { + console.info("DAHelper delete result: " + data) + } + ); + ``` + + + ```ts + // Promise mode (await needs to be used in the asynchronous method): + let datadelete = await DAHelper.delete( + urivar, + da, + ); + ``` + +5. Use **update** to update data in the DataAbility. + + ```ts + // Callback mode: + DAHelper.update( + urivar, + valuesBucket, + da, + (error, data) => { + console.info("DAHelper update result: " + data) + } + ); + ``` + + + ```ts + // Promise mode (await needs to be used in the asynchronous method): + let dataupdate = await DAHelper.update( + urivar, + valuesBucket, + da, + ); + ``` + +6. Use **query** to query data in the DataAbility. + + ```ts + // Callback mode: + DAHelper.query( + urivar, + valArray, + da, + (error, data) => { + console.info("DAHelper query result: " + data) + } + ); + ``` + + + ```ts + // Promise mode (await needs to be used in the asynchronous method): + let dataquery = await DAHelper.query( + urivar, + valArray, + da + ); + ``` + +7. Use **batchInsert** to insert data in batches to the DataAbility. + + ```ts + // Callback mode: + DAHelper.batchInsert( + urivar, + cars, + (error, data) => { + console.info("DAHelper batchInsert result: " + data) + } + ); + ``` + + + ```ts + // Promise mode (await needs to be used in the asynchronous method): + let databatchInsert = await DAHelper.batchInsert( + urivar, + cars + ); + ``` + +8. Use **executeBatch** to process data in batches in the DataAbility. + + ```ts + // Callback mode: + DAHelper.executeBatch( + urivar, + [ + { + uri: urivar, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: {"executeBatch" : "value1",}, + predicates: da, + expectedCount:0, + predicatesBackReferences: null, + interrupted:true, + } + ], + (error, data) => { + console.info("DAHelper executeBatch result: " + data) + } + ); + ``` + + + ```ts + // Promise mode (await needs to be used in the asynchronous method): + let dataexecuteBatch = await DAHelper.executeBatch( + urivar, + [ + { + uri: urivar, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: + { + "executeBatch" : "value1", + }, + predicates: da, + expectedCount:0, + predicatesBackReferences: null, + interrupted:true, + } + ] + ); + ``` + + +The APIs for operating a DataAbility are provided by **DataAbilityHelper**. For details about the APIs, see [DataAbilityHelper](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md). diff --git a/en/application-dev/application-models/access-datashareextensionability-from-fa.md b/en/application-dev/application-models/access-datashareextensionability-from-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..0abc7e3b8e948529b9916f936bf59b4a60a93637 --- /dev/null +++ b/en/application-dev/application-models/access-datashareextensionability-from-fa.md @@ -0,0 +1,52 @@ +# Accessing a DataShareExtensionAbility from the FA Model + + +## Overview + +Regardless of the FA model or stage model, the data read/write function consists of the client and server. + +- In the FA model, the client uses the **DataAbilityHelper** class to provide external APIs, and the server uses the **DataAbility** class to provide database read and write services. + +- In the stage model, the client uses the **DataShareHelper** class to provide external APIs, and the server uses the **DataShareExtensionAbility** class to provide database read and write services. + +If the client uses the FA model whereas the server is upgraded to the stage model, the client cannot access the server. + +To resolve this issue, OpenHarmony provides a solution on the framework side for smooth evolution. + + +## Basic Principles + +A compatible method is that **DataAbilityHelper** determines whether to call the **DataShareHelper** APIs based on the URI prefix (either **DataAbility** or **DataShare**). However, this method requires modification to the URI in the original client code. + +Instead of manual modification, OpenHarmony adopts the following processing: + +1. The system attempts to start the DataAbility based on the URI passed in. If the startup fails, the system converts the URI prefix to **DataShare** and attempts to start the DataShareExtensionAbility. + +2. If the URI does not map to any DataAbility or DataShareExtensionAbility, the startup fails. Otherwise, either the DataAbility or DataShareExtensionAbility is started. + + +## Constraints + +1. When you switch a DataAbility to a DataShareExtensionAbility, only the URI prefix can be modified.![FAvsStage-uri](figures/FAvsStage-uri.png) + +2. The **DataShareHelper** class implements only certain APIs of **DataAbilityHelper**. For details about the APIs, see the table below. + + **Table 1** APIs invoked when the FA model accesses a DataShareExtensionAbility of the stage model + + | API| Provided by DataAbilityHelper| Provided by DataShareHelper| Compatible| + | -------- | -------- | -------- | -------- | + | on | Yes| Yes| Yes| + | off | Yes| Yes| Yes| + | notifyChange | Yes| Yes| Yes| + | insert | Yes| Yes| Yes| + | delete | Yes| Yes| Yes| + | query | Yes| Yes| Yes| + | update | Yes| Yes| Yes| + | batchInsert | Yes| Yes| Yes| + | getType | Yes| No| No| + | getFileTypes | Yes| No| No| + | normalizeUri | Yes| Yes| Yes| + | denormalizeUri | Yes| Yes| Yes| + | openFile | Yes| No| No| + | call | Yes| No| No| + | executeBatch | Yes| No| No| diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md new file mode 100644 index 0000000000000000000000000000000000000000..85dfb9523ca117e691480bcbd2321b5fb3b22304 --- /dev/null +++ b/en/application-dev/application-models/actions-entities.md @@ -0,0 +1,27 @@ +# 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. + + +**Common action Values** + + +- **ACTION_HOME**: action of starting the application entry component. It must be used together with **ENTITY_HOME**. The application icon on the home screen is an explicit entry component. Users can touch the icon to start the entry component. Multiple entry components can be configured for an application. + +- **ACTION_CHOOSE**: action of selecting local resource data, such as Contacts and Gallery. Generally, the system has corresponding Picker applications for different types of data. + +- **ACTION_VIEW_DATA**: action of viewing data. A website URI indicates the action for opening the website. + +- **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. + + +**Common entities Values** + + +- **ENTITY_DEFAULT**: default category, which is meaningless. + +- **ENTITY_HOME**: abilities with an icon displayed on the home screen. + +- **ENTITY_BROWSABLE**: browser type. diff --git a/en/application-dev/application-models/api-switch-overview.md b/en/application-dev/application-models/api-switch-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..bf8223b5a6c047af46e960dad6713f20e251d02f --- /dev/null +++ b/en/application-dev/application-models/api-switch-overview.md @@ -0,0 +1,41 @@ +# API Switching Overview + + +Due to the differences in the thread model and process model, certain APIs (marked with **FAModelOnly** in the SDK) can be used only in the FA model. When switching an application from the FA model to the stage model, replace the APIs marked with **FAModelOnly** in the application with the APIs supported in the stage model. This topic uses the switching of **startAbility()** as an example. + +![api-switch-overview](figures/api-switch-overview.png) + + + +- Sample code of **startAbility()** in the FA model: + + ```ts + import fa from '@ohos.ability.featureAbility'; + let parameter = { + "want": { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.EntryAbility" + } + } + fa.startAbility(parameter).then((data) => { + console.info('startAbility success'); + }).catch((error) => { + console.error('startAbility failed.'); + }) + ``` + +- Sample code of **startAbility()** in the stage model: + + ```ts + // context is a member of the ability object and is required for invoking inside a non-ability object. + // Pass in the Context object. + let wantInfo = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + }; + this.context.startAbility(wantInfo).then((data) => { + console.info('startAbility success.'); + }).catch((error) => { + console.error('startAbility failed.'); + }) + ``` diff --git a/en/application-dev/application-models/app-deviceconfig-switch.md b/en/application-dev/application-models/app-deviceconfig-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..1092c21081cd9a8d62c92a1a68ba434efee7c8c9 --- /dev/null +++ b/en/application-dev/application-models/app-deviceconfig-switch.md @@ -0,0 +1,30 @@ +# Switching of app and deviceConfig + + +To help you better maintain the configuration of application-level attributes, OpenHarmony has extracted the **app** and **deviceConfig** tags from the **config.json** file to the **app.json5** file and changed certain tag names in the stage model. + +**Table 1** Comparison of the app tag in the configuration files + +| Configuration Item| app in config.json| app in app.json5| +| -------- | -------- | -------- | +| Internal version number of an application| "version": {
"code": 1,
} | "versionCode": 1 , | +| Text description of the version number, which is displayed to users| "version": {
"name": "1.0.0",
} | "versionName" : "1.0.0" , | +| Earliest compatible version of the application| "version": {
"minCompatibleVersionCode": 1,
} | "minCompatibleVersionCode" : 1 , | +| Minimum API version required for application running| "apiVersion": {
"compatible": 7,
} | "minAPIVersion" : 7 , | +| Target API version required for application running| "apiVersion": {
"target": 8,
} | "targetApiVersion" : 8 , | +| Type of the target API version required for application running| "apiVersion": {
"releaseType": Release,
} | "apiReleaseType": "Release" , | + + +OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-structure.md) tag of the **config.json** file in the **app.json5** file. It has integrated the fields related to device information under **deviceConfig** into the **app** tag of the [app.json5](../quick-start/app-configuration-file.md) file. + +**Table 2** Comparison of the deviceConfig tag in the configuration files + +| deviceConfig in the FA Model| Description| Stage Model| Difference| +| -------- | -------- | -------- | -------- | +| deviceConfig| Device information.| / | This tag is no longer available in the stage model. In the stage model, device information is configured under the **app** tag.| +| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process.| / | The stage model does not support the configuration of process names.| +| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications.| / | The stage model does not support changing of the model control mode for system applications.| +| supportBackup | Whether the application supports data backup and restore.| / | This configuration is not supported in the stage model.| +| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed.| / | This configuration is not supported in the stage model.| +| network | Network security configuration.| / | This configuration is not supported in the stage model.| + diff --git a/en/application-dev/application-models/application-component-configuration-fa.md b/en/application-dev/application-models/application-component-configuration-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..4cc1c9ad6831f0e54ae4c70f4f7229a7abc7c62f --- /dev/null +++ b/en/application-dev/application-models/application-component-configuration-fa.md @@ -0,0 +1,40 @@ +# Application- or Component-Level Configuration (FA Model) + + +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. + + +- **Configuring the bundle name** + + The bundle name is specified by the **bundleName** field under **app** in the **config.json** file. This field uniquely identifies an application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The bundle name is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first part is the top-level domain **"com"**, and the second part is the vendor or individual name, which can be of multiple levels. For details about the configuration, see [app](../quick-start/app-structure.md). + +- **Configuring the application icon and label** + + The FA model does not support direct configuration of application icons and labels. Instead, the icon and label of a PageAbility component that meet the rules are used as the application icon and label. For details about the rules, see [PageAbility Component](pageability-configuration.md). The icon is specified by the **icon** field under **abilities** in the **config.json** file. The icon must be configured in the resource file on DevEco Studio, and the path of the icon must be **/resource/base/media**. An example value is **$media:ability_icon**. The label is the index of the resource file. It identifies the name of the ability presented to users. The label value can be an ability name or a resource index to the ability name in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon and label of the ability is used as the application icon and label. If multiple abilities address this condition, the icon and label of the first candidate ability is used as the application icon and label. For details about the configuration, see [abilities](../quick-start/module-structure.md). + + ```json + "abilities": [ + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "skills": [ + { + "entities": ["entity.system.home"], + "actions": ["action.system.home"] + } + ] + // ... + } + ``` + +- **Configuring application version declaration** + + To declare the application version, set the **version** field under **app** in the **config.json** file to specify the version number, version name, and earliest compatible version number. For details about the configuration, see [version](../quick-start/module-structure.md). + +- **Configuring device types supported by the module** + + To configure the device types supported by the module, set the **deviceType** field in the **config.json** file. If a certain device type is added to **deviceTypes**, the module can run on that device. For details about the configuration, see [deviceType](../quick-start/module-structure.md). + +- **Configuring the component permission** + + To request component permissions, set the **reqPermission** field under **module** in the **config.json** file. This field declares the name of the permission to request, the reason for requesting the permission, and the scenario where the permission is used. For details about the configuration, see [reqPermission](../quick-start/module-structure.md). + diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..de9e29941b5ddcc9e29f62ddc039fb38b6bc54b6 --- /dev/null +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -0,0 +1,72 @@ +# Application- or Component-Level Configuration (Stage Model) + + +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 + +![application-component-configuration-stage](figures/application-component-configuration-stage.png) + + +- **Configuring the bundle name** + + The bundle name is specified by the **bundleName** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. This field uniquely identifies an application. You are advised to use the reverse domain name notion, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels. + +- **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**. + + 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 **icon** and **label** fields in the **app.json5** file are under **app**, as follows: + + ```json + { + "app": { + "icon": "$media:app_icon", + "label": "$string:app_name" + // ... + } + } + ``` + +- **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. + + ```json + { + "module": { + // ... + "abilities": [ + { + // The information starting with $ is the resource value. + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + } + ] + } + } + ``` +- **Configuring application version declaration** + + To declare the application version, configure the **versionCode** and **versionName** fields in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. **versionCode** specifies the version number of the application. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version. **versionName** provides the text description of the version number. + +- **Configuring device types supported by the module** + + To configure the device types supported by the module, set the **deviceTypes** field in the [module.json5 file](../quick-start/module-configuration-file.md). If a certain device type is added to **deviceTypes**, the module can run on that device. + +- **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-fa.md b/en/application-dev/application-models/application-context-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..9f68b42a873782c9fd1693c73724354cbf347ced --- /dev/null +++ b/en/application-dev/application-models/application-context-fa.md @@ -0,0 +1,66 @@ +# Context (FA Model) + + +There is only one context in the FA model. All capabilities in the context are provided through methods. The context uses these methods to extend the capabilities of the **featureAbility** class. + + +## Available APIs + +To use the context in the FA model, first import the **featureAbility** module. + + +```ts +import featureAbility from "@ohos.ability.featureAbility"; +``` + +Then, call **getContext()** to obtain the **Context** object: + + +```ts +let context = featureAbility.getContext() +``` + +For details about the APIs, see [API Reference](../reference/apis/js-apis-inner-app-context.md). + + +## How to Develop + +1. Query bundle information. + + ```ts + import featureAbility from '@ohos.ability.featureAbility' + export default { + onCreate() { + // Obtain the context and call related APIs. + let context = featureAbility.getContext(); + context.getBundleName((data, bundleName)=>{ + console.info("ability bundleName:" + bundleName) + }); + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +2. Set the display orientation of the host featureAbility. + + ```ts + import featureAbility from '@ohos.ability.featureAbility' + import bundle from '@ohos.bundle'; + + export default { + onCreate() { + // Obtain the context and call related APIs. + let context = featureAbility.getContext(); + context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => { + console.info("Set display orientation.") + }) + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..8d49b7369bb93e26f4407313f2d9352acd7380e1 --- /dev/null +++ b/en/application-dev/application-models/application-context-stage.md @@ -0,0 +1,295 @@ +# Context (Stage Model) + + +## Overview + +[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**. + +- The figure below illustrates the inheritance relationship of contexts. + context-inheritance + +- The figure below illustrates the holding relationship of contexts. + context-holding + +- 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. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let uiAbilityContext = this.context; + // ... + } + } + ``` + - Scenario-specific [ExtensionContext](../reference/apis/js-apis-inner-application-extensionContext.md): For example, ServiceExtensionContext, inherited from ExtensionContext, provides APIs related to background services. + + ```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + export default class MyService extends ServiceExtensionAbility { + onCreate(want) { + let serviceExtensionContext = this.context; + // ... + } + } + ``` + - [AbilityStageContext](../reference/apis/js-apis-inner-application-abilityStageContext.md): module-level context. It provides **HapModuleInfo** and **Configuration** in addition to those provided by the base class **Context**. + + ```ts + import AbilityStage from "@ohos.app.ability.AbilityStage"; + export default class MyAbilityStage extends AbilityStage { + onCreate() { + let abilityStageContext = this.context; + // ... + } + } + ``` + - [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. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let applicationContext = this.context.getApplicationContext(); + // ... + } + } + ``` + + +## Typical Usage Scenarios of Context + + +This topic describes how to use the context in the following scenarios: + + +- [Obtaining the Application Development Path](#obtaining-the-application-development-path) +- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas) +- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) +- [Subscribing to Ability Lifecycle Changes in a Process](#subscribing-to-ability-lifecycle-changes-in-a-process) + + +### Obtaining the Application Development Path + +The following table describes the application development paths obtained from context. + +**Table 1** Application development paths + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.
It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| +| tempDir | string | Yes| No| Temporary file directory of the application.
Files in this directory are deleted after the application is uninstalled.| +| filesDir | string | Yes| No| File directory of the application on the internal storage.
Files in this directory may be synchronized to other directories during application migration or backup.| +| databaseDir | string | Yes| No| Storage directory of the local database.| +| bundleCodeDir | string | Yes| No| Installation directory of the application on the internal storage.| +| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| +| preferencesDir | string | Yes| Yes| Preferences directory of the application.| + +The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below. + +**Figure 1** Application development paths obtained from context +context-dir + +- Obtain the application-level path through **ApplicationContext**. It is recommended that global application information be stored in this path. Files stored in this path will be deleted only when the application is uninstalled. + | Name| Path| + | -------- | -------- | + | bundleCodeDir | {Path prefix}/el1/bundle/| + | cacheDir | {Path prefix}/{Encryption level}/base/cache/| + | filesDir | {Path prefix}/{Encryption level}/base/files/| + | preferencesDir | {Path prefix}/{Encryption level}/base/preferences/| + | tempDir | {Path prefix}/{Encryption level}/base/temp/| + | databaseDir | {Path prefix}/{Encryption level}/database/| + | distributedFilesDir | {Path prefix}/el2/distributedFiles/| + +- Obtain the HAP level path through **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. It is recommended that the HAP information be stored in this path. The file content stored in this path will be deleted when the HAP is uninstalled. The file content in the application-level path will be deleted only after all the HAPs of the application are uninstalled. + | Name| Path| + | -------- | -------- | + | bundleCodeDir | {Path prefix}/el1/bundle/| + | cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/| + | filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/| + | preferencesDir | {path prefix}/{encryption level}/base/**haps/{moduleName}**/preferences/| + | tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/| + | databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/| + | distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/| + +The sample code for obtaining the application development paths is as follows: + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let cacheDir = this.context.cacheDir; + let tempDir = this.context.tempDir; + let filesDir = this.context.filesDir; + let databaseDir = this.context.databaseDir; + let bundleCodeDir = this.context.bundleCodeDir; + let distributedFilesDir = this.context.distributedFilesDir; + let preferencesDir = this.context.preferencesDir; + // ... + } +} +``` + + +### Obtaining and Modifying Encrypted Areas + +You can read and write [the area attribute in the context](../reference/apis/js-apis-inner-application-context.md) to obtain and set an encrypted area. Two encryption levels are supported: + +- AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on. + +- AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time). + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // Before storing common information, switch the encryption level to EL1. + if (this.context.area === 1) {// Obtain the area. + this.context.area = 0; // Modify the area. + } + // Store common information. + + // Before storing sensitive information, switch the encryption level to EL2. + if (this.context.area === 0) { // Obtain the area. + this.context.area = 1; // Modify the area. + } + // Store sensitive information. + } +} +``` + + +### Creating Context of Another Application or Module + +The base class **Context** provides the [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) methods for creating the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules. + +- Call **createBundleContext(bundleName:string)** to create the context of another application. + > **NOTE** + > + > 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. + + 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'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let bundleName2 = "com.example.application"; + let context2 = this.context.createBundleContext(bundleName2); + let label2 = context2.applicationInfo.label; + // ... + } + } +``` + +- 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** + > + > 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. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let bundleName2 = "com.example.application"; + let moduleName2 = "module1"; + let context2 = this.context.createModuleContext(bundleName2, moduleName2); + // ... + } + } + ``` + +- 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 + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let moduleName2 = "module1"; + let context2 = this.context.createModuleContext(moduleName2); + // ... + } + } + ``` + + +### Subscribing to Ability Lifecycle Changes in a Process + +In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to ability lifecycle changes. + +When the ability lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered, and a listener ID is returned. The ID is incremented by 1 each time the listener is registered. When the number of listeners exceeds the upper limit (2^63-1), -1 is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +const TAG: string = "[Example].[Entry].[EntryAbility]"; + +export default class EntryAbility extends UIAbility { + lifecycleId: number; + + onCreate(want, launchParam) { + let abilityLifecycleCallback = { + onAbilityCreate(ability) { + console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability)); + }, + onWindowStageCreate(ability, windowStage) { + console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability)); + console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageActive(ability, windowStage) { + console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability)); + console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageInactive(ability, windowStage) { + console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability)); + console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageDestroy(ability, windowStage) { + console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + }, + onAbilityDestroy(ability) { + console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityForeground(ability) { + console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability)); + }, + onAbilityBackground(ability) { + console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability)); + }, + onAbilityContinue(ability) { + console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability)); + } + } + // 1. Obtain the application context through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Register a listener for the lifecycle changes through the application context. + this.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); + console.info(TAG, "register callback number: " + JSON.stringify(this.lifecycleId)); + } + + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.off("abilityLifecycle", this.lifecycleId, (error, data) => { + console.info(TAG, "unregister callback success, err: " + JSON.stringify(error)); + }); + } +} +``` diff --git a/en/application-dev/application-models/application-model-composition.md b/en/application-dev/application-models/application-model-composition.md new file mode 100644 index 0000000000000000000000000000000000000000..2d7ed88490136c6e94277e94da375278fcab0adf --- /dev/null +++ b/en/application-dev/application-models/application-model-composition.md @@ -0,0 +1,27 @@ +# Elements of the Application Model + + +The application model is the abstraction of capabilities required by OpenHarmony applications. It provides necessary components and running mechanisms for applications. With application models, you can develop applications based on a unified set of models, making application development simpler and more efficient. + + +The OpenHarmony application model consists of the following elements: + + +- Application component + + An application component is the basic unit and running entry of an application. When a user starts, uses, or exits an application, the application component transits in different states. This is called the application component lifecycle. The application component provides lifecycle callback functions, through which you can detect application [status changes](uiability-lifecycle.md). When compiling an application, you needs to compile application components and their lifecycle callback functions, and configure related information in the application configuration file. In this way, the operating system creates an application component instance based on the configuration file during running, and schedules the lifecycle callback functions, so as to execute your code. +- Application process model + + The application process model defines how application processes are created, destroyed, and communicate with each other. + +- Application thread model + + The application thread model defines how a thread in an application process is created and destroyed, how the main thread and UI thread are created, and how the threads communicate with each other. + +- Application mission management model + + The application mission management model defines how a mission is created and destroyed, and the relationship between missions and components. A mission is a record about the use of an application component instance. Each time a user starts an application component instance, a mission is generated. For example, when a user starts a video application, the video application mission is displayed on the **Recents** page. When the user clicks the mission, the system switches the mission to the foreground. If the video editing functionality in the video application is compiled by using an application component, an application component instance for video editing is created when the user starts video editing. In this case, both the video application mission and video editing mission are displayed on the **Recents** page. + +- Application configuration file + + The application configuration file contains information about the application configuration, application components, and permissions, as well as custom information. The information will be provided for the compiler, application market, and operating system in the build, distribution, and running phases. diff --git a/en/application-dev/application-models/application-model-description.md b/en/application-dev/application-models/application-model-description.md new file mode 100644 index 0000000000000000000000000000000000000000..de7e3045d79eff2c681291f8d4de55129d361245 --- /dev/null +++ b/en/application-dev/application-models/application-model-description.md @@ -0,0 +1,60 @@ +# Interpretation of the Application Model + + +## Application Model Overview + +Along its evolution, OpenHarmony has provided two application models: + +- Feature Ability (FA) model. This model is supported by OpenHarmony API version 7 and 8. It is no longer recommended. + +- Stage model. This model is supported since OpenHarmony API version 9. It is recommended and will evolve for a long time. In this model, classes such as **AbilityStage** and **WindowStage** are provided as the stage of application components and windows. That's why it is named stage model. + +The stage model is designed based on the following considerations, which make it become the recommended model: + +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. + +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** + + The stage model decouples application components from User Interfaces (UIs). + + - In cross-device migration scenarios, after the system migrates application component data or status between devices, it can use the declarative feature of ArkUI to restore the UI based on the data or status saved in the application components. + + - In multi-device collaboration scenarios, application components can initiate Remote Procedure Calls (RPCs) and support interaction with cross-device application components. + +3. **Support for multiple device types and window forms** + + Application component management and window management are decoupled at the architecture level. This decoupling makes it: + + - Easy to tailor application components. For example, windows can be tailored for devices without screens. + + - Easy to extend the window forms. + + - Possible for application components to use the same lifecycle on multiple devices (such as desktop devices and mobile devices). + +4. **Well balanced application capabilities and system management costs** + + The stage model redefines the boundary of application capabilities to well balance application capabilities and system management costs. + + - Diverse application components (such as widgets and input methods) for specific scenarios. + - Standardized background process management. To deliver a better user experience, the stage model manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. + + +## Differences Between the FA Model and Stage Model + +In the stage model, multiple application components share the same ArkTS engine instance. In the FA model, each application component exclusively uses an ArkTS engine instance. This is their biggest difference. In the stage model, application components can easily share objects and status while requiring less memory. Therefore, you are advised to use the stage model when developing complex applications in distributed scenarios. + +The table below describes their differences in detail. + + **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). | +| **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/background-services.md b/en/application-dev/application-models/background-services.md new file mode 100644 index 0000000000000000000000000000000000000000..77ed5d98c0798037e57f2867b8e216928bfc2240 --- /dev/null +++ b/en/application-dev/application-models/background-services.md @@ -0,0 +1,7 @@ +# Background Services (Stage Model) + + +The stage model uses ServiceExtensionAbility to provide background services. A system application can implement a background service and provide external capabilities. For example, if system application A implements a background service, third-party application B can communicate with A by connecting to A's background service. + + +For details about ServiceExtensionAbility, see [Background Service Development](serviceextensionability.md). diff --git a/en/application-dev/application-models/bind-serviceability-from-stage.md b/en/application-dev/application-models/bind-serviceability-from-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..2d99fddfe503db082cf7613f3875dcf490331dd9 --- /dev/null +++ b/en/application-dev/application-models/bind-serviceability-from-stage.md @@ -0,0 +1,90 @@ +# Connecting to a ServiceAbility from the Stage Model + + +This topic describes how the two application components of the stage model connect to the ServiceAbility component of the FA model. + + +## UIAbility Accessing a ServiceAbility + +A UIAbility accesses a ServiceAbility in the same way as it accesses a ServiceExtensionAbility. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.info("EntryAbility onCreate"); + } + onDestroy() { + console.info("EntryAbility onDestroy") + } + onWindowStageCreate(windowStage) { + console.info("EntryAbility onWindowStageCreate") + let want = { + bundleName: "com.ohos.fa", + abilityName: "ServiceAbility", + }; + + let options = { + onConnect:function (elementName, proxy) { + console.info("onConnect called."); + }, + onDisconnect:function (elementName) { + console.info("onDisconnect called."); + }, + onFailed:function (code) { + console.info("onFailed code is: " + code); + } + }; + let connectionId = this.context.connectServiceExtensionAbility(want, options); + } + onWindowStageDestroy() { + console.info("EntryAbility onWindowStageDestroy") + } + onForeground() { + console.info("EntryAbility onForeground") + } + onBackground() { + console.info("EntryAbility onBackground") + } +} +``` + + +## ExtensionAbility Accessing a ServiceAbility + +The following uses the ServiceExtensionAbility component as an example to describe how an ExtensionAbility accesses a ServiceAbility. A ServiceExtensionAbility accesses a ServiceAbility in the same way as it accesses another ServiceExtensionAbility. + + +```ts +import Extension from '@ohos.app.ability.ServiceExtensionAbility' + +export default class ServiceExtension extends Extension { + onCreate(want) { + console.info("ServiceExtension onCreate") + } + onDestroy() { + console.info("ServiceExtension onDestroy") + } + onRequest(want, startId) { + console.info("ServiceExtension onRequest") + let wantFA = { + bundleName: "com.ohos.fa", + abilityName: "ServiceAbility", + }; + let options = { + onConnect:function (elementName, proxy) { + console.info("onConnect called."); + }, + onDisconnect:function (elementName) { + console.info("onDisconnect called."); + }, + onFailed:function (code) { + console.info("onFailed code is: " + code); + } + }; + let connectionId = this.context.connectServiceExtensionAbility(wantFA, options); + } +} +``` diff --git a/en/application-dev/application-models/bind-serviceextensionability-from-fa.md b/en/application-dev/application-models/bind-serviceextensionability-from-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..e5f90bf9d6b7616261d2ae1eb1e62438fe2e71e3 --- /dev/null +++ b/en/application-dev/application-models/bind-serviceextensionability-from-fa.md @@ -0,0 +1,60 @@ +# Connecting to a ServiceExtensionAbility from the FA Model + + +This topic describes how the three application components of the FA model connect to the ServiceExtensionAbility component of the stage model. + + +## PageAbility Accessing a ServiceExtensionAbility + +A PageAbility accesses a ServiceExtensionAbility in the same way as it accesses a ServiceAbility. + + +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +let want = { + bundleName: "com.ohos.stage", + abilityName: "com.ohos.stage.ServiceExtensionAbility" +}; + +let faConnect = { + onConnect:function (elementName, proxy) { + console.info("Faconnection onConnect called."); + }, + onDisconnect:function (elementName) { + console.info("Faconnection onDisconnect called."); + }, + onFailed:function (code) { + console.info("Faconnection onFailed code is: " + code); + } +}; +let connectionId = featureAbility.connectAbility(want, faConnect); +``` + + +## ServiceAbility or DataAbility Accessing a ServiceExtensionAbility + +A ServiceAbility or DataAbility accesses a ServiceExtensionAbility in the same way as it accesses a ServiceAbility. + + +```ts +import particleAbility from '@ohos.ability.particleAbility'; + +let want = { + bundleName: "com.ohos.stage", + abilityName: "com.ohos.stage.ServiceExtensionAbility" +}; + +let faConnect = { + onConnect:function (elementName, proxy) { + console.info("Faconnection onConnect called."); + }, + onDisconnect:function (elementName) { + console.info("Faconnection onDisconnect called."); + }, + onFailed:function (code) { + console.info("Faconnection onFailed code is: " + code); + } +}; +let connectionId = particleAbility.connectAbility(want, faConnect); +``` diff --git a/en/application-dev/application-models/common-event-fa.md b/en/application-dev/application-models/common-event-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..9e2f44144d8f028c61c538b48797f5842a48d2a7 --- /dev/null +++ b/en/application-dev/application-models/common-event-fa.md @@ -0,0 +1,4 @@ +# Common Events (FA Model) + + +For details, see [Common Events](common-event-overview.md) in the stage model. diff --git a/en/application-dev/application-models/common-event-overview.md b/en/application-dev/application-models/common-event-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..0d3788b41b516d0af9619d320ceeefc3f52c74c5 --- /dev/null +++ b/en/application-dev/application-models/common-event-overview.md @@ -0,0 +1,28 @@ +# Introduction to Common Events + + +OpenHarmony provides Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. + + +Common events are classified into system common events and custom common events. + + +- System common events: defined in CES. Only system applications and system services can publish system common events, such as HAP installation, update, and uninstall. For details about the supported system common events, see [Support](../reference/apis/js-apis-commonEventManager.md#support). + +- Custom common events: customized by applications to implement cross-process event communication. + + +Common events are also classified into unordered, ordered, and sticky common events. + + +- Unordered common events: CES forwards common events based on the subscription sequence, regardless of whether subscribers receive the events. + +- Ordered common event: CES forwards common events to the next subscriber only after receiving a reply from the previous subscriber. + +- Sticky common event: a public event that can be sent to a subscriber before they initiate a subscription. Only system applications or system services can send sticky common event, and they must request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + + +Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. + +**Figure 1** Common events +![common-event](figures/common-event.png) \ No newline at end of file diff --git a/en/application-dev/application-models/common-event-publish.md b/en/application-dev/application-models/common-event-publish.md new file mode 100644 index 0000000000000000000000000000000000000000..b29c137319fcbb1fe4eaff8e262dca1a403c87e4 --- /dev/null +++ b/en/application-dev/application-models/common-event-publish.md @@ -0,0 +1,78 @@ +# Publishing Common Events + + +## When to Use + +You can use [publish()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerpublish) to publish a custom common event, which can carry data for subscribers to parse and process. + +> **NOTE** +> +> Subscribers can receive sticky common events that have been sent. However, they must subscribe to common events of other types before receiving them. For details about subscription, see [Subscribing to Common Events](common-event-subscription.md). + + +## Available APIs + +For details about the APIs, see [API Reference](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerpublish). + +| API| Description| +| -------- | -------- | +| publish(event: string, callback: AsyncCallback) | Publishes a common event.| +| publish(event: string, options: [CommonEventPublishData](../reference/apis/js-apis-commonEventManager.md#commoneventpublishdata), callback: AsyncCallback) | Publishes a common event with given attributes.| + + +## Publishing a Common Event That Does Not Carry Information + +Common events that do not carry information can be published only as unordered common events. + +1. Import the **commonEventManager** module. + + ```ts + import commonEventManager from '@ohos.commonEventManager'; + ``` + +2. Pass in the common event name and callback, and publish the event. + + ```ts + // Publish a common event. + commonEventManager.publish("usual.event.SCREEN_OFF", (err) => { + if (err) { + console.error(`[CommonEvent] PublishCallBack err=${JSON.stringify(err)}`); + } else { + console.info(`[CommonEvent] Publish success`); + } + }) + ``` + + +## Publishing a Common Event That Carries Information + +Common events that carry information can be published as unordered, ordered, and sticky common events, which are specified by the **isOrdered** and **isSticky** fields of [CommonEventPublishData](../reference/apis/js-apis-commonEventManager.md#commoneventpublishdata). + +1. Import the **commonEventManager** module. + + ```ts + import commonEventManager from '@ohos.commonEventManager'; + ``` + +2. Pass in the common event name and callback, and publish the event. + + ```ts + // Attributes of a common event. + let options = { + code: 1, // Result code of the common event. + data: "initial data", // Result data of the common event. + } + ``` + +3. Pass in the common event name, attributes of the common event, and callback, and publish the event. + + ```ts + // Publish a common event. + commonEventManager.publish("usual.event.SCREEN_OFF", options, (err) => { + if (err) { + console.error('[CommonEvent] PublishCallBack err=' + JSON.stringify(err)); + } else { + console.info('[CommonEvent] Publish success') + } + }) + ``` diff --git a/en/application-dev/application-models/common-event-subscription.md b/en/application-dev/application-models/common-event-subscription.md new file mode 100644 index 0000000000000000000000000000000000000000..ce61e40458a7cbd5c9ec226138535da93d3766b1 --- /dev/null +++ b/en/application-dev/application-models/common-event-subscription.md @@ -0,0 +1,69 @@ +# Subscribing to Common Events + + +## When to Use + +You can create a subscriber object to subscribe to a common event so as to obtain the parameters passed in the event. Certain system common events [require specific permissions](../security/accesstoken-guidelines.md) to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEventManager.md#support). + + +## Available APIs + +For details about the APIs, see [API Reference](../reference/apis/js-apis-commonEventManager.md#commoneventmanagersubscribe). + +| API| Description| +| -------- | -------- | +| createSubscriber(subscribeInfo: [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo), callback: AsyncCallback<[CommonEventData](../reference/apis/js-apis-commonEventManager.md#commoneventdata)>): void | Creates a subscriber. This API uses an asynchronous callback to return the result.| +| createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber> | Creates a subscriber. This API uses a promise to return the result.| +| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback): void | Subscribes to common events.| + + +## How to Develop + +1. Import the **commonEventManager** module. + + ```ts + import commonEventManager from '@ohos.commonEventManager'; + ``` + +2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEventManager.md#commoneventsubscribeinfo). + + ```ts + // Used to save the created subscriber object for subsequent subscription and unsubscription. + let subscriber = null; + // Subscriber information. + let subscribeInfo = { + events: ["usual.event.SCREEN_OFF"], // Subscribe to the common event screen-off. + } + ``` + +3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. + + ```ts + // Callback for subscriber creation. + commonEventManager.createSubscriber(subscribeInfo, (err, data) => { + if (err) { + console.error(`[CommonEvent] CreateSubscriberCallBack err=${JSON.stringify(err)}`); + } else { + console.info(`[CommonEvent] CreateSubscriber success`); + subscriber = data; + // Callback for common event subscription. + } + }) + ``` + +4. Create a subscription callback, which is triggered when an event is received. The data returned in the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEventManager.md#commoneventdata). + + ```ts + // Callback for common event subscription. + if (subscriber !== null) { + commonEventManager.subscribe(subscriber, (err, data) => { + if (err) { + console.error(`[CommonEvent] SubscribeCallBack err=${JSON.stringify(err)}`); + } else { + console.info(`[CommonEvent] SubscribeCallBack data=${JSON.stringify(data)}`); + } + }) + } else { + console.error(`[CommonEvent] Need create subscriber`); + } + ``` diff --git a/en/application-dev/application-models/common-event-unsubscription.md b/en/application-dev/application-models/common-event-unsubscription.md new file mode 100644 index 0000000000000000000000000000000000000000..c87017ef08c05e8a22097c4bd2a05f52fc758134 --- /dev/null +++ b/en/application-dev/application-models/common-event-unsubscription.md @@ -0,0 +1,40 @@ +# Unsubscribing from Common Events + + +## When to Use + +You can call [unsubscribe()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerunsubscribe) to unsubscribe from a common event that is no longer required. + + +## Available APIs + +| API| Description| +| -------- | -------- | +| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| + + +## How to Develop + +1. Import the **commonEventManager** module. + + ```ts + import commonEventManager from '@ohos.commonEventManager'; + ``` + +2. Subscribe to an event by following the procedure described in [Subscribing to Common Events](common-event-subscription.md). + +3. Call **unsubscribe** in **CommonEvent** to unsubscribe from the common event. + + ```ts + // The subscriber object iscreated during event subscription. + if (subscriber !== null) { + commonEventManager.unsubscribe(subscriber, (err) => { + if (err) { + console.error(`[CommonEvent] UnsubscribeCallBack err=${JSON.stringify(err)}`); + } else { + console.info(`[CommonEvent] Unsubscribe`); + subscriber = null; + } + }) + } + ``` diff --git a/en/application-dev/application-models/component-startup-rules-fa.md b/en/application-dev/application-models/component-startup-rules-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..db64e8c093df679a9e52d6bc753e4935a21c25be --- /dev/null +++ b/en/application-dev/application-models/component-startup-rules-fa.md @@ -0,0 +1,69 @@ +# Component Startup Rules (FA Model) + + +Component startup refers to the behavior of starting or connecting to an application component. + + +- Start the PageAbility and ServiceAbility. For example, you can use **startAbility()**. + +- Connect to the ServiceAbility and DataAbility. For example, you can use **connectAbility()** and **acquireDataAbilityHelper()**. + + +To deliver a better user experience, OpenHarmony restricts the following behavior: + + +- A background application randomly displays a dialog box, such as an ads pop-up. + +- Background applications wake up each other. This type of behavior occupies system resources and increases power consumption, or even causes system frozen. + +- A foreground application randomly redirects to another application, for example, redirecting to the payment page of another application. This type of behavior poses security risks. + + +In view of this, OpenHarmony formulates a set of component startup rules, as follows: + + +- **Before starting a component of another application, verify the visible field of the target component.** + - This rule applies only to cross-application scenarios. + - If the **visible** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities). + +- **Before starting a component of a background application, verify the BACKGROUND permission.** + - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. + - Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + +- **Before starting the ServiceAbility or DataAbility component of an application, verify the AssociateWakeUp field of the target application.** + - This rule applies only to cross-application scenarios. + - This rule is valid only when the target component is ServiceAbility or DataAbility. + - The ServiceAbility and DataAbility of an application can be accessed by others only when **AssociateWakeUp** of the target application is set to **true**. + - The **AssociateWakeUp** field can be configured only for preset applications. For other applications, this field is set to **false** by default. + + +> **NOTE** +> 1. Component startup control has been implemented since OpenHarmony v3.2 Release. +> +> 2. The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. + + + + +## Intra-Device Component Startup Rules + + The rules for starting components on the same device vary in the following scenarios: + +- Starting a PageAbility + +- Starting a ServiceAbility or DataAbility + +![startup-rule](figures/component-startup-inner-fa.png) + + +## Inter-Device Component Startup Rules + + The rules for starting components on a different device vary in the following scenarios: + +- Starting a PageAbility + +- Starting a ServiceAbility + +![component-startup-rules](figures/component-startup-inter-fa.png) + diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..0e6c2ce33c68913221c7b09f02e96327b0ea1c30 --- /dev/null +++ b/en/application-dev/application-models/component-startup-rules.md @@ -0,0 +1,64 @@ +# Component Startup Rules (Stage Model) + + +Component startup refers to the behavior of starting or connecting to an application component. + + +- Start the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components. For example, you can use **startAbility()**, **startServiceExtensionAbility()**, and **startAbilityByCall()**. + +- Connect to the ServiceExtensionAbility and DataShareExtensionAbility components. For example, you can use **connectServiceExtensionAbility()** and **createDataShareHelper()**. + + +To deliver a better user experience, OpenHarmony restricts the following behavior: + + +- A background application randomly displays a dialog box, such as an ads pop-up. + +- Background applications wake up each other. This type of behavior occupies system resources and increases power consumption, or even causes system frozen. + +- A foreground application randomly redirects to another application, for example, redirecting to the payment page of another application. This type of behavior poses security risks. + + +In view of this, OpenHarmony formulates a set of component startup rules, as follows: + + +- **Before starting a component of another application, verify the visible field of the target component.** + - If the **visible** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details, see [Component Visible Configuration](../quick-start/module-configuration-file.md#abilities). + +- **Before starting a component of a background application, verify the BACKGROUND permission.** + - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. + - Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + +- **When the startAbilityByCall() method is used, verify the call permission.** For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call). + - Verify the **ohos.permission.ABILITY_BACKGROUND_COMMUNICATION** permission. + + +> **NOTE** +> +> - Component startup control has been implemented since OpenHarmony v3.2 Release. +> +> - The new component startup rules are more strict than the original ones. You must be familiar with the new startup rules to prevent service exceptions. + + +## Intra-Device Component Startup Rules + + The rules for starting components on the same device vary in the following scenarios: + +- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components + +- Using **startAbilityByCall()** to start the UIAbility component + +![startup-rule](figures/component-startup-inner-stage.png) + + +## Inter-Device Component Startup Rules + + The rules for starting components on a different device vary in the following scenarios: + +- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components + +- Using **startAbilityByCall()** to start the UIAbility component + +![component-startup-rules](figures/component-startup-inter-stage.png) + diff --git a/en/application-dev/application-models/config-file-fa.md b/en/application-dev/application-models/config-file-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..3f550aa6192faeab625b9f65884fb0bbc7e79e15 --- /dev/null +++ b/en/application-dev/application-models/config-file-fa.md @@ -0,0 +1,6 @@ +# Application Configuration File (FA Model) + +The application configuration file contains information about the application configuration, application components, and permissions, as well as custom information. The information will be provided for the compiler, application market, and operating system in the build, distribution, and running phases. + +The application project code developed based on the FA model contains a **config.json** file. For details about common configuration items, see [Application- or Component-Level Configuration](application-component-configuration-fa.md). For details about the file, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md). + diff --git a/en/application-dev/application-models/config-file-stage.md b/en/application-dev/application-models/config-file-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..66cabf4a99fd4a3f5138c0a8ef1bbf2cefbe15c0 --- /dev/null +++ b/en/application-dev/application-models/config-file-stage.md @@ -0,0 +1,6 @@ +# Application Configuration File (Stage Model) + +The application configuration file contains information about the application configuration, application components, and permissions, as well as custom information. The information will be provided for the compiler, application market, and operating system in the build, distribution, and running phases. + +The application project code developed based on the stage model contains one **app.json5** file and one or more **module.json5** files. For details about common configuration items, see [Application- or Component-Level Configuration (Stage Model)](application-component-configuration-stage.md). For details about the two files, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md). + diff --git a/en/application-dev/application-models/configuration-file-diff.md b/en/application-dev/application-models/configuration-file-diff.md new file mode 100644 index 0000000000000000000000000000000000000000..745f2702cab12b8ef99e174c924d49cf2217bf2b --- /dev/null +++ b/en/application-dev/application-models/configuration-file-diff.md @@ -0,0 +1,11 @@ +# Differences in Configuration Files + + +The FA model uses the [config.json file](../quick-start/application-configuration-file-overview-fa.md) to describe the basic information about an application. An application can have multiple modules, and each module has a **config.json** file. The **config.json** file consists of three parts: **app**, **deviceConfig**, and **module**. The **app** tag is used to configure application-level attributes. If an application has multiple modules, the **app** configuration in each **config.json** file must be consistent. + + +The stage model uses the [app.json5](../quick-start/app-configuration-file.md) and [module.json](../quick-start/module-configuration-file.md) files to describe the basic information about an application. An application can have multiple modules but only one **app.json5** file. This file is used to configure application-level attributes and takes effect for all the modules. Each module has a **module.json5** file, which is used to configure module-level attributes and takes effect only for the current module. + +**Figure 1** Configuration file differences +![comparison-of-configuration-file](figures/comparison-of-configuration-file.png) + diff --git a/en/application-dev/application-models/connect-serviceability.md b/en/application-dev/application-models/connect-serviceability.md new file mode 100644 index 0000000000000000000000000000000000000000..ac2acb898a3bd7ef905b8a33dc10f7980ce74548 --- /dev/null +++ b/en/application-dev/application-models/connect-serviceability.md @@ -0,0 +1,93 @@ +# Connecting to a ServiceAbility + + +If a ServiceAbility wants to interact with a PageAbility or a ServiceAbility in another application, you must first create a connection by calling **connectAbility()**. This method is defined in the **featureAbility** class for the PageAbility and in the **particleAbility** class for the ServiceAbility. For details about the connection rules, see [Component Startup Rules](component-startup-rules.md). When calling **connectAbility()**, you should pass in a **Want** object containing information about the target ServiceAbility and an **IAbilityConnection** object. **IAbilityConnection** provides the following APIs that you need to implement. + +**Table 1** IAbilityConnection APIs + +| API| Description| +| -------- | -------- | +| onConnect() | Callback invoked when the ServiceAbility is connected.| +| onDisconnect() | Callback invoked when the ServiceAbility is disconnected.| +| onFailed() | Callback invoked when the connection to the ServiceAbility fails.| + + +The following sample code enables the PageAbility to create connection callback instances and connect to the local ServiceAbility: + +```ts +import rpc from "@ohos.rpc" +import prompt from '@system.prompt' +import featureAbility from '@ohos.ability.featureAbility' + +let option = { + onConnect: function onConnectCallback(element, proxy) { + console.info(`onConnectLocalService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) + prompt.showToast({ + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.info(`onConnectLocalService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.info(`onConnectLocalService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } +} + +let request = { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.ServiceAbility", +} +let connId = featureAbility.connectAbility(request, option) +``` + + +When the ServiceAbility is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the ServiceAbility. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**. + + +The following sample code shows how the ServiceAbility returns itself to the caller: + +```ts +import rpc from "@ohos.rpc" + +class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { + if (typeof des === 'string') { + super(des) + } else { + return + } + } + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.info(`onRemoteRequest called`) + if (code === 1) { + let string = data.readString() + console.info(`string=${string}`) + let result = Array.from(string).sort().join('') + console.info(`result=${result}`) + reply.writeString(result) + } else { + console.info(`unknown request code`) + } + return true + } +} +``` diff --git a/en/application-dev/application-models/context-switch.md b/en/application-dev/application-models/context-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..2f52158f5d36be8c59f747376195e9e43078d1f9 --- /dev/null +++ b/en/application-dev/application-models/context-switch.md @@ -0,0 +1,28 @@ +# Context Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API or Field in the Stage Model| +| -------- | -------- | -------- | +| [getOrCreateLocalDir(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatelocaldir7)
[getOrCreateLocalDir():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatelocaldir7-1) | There is no corresponding API in the stage model.| Applications developed on the stage model do not have the operation permission in the application root directory. Therefore, no corresponding API is provided.| +| [verifyPermission(permission:string,options:PermissionOptions,callback:AsyncCallback<number>):void;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7)
[verifyPermission(permission:string,callback:AsyncCallback<number>):void;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7-1)
[verifyPermission(permission:string,options?:PermissionOptions):Promise<number>;](../reference/apis/js-apis-inner-app-context.md#contextverifypermission7-2) | \@ohos.abilityAccessCtrl.d.ts | [verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus;](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstokensync9)
[verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus>;](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstoken9) | +| [requestPermissionsFromUser(permissions:Array<string>,requestCode:number,resultCallback:AsyncCallback<PermissionRequestResult>):void;](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7)
[requestPermissionsFromUser(permissions:Array<string>,requestCode:number):Promise<PermissionRequestResult>;](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7-1) | application\UIAbilityContext.d.ts | [requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextrequestpermissionsfromuser)
[requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextrequestpermissionsfromuser-1) | +| [getApplicationInfo(callback:AsyncCallback<ApplicationInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationinfo7)
[getApplicationInfo():Promise<ApplicationInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationinfo7-1) | application\Context.d.ts | [applicationInfo: ApplicationInfo;](../reference/apis/js-apis-inner-application-context.md#attributes)| +| [getBundleName(callback : AsyncCallback<string>): void;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7)
[getBundleName(): Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetbundlename7-1) | application\UIAbilityContext.d.ts | [abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| +| [getDisplayOrientation(callback : AsyncCallback<bundle.DisplayOrientation>): void;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7)
[getDisplayOrientation(): Promise<bundle.DisplayOrientation>;](../reference/apis/js-apis-inner-app-context.md#contextgetdisplayorientation7-1) | \@ohos.screen.d.ts | [readonly orientation: Orientation;](../reference/apis/js-apis-screen.md#orientation) | +| [setDisplayOrientation(orientation:bundle.DisplayOrientation, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7)
[setDisplayOrientation(orientation:bundle.DisplayOrientation):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetdisplayorientation7-1) | \@ohos.screen.d.ts | [setOrientation(orientation: Orientation, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-screen.md#setorientation)
[setOrientation(orientation: Orientation): Promise<void>;](../reference/apis/js-apis-screen.md#setorientation-1) | +| [setShowOnLockScreen(show:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreen7)
[setShowOnLockScreen(show:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetshowonlockscreen7-1) | \@ohos.window.d.ts | [setShowOnLockScreen(showOnLockScreen: boolean): void;](../reference/apis/js-apis-window.md#setshowonlockscreen9) | +| [setWakeUpScreen(wakeUp:boolean, callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextsetwakeupscreen7)
[setWakeUpScreen(wakeUp:boolean):Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextsetwakeupscreen7-1) | \@ohos.window.d.ts | [setWakeUpScreen(wakeUp: boolean): void;](../reference/apis/js-apis-window.md#setwakeupscreen9) | +| [getProcessInfo(callback:AsyncCallback<ProcessInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessinfo7)
[getProcessInfo():Promise<ProcessInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessinfo7-1) | \@ohos.app.ability.abilityManager.d.ts | [getAbilityRunningInfos(callback: AsyncCallback<Array<AbilityRunningInfo>>): void;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos)
[getAbilityRunningInfos(): Promise<Array<AbilityRunningInfo>>;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos-1) | +| [getElementName(callback:AsyncCallback<ElementName>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetelementname7)
[getElementName():Promise<ElementName>;](../reference/apis/js-apis-inner-app-context.md#contextgetelementname7-1) | application\UIAbilityContext.d.ts | [abilityInfo.name: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)
[abilityInfo.bundleName: string;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| +| [getProcessName(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessname7)
[getProcessName():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetprocessname7-1) | \@ohos.app.ability.abilityManager.d.ts | [getAbilityRunningInfos(callback: AsyncCallback<Array<AbilityRunningInfo>>): void;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos)
[getAbilityRunningInfos(): Promise<Array<AbilityRunningInfo>>;](../reference/apis/js-apis-app-ability-abilityManager.md#getabilityrunninginfos-1) | +| [getCallingBundle(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetcallingbundle7)
[getCallingBundle():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetcallingbundle7-1) | There is no corresponding API in the stage model.| Applications developed on the stage model can use the **ohos.aafwk.param.callerUid** parameter of **Want.parameters** to obtain the application information of the caller.| +| [getFilesDir(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir)
[getFilesDir():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir-1) | application\Context.d.ts | [filesDir: string;](../reference/apis/js-apis-inner-application-context.md#attributes)| +| [getCacheDir(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetcachedir)
[getCacheDir():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetcachedir-1) | application\Context.d.ts | [cacheDir: string;](../reference/apis/js-apis-inner-application-context.md#attributes)| +| [getOrCreateDistributedDir(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatedistributeddir7)
[getOrCreateDistributedDir():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetorcreatedistributeddir7-1) | application\Context.d.ts | [distributedFilesDir: string;](../reference/apis/js-apis-inner-application-context.md#attributes)| +| [getAppType(callback:AsyncCallback<string>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetapptype7)
[getAppType():Promise<string>;](../reference/apis/js-apis-inner-app-context.md#contextgetapptype7-1) | application\UIAbilityContext.d.ts | The stage model obtains the application type through the **type** attribute of the **abilityInfo** field.
[abilityInfo.type: bundleManager.AbilityType;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| +| [getHapModuleInfo(callback:AsyncCallback<HapModuleInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgethapmoduleinfo7)
[getHapModuleInfo():Promise<HapModuleInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgethapmoduleinfo7-1) | application\UIAbilityContext.d.ts | [currentHapModuleInfo: HapModuleInfo;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| +| [getAppVersionInfo(callback:AsyncCallback<AppVersionInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetappversioninfo7)
[getAppVersionInfo():Promise<AppVersionInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetappversioninfo7-1) | bundle\bundleInfo.d.ts | [readonly name: string;](../reference/apis/js-apis-bundleManager-bundleInfo.md#bundleinfo-1)
[readonly versionCode: number;](../reference/apis/js-apis-bundleManager-bundleInfo.md#bundleinfo-1)
[readonly versionName: string;](../reference/apis/js-apis-bundleManager-bundleInfo.md#bundleinfo-1) | +| [getApplicationContext():Context;](../reference/apis/js-apis-inner-app-context.md#contextgetapplicationcontext7) | application\Context.d.ts | [getApplicationContext(): ApplicationContext;](../reference/apis/js-apis-inner-application-context.md#contextgetapplicationcontext) | +| [getAbilityInfo(callback:AsyncCallback<AbilityInfo>):void;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7)
[getAbilityInfo():Promise<AbilityInfo>;](../reference/apis/js-apis-inner-app-context.md#contextgetabilityinfo7-1) | application\UIAbilityContext.d.ts | [abilityInfo: AbilityInfo;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#attributes)| +| [isUpdatingConfigurations(callback:AsyncCallback<boolean>):void;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7)
[isUpdatingConfigurations():Promise<boolean>;](../reference/apis/js-apis-inner-app-context.md#contextisupdatingconfigurations7-1) | There is no corresponding API in the stage model.| OpenHarmony applications do not restart when the system environment changes. The **onConfigurationUpdated** callback is invoked to notify the applications of the changes. This API provides an empty implementation in the FA model, and the stage model does not provide a corresponding API.| +| [printDrawnCompleted(callback:AsyncCallback<void>):void;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7)
[printDrawnCompleted():Promise<void>;](../reference/apis/js-apis-inner-app-context.md#contextprintdrawncompleted7-1) | There is no corresponding API in the stage model.| This API provides an empty implementation in the FA model. The stage model does not provide a corresponding API.| diff --git a/en/application-dev/application-models/create-dataability.md b/en/application-dev/application-models/create-dataability.md new file mode 100644 index 0000000000000000000000000000000000000000..488b0593dbdc23bc1e6ea30c17f9165a92c79f20 --- /dev/null +++ b/en/application-dev/application-models/create-dataability.md @@ -0,0 +1,62 @@ +# Creating a DataAbility + + +To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** methods for a DataAbility. The **BatchInsert** and **ExecuteBatch** methods have already implemented the traversal logic, but not batch data processing. + + +The following sample code shows how to create a DataAbility: + +```ts +import featureAbility from '@ohos.ability.featureAbility' +import dataAbility from '@ohos.data.dataAbility' +import dataRdb from '@ohos.data.rdb' + +const TABLE_NAME = 'book' +const STORE_CONFIG = { name: 'book.db' } +const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)' +let rdbStore: dataRdb.RdbStore = undefined + +export default { + onInitialized(abilityInfo) { + console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) + let context = featureAbility.getContext() + dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => { + console.info('DataAbility getRdbStore callback') + store.executeSql(SQL_CREATE_TABLE, []) + rdbStore = store + }); + }, + insert(uri, valueBucket, callback) { + console.info('DataAbility insert start') + rdbStore.insert(TABLE_NAME, valueBucket, callback) + }, + batchInsert(uri, valueBuckets, callback) { + console.info('DataAbility batch insert start') + for (let i = 0;i < valueBuckets.length; i++) { + console.info('DataAbility batch insert i=' + i) + if (i < valueBuckets.length - 1) { + rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => { + console.info('DataAbility batch insert ret=' + num) + }) + } else { + rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) + } + } + }, + query(uri, columns, predicates, callback) { + console.info('DataAbility query start') + let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) + rdbStore.query(rdbPredicates, columns, callback) + }, + update(uri, valueBucket, predicates, callback) { + console.info('DataAbilityupdate start') + let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) + rdbStore.update(valueBucket, rdbPredicates, callback) + }, + delete(uri, predicates, callback) { + console.info('DataAbilitydelete start') + let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) + rdbStore.delete(rdbPredicates, callback) + } +}; +``` diff --git a/en/application-dev/application-models/create-pageability.md b/en/application-dev/application-models/create-pageability.md new file mode 100644 index 0000000000000000000000000000000000000000..783646ff4cfd5fa2ab193005bfa9d182dc75b70c --- /dev/null +++ b/en/application-dev/application-models/create-pageability.md @@ -0,0 +1,97 @@ +# Creating a PageAbility + + +When you create a PageAbility on DevEco Studio, DevEco Studio automatically generates the **onCreate()** and **onDestroy()** callbacks in **app.js** and **app.ets**. You need to implement the other lifecycle callbacks in **app.js** and **app.ets**. The following code snippet shows how to create a PageAbility: + +```ts +export default { + onCreate() { + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + onShow() { + console.info('Application onShow') + }, + onHide() { + console.info('Application onHide') + }, + onActive() { + console.info('Application onActive') + }, + onInactive() { + console.info('Application onInactive') + }, + onNewWant() { + console.info('Application onNewWant') + }, +} +``` + + +After the PageAbility is created, its abilities-related configuration items are displayed in the **config.json** file. The following is an example **config.json** file of an ability named EntryAbility: + +```json +{ + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "EntryAbility", + "name": ".EntryAbility", + "srcLanguage": "ets", + "icon": "$media:icon", + "description": "$string:EntryAbility_desc", + "formsEnabled": false, + "label": "$string:EntryAbility_label", + "type": "page", + "launchType": "singleton" + } + ] +} +``` + + +In the FA model, you can call **getContext** of **featureAbility** to obtain the application context and then use the capabilities provided by the context. + + +**Table 1** featureAbility APIs + +| API| Description| +| -------- | -------- | +| getContext() | Obtains the application context.| + + +The following code snippet shows how to use **getContext()** to obtain the application context and distributed directory: + +```ts +import featureAbility from '@ohos.ability.featureAbility' +import fileIo from '@ohos.fileio' + +(async () => { + let dir: string + try { + console.info('Begin to getOrCreateDistributedDir') + dir = await featureAbility.getContext().getOrCreateDistributedDir() + console.info('distribute dir is ' + dir) + } catch (error) { + console.error('getOrCreateDistributedDir failed with ' + error) + } + + let fd: number; + let path = dir + "/a.txt"; + fd = fileIo.openSync(path, 0o2 | 0o100, 0o666); + fileIo.close(fd); +})() +``` diff --git a/en/application-dev/application-models/create-serviceability.md b/en/application-dev/application-models/create-serviceability.md new file mode 100644 index 0000000000000000000000000000000000000000..78623839266f4e97de26d0a3d66c19236eacf815 --- /dev/null +++ b/en/application-dev/application-models/create-serviceability.md @@ -0,0 +1,61 @@ +# Creating a ServiceAbility + + +1. Create a ServiceAbility. + + Override the ServiceAbility lifecycle callbacks to implement your own logic for processing interaction requests. + + ```ts + import rpc from "@ohos.rpc" + + class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { + if (typeof des === 'string') { + super(des) + } else { + return + } + } + } + + export default { + onStart() { + console.info('ServiceAbility onStart') + }, + onStop() { + console.info('ServiceAbility onStop') + }, + onCommand(want, startId) { + console.info('ServiceAbility onCommand') + }, + onConnect(want) { + console.info('ServiceAbility onConnect' + want) + return new FirstServiceAbilityStub('test') + }, + onDisconnect(want) { + console.info('ServiceAbility onDisconnect' + want) + } + } + ``` + +2. Register the ServiceAbility. + + Declare the ServiceAbility in the **config.json** file by setting its **type** attribute to **service**. The **visible** attribute specifies whether the ServiceAbility can be called by other applications. The value **true** means that the ServiceAbility can be called by other applications, and **false** means that the ServiceAbility can be called only within the application. To enable the ServiceAbility to be called by other applications, set **visible** to **true** when registering the ServiceAbility and enable associated startup. For details about the startup rules, see [Component Startup Rules](component-startup-rules.md). + + ```json + { + "module": { + "abilities": [ + { + "name": ".ServiceAbility", + "srcLanguage": "ets", + "srcPath": "ServiceAbility", + "icon": "$media:icon", + "description": "hap sample empty service", + "type": "service", + "visible": true + } + ] + } + } + ``` diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md new file mode 100644 index 0000000000000000000000000000000000000000..4ecdf35ead5482d4b4b2e0d0a2a4544e75686612 --- /dev/null +++ b/en/application-dev/application-models/data-share-via-want.md @@ -0,0 +1,111 @@ +# Using Want to Share Data Between Applications + + +Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications. + + +## Prerequisites + +1. There are two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing through **startAbility()**, the application selector is started. The system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts that application to complete data sharing. + +2. In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on the Want configuration used for data sharing. + +3. The following actions are involved in this section: + - **ACTION_SELECT (ohos.want.action.select)**: action of displaying the application selector. + - **ACTION_SEND_DATA (ohos.want.action.sendData)**: action of launching the UI for sending a single data record. It is used to transfer data to the shared party. + + +## How to Develop + +- Sharing party + 1. In the stage mode, the [File Descriptor (FD)](../reference/apis/js-apis-fileio.md#fileioopensync) is used for file transfer. This example assumes that the path of the file to share is obtained. + + ```ts + import fileIO from '@ohos.fileio'; + + // let path = ... + // Open the file whose path is a variable. + let fileFd = fileIO.openSync(path, 0o102, 0o666); + ``` + + 2. As described in the prerequisites, the sharing party starts an application selector and shares the data to the selector, and the selector transfers the data to the shared party. Want of the sharing party must be nested at two layers. At the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. At the second layer, complete Want is declared in the custom field **parameters** to transfer the data to share. + + ```ts + import wantConstant from '@ohos.app.ability.wantConstant'; + + // let path = ... + // let fileFd = ... + // let fileSize = ... + let want = { + / This action is used to implicitly match the application selector. + action: wantConstant.Action.ACTION_SELECT, + // This is the custom parameter in the first layer of Want, + / which is intended to add information to the application selector. + parameters: { + // MIME type of PDF. + "ability.picker.type": "application/pdf", + "ability.picker.fileNames": [path], + "ability.picker.fileSizes": [fileSize], + // This nested Want ,which will be directly sent to the selected application. + "ability.want.params.INTENT": { + "action": "ohos.want.action.sendData", + "type": "application/pdf", + "parameters": { + "keyFd": {"type": "FD", "value": fileFd} + } + } + } + } + ``` + + In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved: + + - **"ability.picker.type"**: The application selector renders the file type icon based on this field. + - **"ability.picker.fileNames"**: The application selector displays the file name based on this field. + - **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte. + - **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping. + + For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows: + + stage-want2 + + In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application. + +- Shared party + 1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows: + + ```ts + "skills": [ + { + "entities": [ + // ... + ], + "actions": [ + "ohos.want.action.sendData" + // ... + ], + "uris": [ + { + "type": "application/pdf" + }, + // ... + ] + }, + ] + ``` + + The **actions** and **type** fields in **uris** match the **action** and **type** fields in **ability.want.params.INTENT**, respectively. + + Files can be transferred in FD mode, but not URI mode. In implicit matching, the **type** field in Want must match the **type** field in **uris** under **skills** of the shared party. Therefore, specify only the **type** field in **uris**. If **host** and **port** are specified, the matching fails. The application selector initiates implicit matching based on **ability.want.params.INTENT**. Therefore, when the **uri** field added to **ability.want.params.INTENT** matches the **uris** field under **skills**, the matching is successful and additional data can be transferred. + 2. After the application selector starts the shared party, the system calls **onCreate** and passes **ability.want.params.INTENT** to the **want** parameter. + + ```ts + onCreate(want, launchParam) { + // When keyFd is undefined, the application crashes. + if (want["parameters"]["keyFd"] !== undefined) { + // Receive the file descriptor. + let fd = want["parameters"]["keyFd"].value; + // ... + } + } + ``` diff --git a/en/application-dev/application-models/dataability-configuration.md b/en/application-dev/application-models/dataability-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..c8c69c8626cf9872e40931b2f97c431e105cb38f --- /dev/null +++ b/en/application-dev/application-models/dataability-configuration.md @@ -0,0 +1,61 @@ +# DataAbility Component Configuration + + +## URI Introduction + +A Uniform Resource Identifier (URI) is used to identify a specific data item, such as a table in the database or a file on the disk. URIs used in OpenHarmony comply with the commonly used URI standard. A URI consists of the components: + +![fa-dataability-uri](figures/fa-dataability-uri.png) + +- **scheme**: name of the scheme used by the DataAbility. The value is fixed at **dataability**. + +- **authority**: device ID. To access data on a remote device, set this component to the ID of the remote device. To access data on the local device, leave this component empty. + +- **path**: location of the specific resource to access. + +- **query**: query parameters. + +- **fragment**: subordinate resources to access. + +Example URIs: + +- Cross-device communication: dataability://*device*id_/*com.domainname.dataability.persondata*/*person*/*10* + +- Local-device communication: dataability:///*com.domainname.dataability.persondata*/*person*/*1* + +> **NOTE** +> +> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**. + + +## Introduction to Certain Configuration Items + +Similar to a PageAbility, a DataAbility is configured in **abilities** under **module** of the **config.json** file. The difference between a DataAbility and PageAbility lies in the **type** and **uri** fields. + +**Table 1** DataAbility configuration items + +| Name| Description| +| -------- | -------- | +| "name" | Ability name.| +| "type" | Type of the ability. The value **data** indicates a DataAbility.| +| "uri" | URI used for communication.| +| "visible" | Whether the ability is visible to other applications. Data sharing is allowed only when the value is **true**.| + +The following is an example **config.json** file: + + +```json +"abilities": [{ + "srcPath": "DataAbility", + "name": ".DataAbility", + "icon": "$media:icon", + "srcLanguage": "ets", + "description": "$string:description_dataability", + "type": "data", + "visible": true, + "uri": "dataability://ohos.samples.etsdataability.DataAbility" +}] +``` + +For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md). + diff --git a/en/application-dev/application-models/dataability-lifecycle.md b/en/application-dev/application-models/dataability-lifecycle.md new file mode 100644 index 0000000000000000000000000000000000000000..f35f46ffd9504a29897694054efc15f9a8465a57 --- /dev/null +++ b/en/application-dev/application-models/dataability-lifecycle.md @@ -0,0 +1,23 @@ +# DataAbility Lifecycle + + +You can override lifecycle callbacks (described in the table below) for a DataAbility based on service requirements. + + +**Table 1** DataAbility lifecycle APIs + +| API| Description| +| -------- | -------- | +| onInitialized?(info: AbilityInfo): void | Called during ability initialization to initialize the relational database (RDB).| +| update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void | Updates data in the database.| +| query?(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<ResultSet>): void | Queries data in the database.| +| delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database.| +| normalizeUri?(uri: string, callback: AsyncCallback<string>): void | Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| +| batchInsert?(uri: string, valueBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>): void | Inserts multiple data records into the database.| +| denormalizeUri?(uri: string, callback: AsyncCallback<string>): void | Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| +| insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void | Inserts a data record into the database.| +| openFile?(uri: string, mode: string, callback: AsyncCallback<number>): void | Opens a file.| +| getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void | Obtains the MIME type of a file.| +| getType?(uri: string, callback: AsyncCallback<string>): void | Obtains the MIME type matching the data specified by the URI.| +| executeBatch?(ops: Array<DataAbilityOperation>, callback: AsyncCallback<Array<DataAbilityResult>>): void | Operates data in the database in batches.| +| call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback<PacMap>): void | Calls a custom API.| diff --git a/en/application-dev/application-models/dataability-overview.md b/en/application-dev/application-models/dataability-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..b89ee68bb5fe6cda341dea332a24cf1010c4935f --- /dev/null +++ b/en/application-dev/application-models/dataability-overview.md @@ -0,0 +1,10 @@ +# DataAbility Component Overview + + +A DataAbility is an ability that uses the Data template. It provides unified data access for external systems, but not a UI for user interaction. A DataAbility can be started by a PageAbility, a ServiceAbility, or other applications. It remains to run in the background even after the user switches to another application. + + +A DataAbility helps applications manage access to data stored by themselves and other applications, and provides methods for sharing data with other applications, either on the same device or across devices. + + +Data can be stored in a database or files on disks. The DataAbility provide methods for inserting, deleting, updating, and querying data, and opening files. You should implement these methods. diff --git a/en/application-dev/application-models/dataability-permission-control.md b/en/application-dev/application-models/dataability-permission-control.md new file mode 100644 index 0000000000000000000000000000000000000000..25c5e82726dbc3a7dba8158a0847b5c59ea0c98e --- /dev/null +++ b/en/application-dev/application-models/dataability-permission-control.md @@ -0,0 +1,60 @@ +# DataAbility Permission Control + + +The DataAbility uses permission control to determine whether an ability can access the data service it provides. There are static and dynamic permission controls. + + +## Static Permission Control + +The DataAbility functions as the server. When being started, the DataAbility verifies the client permissions against the settings of the optional fields **readPermission**, **writePermission**, and **Permission** fields in the **config.json** file. The following is an example: + + +```json +"abilities": [{ + "srcPath": "DataAbility", + "name": ".DataAbility", + "icon": "$media:icon", + "srcLanguage": "ets", + "description": "$string:description_dataability", + "type": "data", + "visible": true, + "uri": "dataability://ohos.samples.etsdataability.DataAbility", + "readPermission":"ohos.permission.READ_CONTACTS", + "writePermission":"ohos.permission.WRITE_CONTACTS" +}] +``` + +The client permission is configured in **reqPermissions** under **module** in the **config.json** file. The following is an example: + + +```json +{ + "module": { + "reqPermissions":{ + { + "name":"ohos.permission.READ_CONTACTS" + }, + { + "name":"ohos.permission.WRITE_CONTACTS" + } + } + } +} +``` + + +## Dynamic Permission Control + +Static permission control determines whether a DataAbility can be started by another ability or application. It does not verify the permission of each read/write interface. + +Dynamic permission control verifies whether the client has the corresponding permission for every read/write interface. The table below lists the permissions required for calling these interfaces. + +**Table 1** Permission configuration for data read/write interfaces + +| Interface with the Read Permission| Interface with the Write Permission| Interface with the Read/Write Permission Based on Actual Requirements| +| -------- | -------- | -------- | +| query, normalizeUri, denormalizeUri, openfile (with **mode** set to **'r'**)| insert, batchInsert, delete, update, openfile (with **mode** set to **'w'**)| executeBatch | + +For interfaces that require the read permission, the server must have **readPermission** specified, and the client must obtain the read permission before calling them. + +For interfaces that require the write permission, the server must have **writePermission** specified, and the client must obtain the write permission before calling them. diff --git a/en/application-dev/application-models/dataability-switch.md b/en/application-dev/application-models/dataability-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..b91d50ca37a97fdc1d4824a93a6093bac7cd0f77 --- /dev/null +++ b/en/application-dev/application-models/dataability-switch.md @@ -0,0 +1,44 @@ +# DataAbility Switching + + +The DataAbility component in the FA model corresponds to the DataShareExtensionAbility component in the stage model. + + +The DataShareExtensionAbility class provides system APIs. Only system applications can create DataShareExtensionAbility instances. Therefore, DataAbility switching adopts different policies for system applications and third-party applications. + + +## Switching a DataAbility of a System Application + +The procedure for switching a DataAbility of a system application is similar to the procedure of PageAbility switching. + +1. Create a DataShareExtensionAbility in the stage model. + +2. Migrate the DataAbility code to the DataShareExtensionAbility. + + The table below describes the lifecycle comparison of the DataAbility and DataShareExtensionAbility. + + | DataAbility| DataShareExtensionAbility| Comparison Description| + | -------- | -------- | -------- | + | onInitialized?(info: AbilityInfo): void | onCreate?(want: Want, callback: AsyncCallback<void>): void
| The two methods have the same invoking time but different input parameters. In the stage model, the **want** parameter is added so that you can obtain parameters during creation.| + | update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void | update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | The two methods have the same meaning and invoking time, but slightly different parameter sequence and parameter type. A simple reconstruction is required.| + | query?(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<ResultSet>): void | query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void;| The two methods have the same meaning and invoking time, but slightly different parameter sequence and parameter type. A simple reconstruction is required.| + | delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void | delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):| The two methods have the same meaning and invoking time, but slightly different parameter type. A simple reconstruction is required.| + | normalizeUri?(uri: string, callback: AsyncCallback<string>): void | normalizeUri?(uri: string, callback: AsyncCallback<string>): void| The two methods have the same meaning, invoking time, and parameters.| + | batchInsert?(uri: string, valueBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>): void | batchInsert?(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void| The two methods have the same meaning and invoking time, but slightly different parameter type. A simple reconstruction is required.| + | denormalizeUri?(uri: string, callback: AsyncCallback<string>): void | denormalizeUri?(uri: string, callback: AsyncCallback<string>): void | The two methods have the same meaning, invoking time, and parameters.| + | insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void | insert?(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | The two methods have the same meaning and invoking time, but slightly different parameter type. A simple reconstruction is required.| + | openFile?(uri: string, mode: string, callback: AsyncCallback<number>): void | NA | The stage model does not support cross-process URI access. You are advised to use [the **want** parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| + | getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void | NA | The stage model does not support cross-process URI access. You are advised to use [the **want** parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| + | getType?(uri: string, callback: AsyncCallback<string>): void | NA | The stage model does not support cross-process URI access. You are advised to use [the **want** parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| + | executeBatch?(ops: Array<DataAbilityOperation>, callback: AsyncCallback<Array<DataAbilityResult>>): void | NA | This method is not provided in the stage model. You need to implement the functionality based on service functions.| + | call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback<PacMap>): void | NA | This method is not provided in the stage model. You need to implement the functionality based on service functions.| + + +## Switching a DataAbility of a Third-Party Application + +In the stage model, third-party applications cannot provide data services for other third-party applications. You can select a switching solution based on your service requirements. + +| Service Type| Switching Solution| +| -------- | -------- | +| Providing data for third-party applications| Match a scenario-specific [ExtensionAbility](../reference/apis/js-apis-bundleManager.md#extensionabilitytype).| +| Providing data within the application| Extract the component code as a common module for other components to use.| diff --git a/en/application-dev/application-models/dataabilityhelper-switch.md b/en/application-dev/application-models/dataabilityhelper-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..c709e30ae9c25bcbd47f781e1f43a51100960998 --- /dev/null +++ b/en/application-dev/application-models/dataabilityhelper-switch.md @@ -0,0 +1,20 @@ +# DataAbilityHelper Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| [openFile(uri: string, mode: string, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperopenfile)
[openFile(uri: string, mode: string): Promise<number>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperopenfile-1) | \@ohos.data.fileAccess.d.ts | [openFile(uri: string, flags: OPENFLAGS) : Promise<number>;](../reference/apis/js-apis-fileAccess.md#fileaccesshelperopenfile)
[openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback<number>) : void;](../reference/apis/js-apis-fileAccess.md#fileaccesshelperopenfile) | +| [on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperon) | \@ohos.data.dataShare.d.ts | [on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-data-dataShare.md#ondatachange) | +| [off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperoff) | \@ohos.data.dataShare.d.ts | [off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void;](../reference/apis/js-apis-data-dataShare.md#offdatachange) | +| [getType(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpergettype)
[getType(uri: string): Promise<string>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpergettype-1) | There is no corresponding API in the stage model.| The stage model does not support cross-process URI access. You are advised to use [the want parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| +| [getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpergetfiletypes)
[getFileTypes(uri: string, mimeTypeFilter: string): Promise<Array<string>>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpergetfiletypes-1) | There is no corresponding API in the stage model.| The stage model does not support cross-process URI access. You are advised to use [the want parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| +| [normalizeUri(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpernormalizeuri)
[normalizeUri(uri: string): Promise<string>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpernormalizeuri-1) | \@ohos.data.dataShare.d.ts | [normalizeUri(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-data-dataShare.md#normalizeuri)
[normalizeUri(uri: string): Promise<string>;](../reference/apis/js-apis-data-dataShare.md#normalizeuri-1) | +| [denormalizeUri(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperdenormalizeuri)
[denormalizeUri(uri: string): Promise<string>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperdenormalizeuri-1) | \@ohos.data.dataShare.d.ts | [denormalizeUri(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-data-dataShare.md#denormalizeuri)
[denormalizeUri(uri: string): Promise<string>;](../reference/apis/js-apis-data-dataShare.md#denormalizeuri-1) | +| [notifyChange(uri: string, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpernotifychange)
[notifyChange(uri: string): Promise<void>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpernotifychange-1) | \@ohos.data.dataShare.d.ts | [notifyChange(uri: string, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-data-dataShare.md#notifychange)
[notifyChange(uri: string): Promise<void>;](../reference/apis/js-apis-data-dataShare.md#notifychange-1) | +| [insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperinsert)
[insert(uri: string, valuesBucket: rdb.ValuesBucket): Promise<number>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperinsert-1) | \@ohos.data.dataShare.d.ts | [insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-data-dataShare.md#insert)
[insert(uri: string, value: ValuesBucket): Promise<number>;](../reference/apis/js-apis-data-dataShare.md#insert-1) | +| [batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperbatchinsert)
[batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>): Promise<number>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperbatchinsert-1) | \@ohos.data.dataShare.d.ts | [batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-data-dataShare.md#batchinsert)
[batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number>;](../reference/apis/js-apis-data-dataShare.md#batchinsert-1) | +| [delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperdelete)
[delete(uri: string, predicates?: dataAbility.DataAbilityPredicates): Promise<number>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperdelete-1)
[delete(uri: string, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperdelete) | \@ohos.data.dataShare.d.ts | [delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-data-dataShare.md#delete)
[delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promise<number>;](../reference/apis/js-apis-data-dataShare.md#delete-1) | +| [update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperupdate)
[update(uri: string, valuesBucket: rdb.ValuesBucket, predicates?: dataAbility.DataAbilityPredicates): Promise<number>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperupdate-1)
[update(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperupdate) | \@ohos.data.dataShare.d.ts | [update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-data-dataShare.md#update)
[update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket): Promise<number>;](../reference/apis/js-apis-data-dataShare.md#update-1) | +| [query(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<ResultSet>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperquery)
[query(uri: string, callback: AsyncCallback<ResultSet>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperquery)
[query(uri: string, columns: Array<string>, callback: AsyncCallback<ResultSet>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperquery)
[query(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<ResultSet>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperquery)
[query(uri: string, columns?: Array<string>, predicates?: dataAbility.DataAbilityPredicates): Promise<ResultSet>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperquery-1) | \@ohos.data.dataShare.d.ts | [query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void;](../reference/apis/js-apis-data-dataShare.md#query)
[query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>): Promise<DataShareResultSet>;](../reference/apis/js-apis-data-dataShare.md#query-1) | +| [call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback<PacMap>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpercall-1)
[call(uri: string, method: string, arg: string, extras: PacMap): Promise<PacMap>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelpercall) | There is no corresponding API in the stage model.| No corresponding API is provided.| +| [executeBatch(uri: string, operations: Array<DataAbilityOperation>, callback: AsyncCallback<Array<DataAbilityResult>>): void;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch)
[executeBatch(uri: string, operations: Array<DataAbilityOperation>): Promise<Array<DataAbilityResult>>;](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch-1) | There is no corresponding API in the stage model.| No corresponding API is provided.| diff --git a/en/application-dev/application-models/datashareextensionability.md b/en/application-dev/application-models/datashareextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..5b07ba68180fbcc2a51047d37ca9a82addd89cd8 --- /dev/null +++ b/en/application-dev/application-models/datashareextensionability.md @@ -0,0 +1,4 @@ +# DataShareExtensionAbility + + +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). diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md new file mode 100644 index 0000000000000000000000000000000000000000..ccf33e07d1b389eb1246a89a377febb1e7d24a78 --- /dev/null +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -0,0 +1,160 @@ +# Matching Rules of Explicit Want and Implicit Want + +Both explicit Want and implicit Want can be used to match an ability to start based on certain rules. These rules determine how the parameters set in Want match the configuration file declared by the target ability. + +## Matching Rules of Explicit Want + + +The table below describes the matching rules of explicit Want. + +| Name| Type| Matching Item| Mandatory| Rule Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceId | string | Yes| No| If this field is unspecified, only abilities on the local device are matched.| +| bundleName | string | Yes| Yes| If **abilityName** is specified but **bundleName** is unspecified, the matching fails.| +| moduleName | string | Yes| No| If this field is unspecified and multiple modules with the same ability name exist in the application, the first ability is matched by default.| +| abilityName | string | Yes| Yes| To use explicit Want, this field must be specified.| +| uri | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| type | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| action | string | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| entities | Array<string> | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| +| flags | number | No| No| This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| +| parameters | {[key: string]: any} | No| No| This field is not used for matching. It is passed to the target ability as a parameter.| + +## Matching Rules for Implicit Want + +The table below describes the matching rules of implicit Want. + +| Name | Type | Matching Item| Mandatory| Rule Description | +| ----------- | ------------------------------ | ------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | No | Implicit invoking is not supported across devices. | +| abilityName | string | No | No | To use implicit Want, this field must be left unspecified. | +| bundleName | string | Yes | No | - When only **bundleName** is specified, matching is limited to that application.
- When both **bundleName** and **moduleName** are specified, matching is limited to that module in that application.
- When only **moduleName** is specified, the setting is invalid.

These fields will be used for implicit matching.| +| moduleName | string | Yes | No | | +| uri | string | Yes | No | | +| type | string | Yes | No | | +| action | string | Yes | No | | +| entities | Array<string> | Yes | No | | +| flags | number | No | No | This field is not used for matching and is directly transferred to the system for processing. It is generally used to set runtime information, such as URI data authorization.| +| parameters | {[key: string]: any} | No | No | This field is not used for matching. It is passed to the target ability as a parameter. | + +Get familiar with the following about implicit Want: + + +- The **want** parameter passed by the caller indicates the operation to be performed by the caller. It also provides data and application type restrictions. + +- The **skills** field declares the capabilities of the target ability. For details, see [the skills tag](../quick-start/module-configuration-file.md#skills) in the [module.json5 file](../quick-start/module-configuration-file.md). + + +The system matches the **want** parameter (including the **action**, **entities**, **uri**, and **type** attributes) passed by the caller against the **skills** configuration (including the **actions**, **entities**, **uris**, and **type** attributes) of the abilities one by one. When all the four attributes are matched, a dialog box is displayed for users to select a matched application. + + +### 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. + +- If **action** in the passed **want** parameter is specified but **actions** under **skills** of an ability is unspecified, the matching fails. + +- If **action** in the passed **want** parameter is unspecified but **actions** under **skills** of an ability is specified, the matching is successful. + +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified and contains **action** in the passed **want** parameter, the matching is successful. + +- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified but does not contain **action** in the passed **want** parameter, the matching fails. + + **Figure 1** Matching rules of action in the want parameter + want-action + + +### 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. + +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is specified, the matching is successful. + +- If **entities** in the passed **want** parameter is unspecified but **entities** under **skills** of an ability is unspecified, the matching is successful. + +- If **entities** in the passed **want** parameter is specified but **entities** under **skills** of an ability is unspecified, the matching fails. + +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified and contains **entities** in the passed **want** parameter, the matching is successful. + +- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails. + + Figure 2 Matching rule of entities in the want parameter +want-entities + + +### Matching Rules of uri and type in the want Parameter + +When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. + +Figure 3 Matching rules when uri and type are specified in the want parameter +want-uri-type1 + +There are four combinations of **uri** and **type** settings. The matching rules are as follows: + +- Neither **uri** or **type** is specified in the **want** parameter. + - If the **uris** array under **skills** of an ability is unspecified, the matching is successful. + - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** and **type** are unspecified, the matching is successful. + - In other cases, the matching fails. + +- Only **uri** is specified in the **want** parameter. + - If the **uris** array under **skills** of an ability is unspecified, the matching fails. + - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and **type** is unspecified, the matching is successful. Otherwise, the matching fails. + +- Only **type** is specified in the **want** parameter. + - If the **uris** array under **skills** of an ability is unspecified, the matching fails. + - If the **uris** array under **skills** of an ability contains an URI element whose **scheme** is unspecified and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. + +- Both **uri** and **type** are specified in the **want** parameter, as shown in Figure 3. + - If the **uris** array under **skills** of an ability is unspecified, the matching fails. + - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. + + +To simplify the description, **uri** and **type** passed in the **want** parameter are called **w_uri** and **w_type**, respectively; the **uris** array under **skills** of an ability to match is called **s_uris**; each element in the array is called **s_uri**. Matching is performed from top to bottom. + + +Figure 4 Matching rules of uri and type in the want parameter +want-uri-type2 + + +### Matching Rules of uri + +To simplify the description, **uri** in the passed **want** parameter is called **w_uri**; **uri** under **skills** of an ability to match is called **s_uri**. The matching rules are as follows: + +- If **scheme** of **s_uri** is unspecified and **w_uri** is unspecified, the matching is successful. Otherwise, the matching fails. + +- If **host** of **s_uri** is unspecified and **scheme** of **w_uri** and **scheme** of **s_uri** are the same, the matching is successful. Otherwise, the matching fails. + +- If **path**, **pathStartWith**, and **pathRegex** of **s_uri** are unspecified and **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching fails. + +- If **path** of **s_uri** is specified and the **full path expressions** of **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching of **pathStartWith** continues. + +- If **pathStartWith** of **s_uri** is specified and **w_uri** contains the prefix expression of **s_uri**, the matching is successful. Otherwise, **pathRegex** matching continues. + +- If **pathRegex** of **s_uri** is specified and **w_uri** meets the regular expression of **s_uri**, the matching is successful. Otherwise, the matching fails. + +> **NOTE** +> +> The **scheme**, **host**, **port**, **path**, **pathStartWith**, and **pathRegex** attributes of **uris** under **skills** of an ability are concatenated. If **path**, **pathStartWith**, and **pathRegex** are declared in sequence, **uris** can be concatenated into the following expressions: +> +> - **Full path expression**: `scheme://host:port/path` +> +> - **Prefix expression**: `scheme://host:port/pathStartWith` +> +> - **Regular expression**: `scheme://host:port/pathRegex` + + +### Matching Rules of type + +> **NOTE** +> +> The matching rules of **type** described in this section are based on the fact that **type** in the **want** parameter is specified. If **type** is unspecified, follow the [matching rules of uri and type in the want parameter](#matching-rules-of-uri-and-type-in-the-want-parameter). + +To simplify the description, **uri** in the passed **want** parameter is called **w_type**, and **type** of **uris** under **skills** of an ability to match is called **s_type**. The matching rules are as follows: + +- If **s_type** is unspecified, the matching fails. + +- If **s_type** or **w_type** contains the wildcard `*/*`, the matching is successful. + +- If the last character of **s_type** is the wildcard `*`, for example, `prefixType/*`, the matching is successful only when **w_type** contains `prefixType/`. + +- If the last character of **w_type** is the wildcard `*`, for example, `prefixType/*`, the matching is successful only when **s_type** contains `prefixType/`. diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..d85f02ace879e409a8d42d6f09408680a99f8056 --- /dev/null +++ b/en/application-dev/application-models/extensionability-overview.md @@ -0,0 +1,58 @@ +# ExtensionAbility Component Overview + + +The ExtensionAbility component is used for specific scenarios such as widgets and input methods. + + +An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionabilitytype) is provided for every specific scenario. All types of ExtensionAbility components are managed by the corresponding system services in a unified manner. For example, the InputMethodExtensionAbility component is managed by the input method management service. The following ExtensionAbility types are supported: + + +- [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 APIs for registering, canceling, and querying 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. + +- [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md): ExtensionAbility component of the service type, which provides APIs related to background service scenarios. + +- [AccessibilityExtensionAbility](../reference/apis/js-apis-application-accessibilityExtensionAbility.md): ExtensionAbility component of the accessibility type, which provides APIs related to the accessibility feature. + +- [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md): ExtensionAbility component of the data_share type, which provides APIs for data sharing. + +- [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. + +- [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. + + +## Using ExtensionAbility of the Specified Type + +All types of ExtensionAbility components are started by the corresponding system management service, rather than applications, so that their lifecycles are under control by the system. The caller of the ExtensionAbility component does not need to care about its lifecycle. + +The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md) as an example. As shown in the figure below, when an application calls the InputMethodExtensionAbility component, the input method management service is called first. The input method management service starts the InputMethodExtensionAbility component, returns the component to the application, and starts to manage its lifecycle. + +**Figure 1** Using the InputMethodExtensionAbility component +![ExtensionAbility-start](figures/ExtensionAbility-start.png) + + +## Implementing ExtensionAbility of the Specified Type + +The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](Widget-development-stage.md). + +You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService. + +![form_extension](figures/form_extension.png) + + +> **NOTE** +> +> For an application, all ExtensionAbility components of the same type run in an independent process, whereas UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md). +> +> For example, an application has one UIAbility component, one ServiceExtensionAbility, one DataShareExtensionAbility, two FormExtensionAbility, and one ImeExtensionAbility. When the application is running, there are three processes: +> +> - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process. +> +> - The two FormExtensionAbility components run in an independent process. +> +> - The two ImeExtensionAbility components run in an independent process. diff --git a/en/application-dev/application-models/fa-model-development-overview.md b/en/application-dev/application-models/fa-model-development-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..07e7ef8a0bdaea927762c15e4123ae728c026cb7 --- /dev/null +++ b/en/application-dev/application-models/fa-model-development-overview.md @@ -0,0 +1,15 @@ +# FA Model Development Overview + + +During application development based on the Feature Ability (FA) model, the following tasks are involved in the application model. + + + **Table 1** FA model development process + +| Task| Introduction| Guide| +| -------- | -------- | -------- | +| Application component development| Use the PageAbility, ServiceAbility, DataAbility, and widgets of the FA model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-fa.md)
- [PageAbility Component](pageability-overview.md)
- [ServiceAbility Component](serviceability-overview.md)
- [DataAbility Component](dataability-overview.md)
- [Widget Development](Widget-development-fa.md)
- [Context](application-context-fa.md)
- [Want](want-fa.md) | +| Inter-process communication (IPC)| Learn the process model and common IPC modes of the FA model.| [Common Events](common-event-fa.md)
[Background Services](rpc.md) | +| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the FA model.| [Inter-Thread Communication](itc-fa-overview.md)| +| Mission management| Learn the basic concepts and typical scenarios of mission management in the FA model.| [Mission Management](mission-management-fa.md)| +| Application configuration file| Learn the requirements for developing application configuration files in the FA model.| [Application Configuration File](config-file-fa.md) | diff --git a/en/application-dev/application-models/fa-stage-interaction-overview.md b/en/application-dev/application-models/fa-stage-interaction-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..0d1ed27f0df2d4964b0d69faf48afcb42e32bf91 --- /dev/null +++ b/en/application-dev/application-models/fa-stage-interaction-overview.md @@ -0,0 +1,25 @@ +# Component Interaction Between the FA Model and Stage Model + + +The FA model is supported by API version 8 and earlier versions, and the stage model is recommended since API version 9. The FA model and stage model have their respective components. The FA model provides three types of application components: PageAbility, ServiceAbility, and DataAbility. The stage model provides two types of application components: UIAbility and ExtensionAbility. + + +You cannot use both models for the development of an application (see the figure below). However, a device (system) can contain applications developed on both models (scenario 3 in the figure below). In this case, their components may interact with each other. + +Figure 1 Coexistent application components of the FA model and stage model +![coexistence-of-FAandStage](figures/coexistence-of-FAandStage.png) + + +The following table lists the possible interaction scenarios. You must pay attention to the concerns listed below during your application development. + + +Table 1 Application component interaction scenarios + +| Interaction Scenario| Concerns| +| -------- | -------- | +| [Starting a UIAbility from the FA Model](start-uiability-from-fa.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the UIAbility in the stage model.| +| [Connecting to a ServiceExtensionAbility from the FA Model](bind-serviceextensionability-from-fa.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the ServiceExtensionAbility in the stage model.| +| [Accessing a DataShareExtensionAbility from the FA Model](access-datashareextensionability-from-fa.md) | No code modification is required. However, you need to understand the API compatibility of **DataShareHelper** and **DataAbilityHelper**.| +| [Starting a PageAbility from the Stage Model](start-pageability-from-stage.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the PageAbility in the FA model.| +| [Connecting to a ServiceAbility from the Stage Model](bind-serviceability-from-stage.md) | Set **bundleName** and **abilityName** in the **want** parameter to the bundle name and ability name of the ServiceAbility in the FA model.| +| Accessing a DataAbility from the Stage Model | This type of access is not supported.| diff --git a/en/application-dev/application-models/featureability-switch.md b/en/application-dev/application-models/featureability-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..f7db8056ea156650e11b55a78137de194ce9d43f --- /dev/null +++ b/en/application-dev/application-models/featureability-switch.md @@ -0,0 +1,16 @@ +# featureAbility Switching + + +| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| [getWant(callback: AsyncCallback<Want>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwant)
[getWant(): Promise<Want>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwant-1) | \@ohos.app.ability.UIAbility.d.ts | [launchWant: Want;](../reference/apis/js-apis-app-ability-uiAbility.md#attributes)| +| [startAbility(parameter: StartAbilityParameter, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartability)
[startAbility(parameter: StartAbilityParameter): Promise<number>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartability-1) | application\UIAbilityContext.d.ts | [startAbility(want: Want, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability)
[startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability-1)
[startAbility(want: Want, options?: StartOptions): Promise<void>;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability-2) | +| [getContext(): Context;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetcontext) | \@ohos.app.ability.UIAbility.d.ts | [context: UIAbilityContext;](../reference/apis/js-apis-app-ability-uiAbility.md#attributes)| +| [startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback<AbilityResult>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7)
[startAbilityForResult(parameter: StartAbilityParameter): Promise<AbilityResult>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitystartabilityforresult7-1) | application\UIAbilityContext.d.ts | [startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult)
[startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult-1)
[startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilityforresult-2) | +| [terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7)
[terminateSelfWithResult(parameter: AbilityResult): Promise<void>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityterminateselfwithresult7-1) | application\UIAbilityContext.d.ts | [terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextterminateselfwithresult)
[terminateSelfWithResult(parameter: AbilityResult): Promise<void>;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextterminateselfwithresult-1) | +| [terminateSelf(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityterminateself7)
[terminateSelf(): Promise<void>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityterminateself7-1) | application\UIAbilityContext.d.ts | [terminateSelf(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextterminateself)
[terminateSelf(): Promise<void>;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextterminateself-1) | +| [acquireDataAbilityHelper(uri: string): DataAbilityHelper;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityacquiredataabilityhelper7) | \@ohos.data.dataShare.d.ts
\@ohos.data.fileAccess.d.ts | [createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper)
[createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper>;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper-1)
[createFileAccessHelper(context: Context): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper-1)
[createFileAccessHelper(context: Context, wants: Array<Want>): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper) | +| [hasWindowFocus(callback: AsyncCallback<boolean>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityhaswindowfocus7)
[hasWindowFocus(): Promise<boolean>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityhaswindowfocus7-1) | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)
Checks whether the [active window](../reference/apis/js-apis-window.md#windowstageeventtype9) has the focus.| +| [connectAbility(request: Want, options:ConnectOptions ): number;](../reference/apis/js-apis-ability-featureAbility.md#featureabilityconnectability7) | application\UIAbilityContext.d.ts | [connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability) | +| [disconnectAbility(connection: number, callback:AsyncCallback<void>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitydisconnectability7)
[disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitydisconnectability7-1) | application\UIAbilityContext.d.ts | [disconnectAbility(connection: number, callback:AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextdisconnectserviceextensionability-1)
[disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextdisconnectserviceextensionability) | +| [getWindow(callback: AsyncCallback<window.Window>): void;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwindow7)
[getWindow(): Promise<window.Window>;](../reference/apis/js-apis-ability-featureAbility.md#featureabilitygetwindow7-1) | \@ohos.window.d.ts | [getLastWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void;](../reference/apis/js-apis-window.md#windowgetlastwindow9)
[getLastWindow(ctx: BaseContext): Promise<Window>;](../reference/apis/js-apis-window.md#windowgetlastwindow9-1) | diff --git a/en/application-dev/application-models/figures/Ability-Life-Cycle-WindowStage.png b/en/application-dev/application-models/figures/Ability-Life-Cycle-WindowStage.png new file mode 100644 index 0000000000000000000000000000000000000000..e140763dfda32a5ad168e8a6daa38a9c51baf147 Binary files /dev/null and b/en/application-dev/application-models/figures/Ability-Life-Cycle-WindowStage.png differ diff --git a/en/application-dev/application-models/figures/Ability-Life-Cycle.png b/en/application-dev/application-models/figures/Ability-Life-Cycle.png new file mode 100644 index 0000000000000000000000000000000000000000..cc0681f5f2678ca15008d7b98d7ddc34d20dcf83 Binary files /dev/null and b/en/application-dev/application-models/figures/Ability-Life-Cycle.png differ diff --git a/en/application-dev/application-models/figures/ExtensionAbility-start.png b/en/application-dev/application-models/figures/ExtensionAbility-start.png new file mode 100644 index 0000000000000000000000000000000000000000..3bd844f462199d5b7792cc5229fa763eb851a2d3 Binary files /dev/null and b/en/application-dev/application-models/figures/ExtensionAbility-start.png differ diff --git a/en/application-dev/application-models/figures/FAvsStage-uri.png b/en/application-dev/application-models/figures/FAvsStage-uri.png new file mode 100644 index 0000000000000000000000000000000000000000..132c1ba0f09f7da7344d6edcfae3c59fe355e7f9 Binary files /dev/null and b/en/application-dev/application-models/figures/FAvsStage-uri.png differ diff --git a/en/application-dev/application-models/figures/ServiceExtensionAbility-lifecycle.png b/en/application-dev/application-models/figures/ServiceExtensionAbility-lifecycle.png new file mode 100644 index 0000000000000000000000000000000000000000..fd3a15c8b1588e19d88938b39dbbc12b98d3c723 Binary files /dev/null and b/en/application-dev/application-models/figures/ServiceExtensionAbility-lifecycle.png differ diff --git a/en/application-dev/application-models/figures/api-switch-overview.png b/en/application-dev/application-models/figures/api-switch-overview.png new file mode 100644 index 0000000000000000000000000000000000000000..c17f5d3deb13d9c2d31d1b1d8b8569c7bc842676 Binary files /dev/null and b/en/application-dev/application-models/figures/api-switch-overview.png differ diff --git a/en/application-dev/application-models/figures/application-component-configuration-stage.png b/en/application-dev/application-models/figures/application-component-configuration-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..9ddf0c3892998aa5391de99775db5965f66bd4b1 Binary files /dev/null and b/en/application-dev/application-models/figures/application-component-configuration-stage.png differ diff --git a/en/application-dev/application-models/figures/application-context-stage.png b/en/application-dev/application-models/figures/application-context-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..0d4c6cdfd040b4df9930d8bc639deff32f033824 Binary files /dev/null and b/en/application-dev/application-models/figures/application-context-stage.png differ diff --git a/en/application-dev/application-models/figures/call.png b/en/application-dev/application-models/figures/call.png new file mode 100644 index 0000000000000000000000000000000000000000..5a374f942e7754fa7b4e9303c89ee53d4ff8ee2b Binary files /dev/null and b/en/application-dev/application-models/figures/call.png differ diff --git a/en/application-dev/application-models/figures/coexistence-of-FAandStage.png b/en/application-dev/application-models/figures/coexistence-of-FAandStage.png new file mode 100644 index 0000000000000000000000000000000000000000..02e09b48b3f146371ddb6acac7e4a259be4448fb Binary files /dev/null and b/en/application-dev/application-models/figures/coexistence-of-FAandStage.png differ diff --git a/en/application-dev/application-models/figures/common-event.png b/en/application-dev/application-models/figures/common-event.png new file mode 100644 index 0000000000000000000000000000000000000000..24b51ff8718ae504ba69c1e12656d4daad797a62 Binary files /dev/null and b/en/application-dev/application-models/figures/common-event.png differ diff --git a/en/application-dev/application-models/figures/comparison-of-configuration-file.png b/en/application-dev/application-models/figures/comparison-of-configuration-file.png new file mode 100644 index 0000000000000000000000000000000000000000..e0a2b47835f7814511049807f8582c50057bb459 Binary files /dev/null and b/en/application-dev/application-models/figures/comparison-of-configuration-file.png differ diff --git a/en/application-dev/application-models/figures/component-startup-inner-fa.png b/en/application-dev/application-models/figures/component-startup-inner-fa.png new file mode 100644 index 0000000000000000000000000000000000000000..f6ed21c09d9ae0d409a180885c172918a123c728 Binary files /dev/null and b/en/application-dev/application-models/figures/component-startup-inner-fa.png differ diff --git a/en/application-dev/application-models/figures/component-startup-inner-stage.png b/en/application-dev/application-models/figures/component-startup-inner-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..00514276f4ac3eb8ead650e5858cebb0a344d2c6 Binary files /dev/null and b/en/application-dev/application-models/figures/component-startup-inner-stage.png differ diff --git a/en/application-dev/application-models/figures/component-startup-inter-fa.png b/en/application-dev/application-models/figures/component-startup-inter-fa.png new file mode 100644 index 0000000000000000000000000000000000000000..2d50fb61e502ae2d2af917931d579ca2404d19b0 Binary files /dev/null and b/en/application-dev/application-models/figures/component-startup-inter-fa.png differ diff --git a/en/application-dev/application-models/figures/component-startup-inter-stage.png b/en/application-dev/application-models/figures/component-startup-inter-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..a6f79e6803edc160e5570729456569f46cc80967 Binary files /dev/null and b/en/application-dev/application-models/figures/component-startup-inter-stage.png differ diff --git a/en/application-dev/application-models/figures/context-dir.png b/en/application-dev/application-models/figures/context-dir.png new file mode 100644 index 0000000000000000000000000000000000000000..f16b56b43fbd0f493a10acecfb9b1edb79b2421f Binary files /dev/null and b/en/application-dev/application-models/figures/context-dir.png differ diff --git a/en/application-dev/application-models/figures/context-holding.png b/en/application-dev/application-models/figures/context-holding.png new file mode 100644 index 0000000000000000000000000000000000000000..fe4fbd4a4dff7024e3d5d35bd46d304d23e1f8c9 Binary files /dev/null and b/en/application-dev/application-models/figures/context-holding.png differ diff --git a/en/application-dev/application-models/figures/context-inheritance.png b/en/application-dev/application-models/figures/context-inheritance.png new file mode 100644 index 0000000000000000000000000000000000000000..2619daca03187d58db5b3690734704c66fb70d06 Binary files /dev/null and b/en/application-dev/application-models/figures/context-inheritance.png differ diff --git a/en/application-dev/application-models/figures/fa-dataability-uri.png b/en/application-dev/application-models/figures/fa-dataability-uri.png new file mode 100644 index 0000000000000000000000000000000000000000..d89ada0ee9b2f9f655a6c3d8b0df17d6b1ca9326 Binary files /dev/null and b/en/application-dev/application-models/figures/fa-dataability-uri.png differ diff --git a/en/application-dev/application-models/figures/fa-pageAbility-lifecycle.png b/en/application-dev/application-models/figures/fa-pageAbility-lifecycle.png new file mode 100644 index 0000000000000000000000000000000000000000..59a06741053c85cab6ea90b41bd16a6f2e1ff508 Binary files /dev/null and b/en/application-dev/application-models/figures/fa-pageAbility-lifecycle.png differ diff --git a/en/application-dev/application-models/figures/form-extension.png b/en/application-dev/application-models/figures/form-extension.png new file mode 100644 index 0000000000000000000000000000000000000000..ce47308856c4d41baff5dbaefdcefe9561b383b7 Binary files /dev/null and b/en/application-dev/application-models/figures/form-extension.png differ diff --git a/en/application-dev/application-models/figures/form_extension.png b/en/application-dev/application-models/figures/form_extension.png new file mode 100644 index 0000000000000000000000000000000000000000..daf36c75dae010492fa57ac05c85eaed58fbe00c Binary files /dev/null and b/en/application-dev/application-models/figures/form_extension.png differ diff --git a/en/application-dev/application-models/figures/globalThis1.png b/en/application-dev/application-models/figures/globalThis1.png new file mode 100644 index 0000000000000000000000000000000000000000..128f79d3437304845ac822d32377dab4cf0c9e05 Binary files /dev/null and b/en/application-dev/application-models/figures/globalThis1.png differ diff --git a/en/application-dev/application-models/figures/globalThis2.png b/en/application-dev/application-models/figures/globalThis2.png new file mode 100644 index 0000000000000000000000000000000000000000..11e015286489df52d5b9cd3ed35a564223b7ab4c Binary files /dev/null and b/en/application-dev/application-models/figures/globalThis2.png differ diff --git a/en/application-dev/application-models/figures/hop-cross-device-migration.png b/en/application-dev/application-models/figures/hop-cross-device-migration.png new file mode 100644 index 0000000000000000000000000000000000000000..1623bc94af414539f6634aea6d583e205eccf409 Binary files /dev/null and b/en/application-dev/application-models/figures/hop-cross-device-migration.png differ diff --git a/en/application-dev/application-models/figures/hop-multi-device-collaboration.png b/en/application-dev/application-models/figures/hop-multi-device-collaboration.png new file mode 100644 index 0000000000000000000000000000000000000000..28fa0a6e269a4266236898e19ce7bca4e670027d Binary files /dev/null and b/en/application-dev/application-models/figures/hop-multi-device-collaboration.png differ diff --git a/en/application-dev/application-models/figures/hop-structure.png b/en/application-dev/application-models/figures/hop-structure.png new file mode 100644 index 0000000000000000000000000000000000000000..96b82de856fcbc7db6d7668791a668ec152141fc Binary files /dev/null and b/en/application-dev/application-models/figures/hop-structure.png differ diff --git a/en/application-dev/application-models/figures/mission-and-singleton.png b/en/application-dev/application-models/figures/mission-and-singleton.png new file mode 100644 index 0000000000000000000000000000000000000000..eee0a39644d7080e9f9f26f30b184d679a5bff3c Binary files /dev/null and b/en/application-dev/application-models/figures/mission-and-singleton.png differ diff --git a/en/application-dev/application-models/figures/mission-and-specified.png b/en/application-dev/application-models/figures/mission-and-specified.png new file mode 100644 index 0000000000000000000000000000000000000000..6af8c28d4277b3582fed2cfc313cc301086e6314 Binary files /dev/null and b/en/application-dev/application-models/figures/mission-and-specified.png differ diff --git a/en/application-dev/application-models/figures/mission-and-standard.png b/en/application-dev/application-models/figures/mission-and-standard.png new file mode 100644 index 0000000000000000000000000000000000000000..feeed48f41371bf22abbee8dbae4695b11ed2514 Binary files /dev/null and b/en/application-dev/application-models/figures/mission-and-standard.png differ diff --git a/en/application-dev/application-models/figures/mission-chain1.png b/en/application-dev/application-models/figures/mission-chain1.png new file mode 100644 index 0000000000000000000000000000000000000000..6b9ce7dd3c74b26e0dd8d1b12e00d6414e3cdadb Binary files /dev/null and b/en/application-dev/application-models/figures/mission-chain1.png differ diff --git a/en/application-dev/application-models/figures/mission-chain2.png b/en/application-dev/application-models/figures/mission-chain2.png new file mode 100644 index 0000000000000000000000000000000000000000..7ed2b6f0052a08445c53ec2882a7f474fa5a4763 Binary files /dev/null and b/en/application-dev/application-models/figures/mission-chain2.png differ diff --git a/en/application-dev/application-models/figures/mission-chain3.png b/en/application-dev/application-models/figures/mission-chain3.png new file mode 100644 index 0000000000000000000000000000000000000000..e02c135ad4a90f99bb65bdccd821d29990b9536e Binary files /dev/null and b/en/application-dev/application-models/figures/mission-chain3.png differ diff --git a/en/application-dev/application-models/figures/mission-list-manager.png b/en/application-dev/application-models/figures/mission-list-manager.png new file mode 100644 index 0000000000000000000000000000000000000000..792745f100e6ba3613c3a496421b00bbb5f6db8f Binary files /dev/null and b/en/application-dev/application-models/figures/mission-list-manager.png differ diff --git a/en/application-dev/application-models/figures/mission-record.png b/en/application-dev/application-models/figures/mission-record.png new file mode 100644 index 0000000000000000000000000000000000000000..77f9c156d83876524977a139308046a6acfed711 Binary files /dev/null and b/en/application-dev/application-models/figures/mission-record.png differ diff --git a/en/application-dev/application-models/figures/model-switch-overview1.png b/en/application-dev/application-models/figures/model-switch-overview1.png new file mode 100644 index 0000000000000000000000000000000000000000..e9d8a120dedcda4f27f5f92e52c826b900a105d9 Binary files /dev/null and b/en/application-dev/application-models/figures/model-switch-overview1.png differ diff --git a/en/application-dev/application-models/figures/model-switch-overview2.png b/en/application-dev/application-models/figures/model-switch-overview2.png new file mode 100644 index 0000000000000000000000000000000000000000..522656745c55d165208be94b23d264c334421722 Binary files /dev/null and b/en/application-dev/application-models/figures/model-switch-overview2.png differ diff --git a/en/application-dev/application-models/figures/model-switch-overview3.png b/en/application-dev/application-models/figures/model-switch-overview3.png new file mode 100644 index 0000000000000000000000000000000000000000..e7fe19489d38bf971619dbb41294c5287377b8dc Binary files /dev/null and b/en/application-dev/application-models/figures/model-switch-overview3.png differ diff --git a/en/application-dev/application-models/figures/model-switch-overview4.png b/en/application-dev/application-models/figures/model-switch-overview4.png new file mode 100644 index 0000000000000000000000000000000000000000..e455ae9333e73b0898d6dd1700e79cbe529b7163 Binary files /dev/null and b/en/application-dev/application-models/figures/model-switch-overview4.png differ diff --git a/en/application-dev/application-models/figures/model-switch-overview5.png b/en/application-dev/application-models/figures/model-switch-overview5.png new file mode 100644 index 0000000000000000000000000000000000000000..82d5dbc6fee5b3b393e0a1abd8f4e7fbbeb0c4ac Binary files /dev/null and b/en/application-dev/application-models/figures/model-switch-overview5.png differ diff --git a/en/application-dev/application-models/figures/model-switch-overview6.png b/en/application-dev/application-models/figures/model-switch-overview6.png new file mode 100644 index 0000000000000000000000000000000000000000..c17f5d3deb13d9c2d31d1b1d8b8569c7bc842676 Binary files /dev/null and b/en/application-dev/application-models/figures/model-switch-overview6.png differ diff --git a/en/application-dev/application-models/figures/multi-process.png b/en/application-dev/application-models/figures/multi-process.png new file mode 100644 index 0000000000000000000000000000000000000000..55ab9a514c3fd1136747efc1bbb80ec900891bce Binary files /dev/null and b/en/application-dev/application-models/figures/multi-process.png differ diff --git a/en/application-dev/application-models/figures/page-ability-lifecycle.png b/en/application-dev/application-models/figures/page-ability-lifecycle.png new file mode 100644 index 0000000000000000000000000000000000000000..b35954967bb9c733725da2f0700481932619ae45 Binary files /dev/null and b/en/application-dev/application-models/figures/page-ability-lifecycle.png differ diff --git a/en/application-dev/application-models/figures/pageability-switch.png b/en/application-dev/application-models/figures/pageability-switch.png new file mode 100644 index 0000000000000000000000000000000000000000..4b68d46e529715a7258eb295bef1648da0b8ebbd Binary files /dev/null and b/en/application-dev/application-models/figures/pageability-switch.png differ diff --git a/en/application-dev/application-models/figures/process-model-fa.png b/en/application-dev/application-models/figures/process-model-fa.png new file mode 100644 index 0000000000000000000000000000000000000000..2a71de2389970a63d0a9dc2ec7d3c5b44e58a9ca Binary files /dev/null and b/en/application-dev/application-models/figures/process-model-fa.png differ diff --git a/en/application-dev/application-models/figures/process-model.png b/en/application-dev/application-models/figures/process-model.png new file mode 100644 index 0000000000000000000000000000000000000000..f6f3b22381539ac73371b4c7f6025a5c3127838b Binary files /dev/null and b/en/application-dev/application-models/figures/process-model.png differ diff --git a/en/application-dev/application-models/figures/stage-concepts.png b/en/application-dev/application-models/figures/stage-concepts.png new file mode 100644 index 0000000000000000000000000000000000000000..42e99447a780b167adaf6ddd196bea4437dfa1a7 Binary files /dev/null and b/en/application-dev/application-models/figures/stage-concepts.png differ diff --git a/en/application-dev/application-models/figures/stage-want1.png b/en/application-dev/application-models/figures/stage-want1.png new file mode 100644 index 0000000000000000000000000000000000000000..558f0a8588d7785eaad1402e68d6ba60c3118f27 Binary files /dev/null and b/en/application-dev/application-models/figures/stage-want1.png differ diff --git a/en/application-dev/application-models/figures/stage-want2.png b/en/application-dev/application-models/figures/stage-want2.png new file mode 100644 index 0000000000000000000000000000000000000000..72829adade52ee11419d726f19e218ec4de15220 Binary files /dev/null and b/en/application-dev/application-models/figures/stage-want2.png differ diff --git a/en/application-dev/application-models/figures/standard-mode.png b/en/application-dev/application-models/figures/standard-mode.png new file mode 100644 index 0000000000000000000000000000000000000000..fc903e6c1be80d3c00281d00d9ab0a1e334d7724 Binary files /dev/null and b/en/application-dev/application-models/figures/standard-mode.png differ diff --git a/en/application-dev/application-models/figures/startAbilityWtExplicitWant.PNG b/en/application-dev/application-models/figures/startAbilityWtExplicitWant.PNG new file mode 100644 index 0000000000000000000000000000000000000000..1d9e25f148d08a58a0ac45b703e08072f52fc300 Binary files /dev/null and b/en/application-dev/application-models/figures/startAbilityWtExplicitWant.PNG differ diff --git a/en/application-dev/application-models/figures/thread-model-stage.png b/en/application-dev/application-models/figures/thread-model-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..eb407a10616ce3eb1584f81ad80c4f29a7e95c10 Binary files /dev/null and b/en/application-dev/application-models/figures/thread-model-stage.png differ diff --git a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png new file mode 100644 index 0000000000000000000000000000000000000000..92292f2c6ef4c9cbd06da2a523f27b571a957e2b Binary files /dev/null and b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png differ diff --git a/en/application-dev/application-models/figures/uiability-launch-type1.png b/en/application-dev/application-models/figures/uiability-launch-type1.png new file mode 100644 index 0000000000000000000000000000000000000000..c4f5aa4b9a988d8e7148b504c4dcc163961cb103 Binary files /dev/null and b/en/application-dev/application-models/figures/uiability-launch-type1.png differ diff --git a/en/application-dev/application-models/figures/uiability-launch-type2.png b/en/application-dev/application-models/figures/uiability-launch-type2.png new file mode 100644 index 0000000000000000000000000000000000000000..6f0e43d24f745aee41601cc48f4bc138572fbeb5 Binary files /dev/null and b/en/application-dev/application-models/figures/uiability-launch-type2.png differ diff --git a/en/application-dev/application-models/figures/uiability_not_first_started.png b/en/application-dev/application-models/figures/uiability_not_first_started.png new file mode 100644 index 0000000000000000000000000000000000000000..5cff262167ce720b736d6ea554f2355efa0c928e Binary files /dev/null and b/en/application-dev/application-models/figures/uiability_not_first_started.png differ diff --git a/en/application-dev/application-models/figures/usage-of-want.png b/en/application-dev/application-models/figures/usage-of-want.png new file mode 100644 index 0000000000000000000000000000000000000000..86b41b256ee8358c0fa87899b18ae249d28668c7 Binary files /dev/null and b/en/application-dev/application-models/figures/usage-of-want.png differ diff --git a/en/application-dev/application-models/figures/want-action.png b/en/application-dev/application-models/figures/want-action.png new file mode 100644 index 0000000000000000000000000000000000000000..0d8e18ce5870bea777c26b832d3f29674c2fa261 Binary files /dev/null and b/en/application-dev/application-models/figures/want-action.png differ diff --git a/en/application-dev/application-models/figures/want-entities.png b/en/application-dev/application-models/figures/want-entities.png new file mode 100644 index 0000000000000000000000000000000000000000..bf1b85594f1d34c966c061574f6bf6c3cb75bf2f Binary files /dev/null and b/en/application-dev/application-models/figures/want-entities.png differ diff --git a/en/application-dev/application-models/figures/want-uri-type1.png b/en/application-dev/application-models/figures/want-uri-type1.png new file mode 100644 index 0000000000000000000000000000000000000000..e0fe40d1a3cd40b72379bd947aaf2e3977021b32 Binary files /dev/null and b/en/application-dev/application-models/figures/want-uri-type1.png differ diff --git a/en/application-dev/application-models/figures/want-uri-type2.png b/en/application-dev/application-models/figures/want-uri-type2.png new file mode 100644 index 0000000000000000000000000000000000000000..9a64d865066e381536a268023918975e783ddf5e Binary files /dev/null and b/en/application-dev/application-models/figures/want-uri-type2.png differ diff --git a/en/application-dev/application-models/figures/widget-development-fa.png b/en/application-dev/application-models/figures/widget-development-fa.png new file mode 100644 index 0000000000000000000000000000000000000000..795e96171e6d890e72a09382906302dd0fa45fab Binary files /dev/null and b/en/application-dev/application-models/figures/widget-development-fa.png differ diff --git a/en/application-dev/application-models/figures/widget-development-stage.png b/en/application-dev/application-models/figures/widget-development-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..795e96171e6d890e72a09382906302dd0fa45fab Binary files /dev/null and b/en/application-dev/application-models/figures/widget-development-stage.png differ diff --git a/en/application-dev/application-models/figures/widget-switch1.png b/en/application-dev/application-models/figures/widget-switch1.png new file mode 100644 index 0000000000000000000000000000000000000000..71aaf2e41cdf012820c121e5bf538b8c5b8b0784 Binary files /dev/null and b/en/application-dev/application-models/figures/widget-switch1.png differ diff --git a/en/application-dev/application-models/figures/widget-switch2.png b/en/application-dev/application-models/figures/widget-switch2.png new file mode 100644 index 0000000000000000000000000000000000000000..230836fd2c992de1d434e506bf48ff7876f1a5e8 Binary files /dev/null and b/en/application-dev/application-models/figures/widget-switch2.png differ diff --git a/en/application-dev/application-models/figures/widget-switch3.png b/en/application-dev/application-models/figures/widget-switch3.png new file mode 100644 index 0000000000000000000000000000000000000000..1e62fb7ca3be5fa73fb11d809d929b319ce05666 Binary files /dev/null and b/en/application-dev/application-models/figures/widget-switch3.png differ diff --git a/en/application-dev/application-models/figures/widget-switch4.png b/en/application-dev/application-models/figures/widget-switch4.png new file mode 100644 index 0000000000000000000000000000000000000000..65a63969a29dbf9c108618a9ea02db201ec3307d Binary files /dev/null and b/en/application-dev/application-models/figures/widget-switch4.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 new file mode 100644 index 0000000000000000000000000000000000000000..6d30435a819da49855cf9ae818bac419a1c0b614 --- /dev/null +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -0,0 +1,151 @@ +# Cross-Device Migration + + +## 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: + +- Storage and restoration of custom data + +- Storage and restoration of page routing information and page control status data + +- Application compatibility detection + + +## Cross-Device Migration Process + +The following figure shows the cross-device migration process. + +**Figure 1** Cross-device migration process +![hop-cross-device-migration](figures/hop-cross-device-migration.png) + + +## Constraints + +- Since cross-device migration task management is not available, you can only develop applications that support cross-device migration. Your application cannot initiate migration. + +- Cross-device migration can be performed between the same UIAbility component. In other words, the components must have the same **bundleName**, **abilityName**, and **signature**. + + +## Best Practices + +For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB. + + +## Available APIs + +The table below describes the main APIs used for cross-device migration. For details, see [API Reference](../reference/apis/js-apis-app-ability-uiAbility.md). + +**Table 1** Cross-device migration APIs + +| **API**| Description| +| -------- | -------- | +| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for migration and indicate whether the migration is accepted.
- **AGREE**: The migration is accepted.
- **REJECT**: The migration is rejected.
- **MISMATCH**: The version does not match.| +| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the multi-instance migration scenario.| +| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the singleton migration scenario.| + + +## How to Develop + +1. Configure the data synchronization permission in the **module.json5** file. The sample code is as follows: + + ```json + { + "module": { + "requestPermissions":[ + { + "name" : "ohos.permission.DISTRIBUTED_DATASYNC", + } + ] + } + } + ``` + +2. Configure the fields related to cross-device migration in the configuration file. + - Configure the application to support migration. + + + Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. + ```json + { + "module": { + // ... + "abilities": [ + { + // ... + "continuable": true, + } + ] + } + } + ``` + + - Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). + +3. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: + + ```ts + requestPermission() { + let context = this.context + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] + context.requestPermissionsFromUser(permissions).then((data) => { + console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)) + }).catch((error) => { + console.info("Failed to request permission from user with error: "+ JSON.stringify(error)) + }) + } + ``` + +4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. + + [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. + + - Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**. + + - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application. + + - Making a migration decision: You can determine whether to support the migration based on the return value of **onContinue()**. For details about the return value, see [Available APIs](#available-apis). + + The sample code is as follows: + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + + onContinue(wantParam : {[key: string]: any}) { + console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + let workInput = AppStorage.Get('ContinueWork'); + // Set the user input data into wantParam. + wantParam["work"] = workInput // set user input data into want params + console.info(`onContinue input = ${wantParam["input"]}`); + return AbilityConstant.OnContinueResult.AGREE + } + ``` + +5. Implement **onCreate()** and **onNewWant()** in the UIAbility of the target application to implement data restoration. + - Implementation example of **onCreate** in the multi-instance scenario + - The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**. + - You can obtain the saved migration data from the **want** parameter. + - After data restoration is complete, call **restoreWindowStage()** to trigger page restoration. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import AbilityConstant from '@ohos.app.ability.AbilityConstant'; + import distributedObject from '@ohos.data.distributedDataObject'; + + export default class EntryAbility extends UIAbility { + storage : LocalStorage; + onCreate(want, launchParam) { + console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the user data from the want parameter. + let workInput = want.parameters.work + console.info(`work input ${workInput}`) + AppStorage.SetOrCreate('ContinueWork', workInput) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } + ``` + - For a singleton ability, use **onNewWant()** to achieve the same implementation. diff --git a/en/application-dev/application-models/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md new file mode 100644 index 0000000000000000000000000000000000000000..3a6fa2646a37785d41793407d4803d60743342dd --- /dev/null +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -0,0 +1,536 @@ +# Multi-device Collaboration + + +## When to Use + +Multi-device coordination is available only for system applications. It involves the following scenarios: + +- [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned) + +- [Starting UIAbility Across Devices (Data Returned)](#starting-uiability-across-devices-data-returned) + +- [Connecting to ServiceExtensionAbility Across Devices](#connecting-to-serviceextensionability-across-devices) + +- [Using Cross-Device Ability Call](#using-cross-device-ability-call) + + +## Multi-Device Collaboration Process + +The figure below shows the multi-device collaboration process. + +**Figure 1** Multi-device collaboration process +![hop-multi-device-collaboration](figures/hop-multi-device-collaboration.png) + + +## Constraints + +- Since multi-device collaboration task management is not available, you can obtain the device list by developing system applications. Access to third-party applications is not supported. + +- Multi-device collaboration must comply with [Inter-Device Component Startup Rules](component-startup-rules.md#inter-device-component-startup-rules). + +- For better user experience, you are advised to use the **want** parameter to transmit data smaller than 100 KB. + + +## Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned) + +On device A, touch the **Start** button provided by the initiator application to start a specified UIAbility on device B. + + +### Available APIs + +**Table 1** Cross-device startup APIs + +| **API**| **Description**| +| -------- | -------- | +| startAbility(want: Want, callback: AsyncCallback<void>): void; | Starts UIAbility and ServiceExtensionAbility. This API uses an asynchronous callback to return the result.| + + +### How to Develop + +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: + + ```ts + requestPermission() { + let context = this.context; + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { + console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)); + }).catch((error) => { + console.info("Failed to request permission from user with error: "+ JSON.stringify(error)); + }) + } + ``` + +3. Obtain the device ID of the target device. + + ```ts + import deviceManager from '@ohos.distributedHardware.deviceManager'; + + let dmClass; + function initDmClass() { + // createDeviceManager is a system API. + deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => { + if (err) { + // ... + return + } + dmClass = dm + }) + } + function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass !== null) { + let list = dmClass.getTrustedDeviceListSync() + if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') { + console.info('EntryAbility onButtonClick getRemoteDeviceId err: list is null') + return; + } + return list[0].deviceId + } else { + console.info('EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null') + } + } + ``` + +4. Set the target component parameters, and call **startAbility()** to start UIAbility or ServiceExtensionAbility. + + ```ts + let want = { + deviceId: getRemoteDeviceId(), + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', // moduleName is optional. + } + // context is the ability-level context of the initiator UIAbility. + this.context.startAbility(want).then(() => { + // ... + }).catch((err) => { + // ... + }) + ``` + + +## Starting UIAbility Across Devices (Data Returned) + +On device A, touch the **Start** button provided by the initiator application to start a specified UIAbility on device B. When the UIAbility on device B exits, a value is sent back to the initiator application. + + +### Available APIs + +**Table 2** APIs for starting an ability across devices and returning the result data + +| API| Description| +| -------- | -------- | +| startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; | Starts a UIAbility. This API uses an asynchronous callback to return the result when the UIAbility is terminated.| +| terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void;| Terminates this UIAbility. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**.| +| terminateSelfWithResult(parameter: AbilityResult): Promise<void>; | Terminates this UIAbility. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**.| + + +### How to Develop + +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: + + ```ts + requestPermission() { + let context = this.context; + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { + console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)); + }).catch((error) => { + console.info("Failed to request permission from user with error: "+ JSON.stringify(error)); + }) + } + ``` + +3. Set the target component parameters on the initiator, and call **startAbilityForResult()** to start the target UIAbility. **data** in the asynchronous callback is used to receive the information returned by the target UIAbility to the initiator UIAbility after the target UIAbility terminates itself. For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). + + ```ts + let want = { + deviceId: getRemoteDeviceId(), + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', // moduleName is optional. + } + // context is the ability-level context of the initiator UIAbility. + this.context.startAbilityForResult(want).then((data) => { + // ... + }).catch((err) => { + // ... + }) + ``` + +4. After the UIAbility task at the target device is complete, call **terminateSelfWithResult()** to return the data to the initiator UIAbility. + + ```ts + const RESULT_CODE: number = 1001; + let abilityResult = { + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', + }, + } + // context is the ability-level context of the target UIAbility. + this.context.terminateSelfWithResult(abilityResult, (err) => { + // ... + }); + ``` + +5. The initiator UIAbility receives the information returned by the target UIAbility and processes the information. + + ```ts + const RESULT_CODE: number = 1001; + + // ... + + // context is the ability-level context of the initiator UIAbility. + this.context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the target UIAbility. + let info = data.want?.parameters?.info + // ... + } + }).catch((err) => { + // ... + }) + ``` + + +## Connecting to ServiceExtensionAbility Across Devices + +A system application can connect to a service on another device by calling [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability). For example, in the distributed game scenario, a tablet is used as the remote control and a smart TV is used as the display. + + +### Available APIs + +**Table 3** APIs for cross-device connection + +| API| Description| +| -------- | -------- | +| connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; | Connects to a ServiceExtensionAbility.| +| disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void; | Disconnects a connection. This API uses an asynchronous callback to return the result.| +| disconnectServiceExtensionAbility(connection: number): Promise<void>; | Disconnects a connection. This API uses a promise to return the result.| + + +### How to Develop + +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: + + ```ts + requestPermission() { + let context = this.context; + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { + console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)); + }).catch((error) => { + console.info("Failed to request permission from user with error: "+ JSON.stringify(error)); + }) + } + ``` + +3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available. + +4. Connect to the background service. + - Implement the **IAbilityConnection** class. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a service is connected, **onDisconnect()** is invoked when a service is unexpectedly disconnected, and **onFailed()** is invoked when the connection to a service fails. + - Set the target component parameters, including the target device ID, bundle name, and ability name. + - Call **connectServiceExtensionAbility** to initiate a connection. + - Receive the service handle returned by the target device when the connection is successful. + - Perform cross-device invoking and obtain the result returned by the target service. + + ```ts + import rpc from '@ohos.rpc'; + + const REQUEST_CODE = 99; + let want = { + "deviceId": getRemoteDeviceId(), + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" + }; + let options = { + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); // You can send data to the target application for corresponding operations. + + // @param code Indicates the service request code sent by the client. + // @param data Indicates the {@link MessageParcel} object sent by the client. + // @param reply Indicates the response message object sent by the remote service. + // @param options Specifies whether the operation is synchronous or asynchronous. + // + // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. + remote.sendRequest(REQUEST_CODE, data, reply, option).then((ret) => { + let msg = reply.readInt(); // Receive the information (100) returned by the target device if the connection is successful. + console.info(`sendRequest ret:${ret} msg:${msg}`); + }).catch((error) => { + console.info('sendRequest failed'); + }); + }, + onDisconnect(elementName) { + console.info('onDisconnect callback'); + }, + onFailed(code) { + console.info('onFailed callback'); + } + } + // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. + let connectionId = this.context.connectServiceExtensionAbility(want, options); + ``` + + For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). + +5. Disconnect the connection. Use **disconnectServiceExtensionAbility()** to disconnect from the background service. + + ```ts + let connectionId = 1 // ID returned when the service is connected through connectServiceExtensionAbility. + this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { + console.info('disconnectServiceExtensionAbility success'); + }).catch((error) => { + console.error('disconnectServiceExtensionAbility failed'); + }) + ``` + + +## 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 following describes how to implement multi-device collaboration through cross-device ability call. + + +### Available APIs + +**Table 4** Ability call APIs + +| API| Description| +| -------- | -------- | +| startAbilityByCall(want: Want): Promise<Caller>; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.| +| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| +| off(method: string): void | Callback invoked when the callee ability deregisters a method.| +| call(method: string, data: rpc.Sequenceable): Promise<void> | Sends agreed sequenceable data to the callee ability.| +| callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel> | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| +| release(): void | Releases the caller object.| +| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| + + +### How to Develop + +1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: + + ```ts + requestPermission() { + let context = this.context; + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { + console.info("Succeed to request permission from user with data: "+ JSON.stringify(data)); + }).catch((error) => { + console.info("Failed to request permission from user with error: "+ JSON.stringify(error)); + }) + } + ``` + +3. Create the callee ability. + + For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. + + 1. Configure the launch type of the UIAbility. + + 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**.| + + An example of the UIAbility 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 + }] + ``` + + 2. Import the **UIAbility** module. + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + ``` + + 3. Define the agreed sequenceable data. + + 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 + str: string = "" + + constructor(num, string) { + this.num = num + this.str = string + } + + marshalling(messageParcel) { + messageParcel.writeInt(this.num) + messageParcel.writeString(this.str) + return true + } + + unmarshalling(messageParcel) { + this.num = messageParcel.readInt() + this.str = messageParcel.readString() + return true + } + } + ``` + + 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)}`) + } + } + } + ``` + +4. Obtain the caller object and access the callee ability. + 1. Import the **UIAbility** module. + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + ``` + + 2. Obtain the caller object. + + 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 + async onButtonGetRemoteCaller() { + var caller = undefined + var context = this.context + + context.startAbilityByCall({ + deviceId: getRemoteDeviceId(), + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }).then((data) => { + if (data != null) { + caller = data + console.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 register OnRelease succeed') + } + }).catch((error) => { + console.error(`get remote caller failed with ${error}`) + }) + } + ``` + + For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). + +5. Sends agreed sequenceable data to the callee ability. + 1. The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. + + ```ts + const MSG_SEND_METHOD: string = 'CallSendMsg'; + async onButtonCall() { + try { + let msg = new MySequenceable(1, 'origin_Msg'); + await this.caller.call(MSG_SEND_METHOD, msg); + } catch (error) { + console.info(`caller call failed with ${error}`); + } + } + ``` + 2. In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. + + ```ts + const MSG_SEND_METHOD: string = 'CallSendMsg'; + originMsg: string = ''; + backMsg: string = ''; + async onButtonCallWithResult(originMsg, backMsg) { + try { + let msg = new MySequenceable(1, originMsg); + const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg); + console.info('caller callWithResult succeed'); + + let result = new MySequenceable(0, ''); + data.readSequenceable(result); + backMsg(result.str); + console.info(`caller result is [${result.num}, ${result.str}]`); + } catch (error) { + console.info(`caller callWithResult failed with ${error}`); + } + } + ``` + +6. Release the caller object. + + When the caller object is no longer required, use **release()** to release it. + + ```ts + releaseCall() { + try { + this.caller.release(); + this.caller = undefined + console.info('caller release succeed'); + } catch (error) { + console.info(`caller release failed with ${error}`); + } + } + ``` diff --git a/en/application-dev/application-models/inter-device-interaction-hop-overview.md b/en/application-dev/application-models/inter-device-interaction-hop-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6b1fd28b489f0d6d891abd9dffa0bcaf0f1b9ead --- /dev/null +++ b/en/application-dev/application-models/inter-device-interaction-hop-overview.md @@ -0,0 +1,49 @@ +# Continuation Overview + + +## When to Use + +As the all-scenario, multi-device lifestyle becomes popular, users have an increasing number of devices. Each device provides users with what they need in a certain scenario. For example, watches allow users to view information in a timely manner, and smart TVs bring them an immersive watching experience. However, each device has its limitation, for example, typing text on a smart TV is frustrating as it is much more difficult than on a mobile device. If multiple devices can sense each other through a distributed OS and together form a super device, the strengths of each device can be fully exerted to provide a more natural and smoother distributed experience for users. + +In OpenHarmony, distributed operations across devices are called continuation (previously named hopping), which is further classified into [cross-device migration](hop-cross-device-migration.md) and [multi-device collaboration](hop-multi-device-collaboration.md). To implement continuation, cross-device interaction capabilities of application components are required. Currently, these capabilities are open only to system applications. + + +## Basic Concepts + +- **Continuation** + + Continuation refers to distributed operations across devices. It breaks device boundaries and makes applications modular. For example, a user can edit the same email, carry out fitness, or play a game across devices. Continuation provides broad application scenarios, innovative product perspectives, enhanced product advantages, and superior experience. + +- **Cross-device migration** + + When the environment changes, for example, when a user goes outdoors or when a more appropriate device is detected, the user can migrate an ongoing task to another device for better experience. The original device exits the task. A typical cross-device migration scenario is as follows: You migrate a video playback task from your tablet to a smart TV. The video application on the tablet exits. From the perspective of application development, cross-device migration migrates the UIAbility component running on device A to device B. After the migration is complete, the UIAbility component on device B continues the task, whereas that on device A exits. + +- **Multi-device collaboration** + + Multi-device collaboration enables collaboration between multiple devices, providing users with more efficient and immersive experience than with a single device. A typical multi-device collaboration scenario is as follows: Application A on the tablet is used as the answer board, and application B on the smart TV is used for live broadcast, delivering a better online class experience. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. + + +## Continuation Architecture + +OpenHarmony provides a set of APIs for you to implement continuation in your applications. The continuation architecture has the following advantages: + +- Capabilities such as remote service invocation to facilitate service design + +- Simultaneous continuation of multiple applications + +- Different device forms supported, such as tablets, smart TVs, and watches + +The following figure shows the continuation architecture. + + **Figure 1** Continuation architecture +hop-structure + +- Cross-device migration task management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. (This capability is unavailable yet.) + +- Multi-device collaboration task management: The initiator accepts an application registration request and provides management capabilities such as starting or stopping collaboration and status display. (This capability is unavailable yet.) + +- Distributed component management: provides capabilities such as remote service startup, remote service connection, and remote migration, and enables cross-device migration or multi-device collaboration of applications based on a combination of these capabilities. + +- Distributed security authentication: provides an E2E encrypted channel for cross-device transmission between applications to ensure that the right person uses the right data through the right device. + +- DSoftBus: functions as a unified communication base for a wide range of devices such as tablets, wearables, and smart TVs, and enables unified distributed communication between these devices. diff --git a/en/application-dev/application-models/itc-fa-overview.md b/en/application-dev/application-models/itc-fa-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..112a89edd8ba8236fca714a65d6f93287dcbe41d --- /dev/null +++ b/en/application-dev/application-models/itc-fa-overview.md @@ -0,0 +1,4 @@ +# Inter-Thread Communication (FA Model) + + +For details, see [Inter-Thread Communication](thread-model-stage.md) in the stage model. diff --git a/en/application-dev/application-models/itc-with-emitter.md b/en/application-dev/application-models/itc-with-emitter.md new file mode 100644 index 0000000000000000000000000000000000000000..2966bd8eea41e04893814f20a3c5b2f9e4e456c9 --- /dev/null +++ b/en/application-dev/application-models/itc-with-emitter.md @@ -0,0 +1,49 @@ +# Using Emitter for Inter-Thread Communication + +[Emitter](../reference/apis/js-apis-emitter.md) provides APIs for sending and processing events between threads, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. + + +To develop the Emitter mode, perform the following steps: + + +1. Subscribe to an event. + + ```ts + import emitter from "@ohos.events.emitter"; + + // Define an event with eventId 1. + let event = { + eventId: 1 + }; + + // Trigger the callback after the event with eventId 1 is received. + let callback = (eventData) => { + console.info('event callback'); + }; + + // Subscribe to the event with eventId 1. + emitter.on(event, callback); + ``` + +2. Emit the event. + + ```ts + import emitter from "@ohos.events.emitter"; + + // Define an event with eventId 1 and priority Low. + let event = { + eventId: 1, + priority: emitter.EventPriority.LOW + }; + + let eventData = { + data: { + "content": "c", + "id": 1, + "isEmpty": false, + } + }; + + // Emit the event with eventId 1 and event content eventData. + emitter.emit(event, eventData); + ``` diff --git a/en/application-dev/application-models/itc-with-worker.md b/en/application-dev/application-models/itc-with-worker.md new file mode 100644 index 0000000000000000000000000000000000000000..8cbe53eeea067ae1875a8ff4b73bc4cde7bdd629 --- /dev/null +++ b/en/application-dev/application-models/itc-with-worker.md @@ -0,0 +1,79 @@ +# Using Worker for Inter-Thread Communication + +[Worker](../reference/apis/js-apis-worker.md) is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The script file passed in during worker creation is executed in the worker thread. Generally, time-consuming operations are processed in the worker thread. However, pages cannot be directly updated in the worker thread. + + +To develop the Worker mode, perform the following steps: + + +1. Configure the **buildOption** field in the [module-level build-profile.json5](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-building-configuration-0000001218440654#section6887184182020) file of the project. + + ```ts + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] + } + } + ``` + +2. Create the **worker.js** file based on the configuration in **build-profile.json5**. + + ```ts + import worker from '@ohos.worker'; + + let parent = worker.workerPort; + + // Process messages from the main thread. + parent.onmessage = function(message) { + console.info("onmessage: " + message) + // Send a message to the main thread. + parent.postMessage("message from worker thread.") + } + ``` + +3. In the main thread, use the following method to initialize and use the worker thread. + - Stage model: + + ```ts + import worker from '@ohos.worker'; + + let wk = new worker.ThreadWorker("entry/ets/workers/worker.ts"); + + // Send a message to the worker thread. + wk.postMessage("message from main thread.") + + // Process messages from the worker thread. + wk.onmessage = function(message) { + console.info("message from worker: " + message) + + // Stop the worker thread based on service requirements. + wk.terminate() + } + ``` + + - FA model: + + ```ts + import worker from '@ohos.worker'; + + let wk = new worker.ThreadWorker("../workers/worker.js"); + + // Send a message to the worker thread. + wk.postMessage("message from main thread.") + + // Process messages from the worker thread. + wk.onmessage = function(message) { + console.info("message from worker: " + message) + + // Stop the worker thread based on service requirements. + wk.terminate() + } + ``` + +> **NOTE** +> +> - If the relative path of **worker.ts** configured in **build-profile.json5** is **./src/main/ets/workers/worker.ts**, pass in the path **entry/ets/workers/worker.ts** when creating a worker thread in the stage model, and pass in the path **../workers/worker.js** when creating a worker thread in the FA model. +> +> - For details about the data types supported between the main thread and worker thread, see [Sequenceable Data Types](../reference/apis/js-apis-worker.md#sequenceable-data-types). diff --git a/en/application-dev/application-models/lifecycleapp-switch.md b/en/application-dev/application-models/lifecycleapp-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..892a8915bfed9927c2707364bdaffa1547f71bf6 --- /dev/null +++ b/en/application-dev/application-models/lifecycleapp-switch.md @@ -0,0 +1,21 @@ +# LifecycleApp Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| onShow?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)
Listens for the switching to the [foreground](../reference/apis/js-apis-window.md#windowstageeventtype9).| +| onHide?(): void; | \@ohos.window.d.ts | [on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;](../reference/apis/js-apis-window.md#onwindowstageevent9)
Listens for the switching to the [background](../reference/apis/js-apis-window.md#windowstageeventtype9).| +| onDestroy?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityondestroy) | +| onCreate?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate) | +| onWindowDisplayModeChanged?(isShownInMultiWindow: boolean, newConfig: resourceManager.Configuration): void; | There is no corresponding API in the stage model.| No corresponding API is provided.| +| onStartContinuation?(): boolean; | There is no corresponding API in the stage model.| In the stage model, an application does not need to detect whether the continuation is successful (detected when the application initiates the continuation request). Therefore, the **onStartContinuation()** callback is deprecated.| +| onSaveData?(data: Object): boolean; | \@ohos.app.ability.UIAbility.d.ts | [onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) | +| onCompleteContinuation?(result: number): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | +| onRestoreData?(data: Object): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
[onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)
In standard or singleton mode, the target ability completes data restoration in the **onCreate()** callback. In the callback, **launchParam.launchReason** is used to determine whether it is a continuation-based launch scenario. If it is, the data saved before continuation can be obtained from the **want** parameter.| +| onRemoteTerminated?(): void; | application\ContinueCallback.d.ts | [onContinueDone(result: number): void;](../reference/apis/js-apis-distributedMissionManager.md#continuecallback) | +| onSaveAbilityState?(outState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonsavestate) | +| onRestoreAbilityState?(inState: PacMap): void; | \@ohos.app.ability.UIAbility.d.ts | [onCreate(want: Want, param: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncreate)
After the application is restarted, the **onCreate()** callback is triggered. In the callback, **launchParam.launchReason** is used to determine whether it is a self-recovery scenario. If it is, the data saved before the restart can be obtained from the **want** parameter.| +| onInactive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onBackground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonbackground) | +| onActive?(): void; | \@ohos.app.ability.UIAbility.d.ts | [onForeground(): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonforeground) | +| onNewWant?(want: Want): void; | \@ohos.app.ability.UIAbility.d.ts | [onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) | +| onMemoryLevel?(level: number): void | \@ohos.app.ability.UIAbility.d.ts | [onMemoryLevel(level: AbilityConstant.MemoryLevel): void;](../reference/apis/js-apis-app-ability-ability.md#abilityonmemorylevel) | diff --git a/en/application-dev/application-models/lifecycledata-switch.md b/en/application-dev/application-models/lifecycledata-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..be96421a92161deeb26c9e99af9ec5de332d9e25 --- /dev/null +++ b/en/application-dev/application-models/lifecycledata-switch.md @@ -0,0 +1,18 @@ +# LifecycleData Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#update) | +| query?(uri: string, columns: Array<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<ResultSet>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#query) | +| delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback<number>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#delete) | +| normalizeUri?(uri: string, callback: AsyncCallback<string>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [normalizeUri?(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#normalizeuri) | +| batchInsert?(uri: string, valueBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback<number>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#batchinsert) | +| denormalizeUri?(uri: string, callback: AsyncCallback<string>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [denormalizeUri?(uri: string, callback: AsyncCallback<string>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#denormalizeuri) | +| insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback<number>): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#insert) | +| openFile?(uri: string, mode: string, callback: AsyncCallback<number>): void; | There is no corresponding API in the stage model.| The stage model does not support cross-process URI access. You are advised to use [the want parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| +| getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void; | There is no corresponding API in the stage model.| The stage model does not support cross-process URI access. You are advised to use [the want parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| +| onInitialized?(info: AbilityInfo): void; | \@ohos.application.DataShareExtensionAbility.d.ts | [onCreate?(want: Want, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-application-dataShareExtensionAbility.md#oncreate) | +| getType?(uri: string, callback: AsyncCallback<string>): void; | There is no corresponding API in the stage model.| The stage model does not support cross-process URI access. You are advised to use [the want parameter to carry the file descriptor and file information](data-share-via-want.md) for cross-process file access.| +| executeBatch?(ops: Array<DataAbilityOperation>, callback: AsyncCallback<Array<DataAbilityResult>>): void; | There is no corresponding API in the stage model.| No corresponding API is provided.| +| call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback<PacMap>): void; | There is no corresponding API in the stage model.| No corresponding API is provided.| diff --git a/en/application-dev/application-models/lifecycleform-switch.md b/en/application-dev/application-models/lifecycleform-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..80e577eeac759f589cb53c6b367ae17ba8b98e8c --- /dev/null +++ b/en/application-dev/application-models/lifecycleform-switch.md @@ -0,0 +1,13 @@ +# LifecycleForm Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| onCreate?(want: Want): formBindingData.FormBindingData; | \@ohos.app.form.FormExtensionAbility.d.ts | [onAddForm(want: Want): formBindingData.FormBindingData;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) | +| onCastToNormal?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onCastToNormalForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform) | +| onUpdate?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onUpdateForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform) | +| onVisibilityChange?(newStatus: { [key: string]: number }): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onChangeFormVisibility(newStatus: { [key: string]: number }): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onchangeformvisibility) | +| onEvent?(formId: string, message: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onFormEvent(formId: string, message: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) | +| onDestroy?(formId: string): void; | \@ohos.app.form.FormExtensionAbility.d.ts | [onRemoveForm(formId: string): void;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform) | +| onAcquireFormState?(want: Want): formInfo.FormState; | \@ohos.app.form.FormExtensionAbility.d.ts | [onAcquireFormState?(want: Want): formInfo.FormState;](../reference/apis/js-apis-app-form-formExtensionAbility.md#onacquireformstate) | +| onShare?(formId: string): {[key: string]: any}; | \@ohos.app.form.FormExtensionAbility.d.ts | [onShareForm?(formId: string): { [key: string]: any };](../reference/apis/js-apis-app-form-formExtensionAbility.md#onshareform) | diff --git a/en/application-dev/application-models/lifecycleservice-switch.md b/en/application-dev/application-models/lifecycleservice-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..d1fcdc7a30efb0114e092ac5a6233566270312fa --- /dev/null +++ b/en/application-dev/application-models/lifecycleservice-switch.md @@ -0,0 +1,11 @@ +# LifecycleService Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| onStart?(): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onCreate(want: Want): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityoncreate) | +| onCommand?(want: Want, startId: number): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onRequest(want: Want, startId: number): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest) | | +| onStop?(): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onDestroy(): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityondestroy) | | +| onConnect?(want: Want): rpc.RemoteObject; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onConnect(want: Want): rpc.RemoteObject;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonconnect) | | +| onDisconnect?(want: Want): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onDisconnect(want: Want): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityondisconnect) | | +| onReconnect?(want: Want): void; | \@ohos.app.ability.ServiceExtensionAbility.d.ts | [onReconnect(want: Want): void;](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonreconnect) | | diff --git a/en/application-dev/application-models/medialibrary-switch.md b/en/application-dev/application-models/medialibrary-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..29e9b10964d2b9c967960f6c2ad802a942aa0ac3 --- /dev/null +++ b/en/application-dev/application-models/medialibrary-switch.md @@ -0,0 +1,6 @@ +# mediaLibrary Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| [getMediaLibrary(): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary) | \@ohos.multimedia.mediaLibrary.d.ts | [getMediaLibrary(context: Context): MediaLibrary;](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) | diff --git a/en/application-dev/application-models/mission-management-fa.md b/en/application-dev/application-models/mission-management-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..07641af7d736f298c99908805a5493cadadd4b00 --- /dev/null +++ b/en/application-dev/application-models/mission-management-fa.md @@ -0,0 +1,4 @@ +# Mission Management (FA Model) + + +For details, see [Mission Management](mission-management-overview.md) in the stage model. diff --git a/en/application-dev/application-models/mission-management-launch-type.md b/en/application-dev/application-models/mission-management-launch-type.md new file mode 100644 index 0000000000000000000000000000000000000000..72b6dbf80df2628119ebcc29339ed7e4b70e9a50 --- /dev/null +++ b/en/application-dev/application-models/mission-management-launch-type.md @@ -0,0 +1,33 @@ +# Mission Management and Launch Type + + +One UIAbility instance corresponds to one mission. The number of UIAbility instances is related to the UIAbility launch type, specified by **launchType**, which is configured in the **config.json** file in the FA model and the [module.json5](../quick-start/module-configuration-file.md) file in the stage model. + + +The following describes how the mission list manager manages the UIAbility instanced started in different modes. +- **singleton**: Only one UIAbility instance exists for an application. + + **Figure 1** Missions and singleton mode + ![mission-and-singleton](figures/mission-and-singleton.png) + +- **standard**: Each time **startAbility()** is called, a UIAbility instance is created in the application process. + + **Figure 2** Missions and standard mode + ![mission-and-standard](figures/mission-and-standard.png) + +- **specified**: The ([onAcceptWant](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)) method of [AbilityStage](abilitystage.md) determines whether to create an instance. + + **Figure 3** Missions and specified mode + ![mission-and-specified](figures/mission-and-specified.png) + + +Each UIAbility instance corresponds to a mission displayed in **Recents**. + + +Every mission retains a snapshot of the UIAbility instance. After the UIAbility instance is destroyed, the mission information (including the ability information and mission snapshot) is retained until the mission is deleted. + + +> **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 new file mode 100644 index 0000000000000000000000000000000000000000..b6f6668f7ce56a9de0b5a3d0182b14ec189703c9 --- /dev/null +++ b/en/application-dev/application-models/mission-management-overview.md @@ -0,0 +1,129 @@ +# Mission Management Scenarios + + +Before getting started with the development of mission management, be familiar with the following concepts related to mission management: + + +- AbilityRecord: minimum unit for the system service to manage a UIAbility instance. It corresponds to a UIAbility component instance of an application. + +- MissionRecord: minimum unit for mission management. One MissionRecord has only one AbilityRecord. In other words, a UIAbility component instance corresponds to a mission. + +- MissionList: a list of missions started from the home screen. It records the startup relationship between missions. In a MissionList, an above mission is started by the mission under it, and the mission at the bottom is started by the home screen. + +- MissionListManager: system mission management module that maintains all the MissionLists and is consistent with the list in **Recents**. + + **Figure 1** Mission management + ![mission-list-manager](figures/mission-list-manager.png) + + +Missions are managed by system applications (such as home screen), rather than third-party applications. Users interact with missions through **Recents**. After creating a mission, users can perform the following operations on **Recents**: + + +- Delete a mission. + +- Lock or unlock a mission. (Locked missions are not cleared when users attempt to clear all missions in **Recents**.) + +- Clear all missions in **Recents**. + +- 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. + + +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). + + +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' + +let listener = { + // Listen for mission creation. + onMissionCreated: function (mission) { + console.info("--------onMissionCreated-------") + }, + // Listen for mission destruction. + onMissionDestroyed: function (mission) { + console.info("--------onMissionDestroyed-------") + }, + // Listen for mission snapshot changes. + onMissionSnapshotChanged: function (mission) { + console.info("--------onMissionSnapshotChanged-------") + }, + // Listen for switching the mission to the foreground. + onMissionMovedToFront: function (mission) { + console.info("--------onMissionMovedToFront-------") + }, + // Listen for mission icon changes. + onMissionIconUpdated: function (mission, icon) { + console.info("--------onMissionIconUpdated-------") + }, + // Listen for mission name changes. + onMissionLabelUpdated: function (mission) { + console.info("--------onMissionLabelUpdated-------") + }, + // Listen for mission closure events. + onMissionClosed: function (mission) { + console.info("--------onMissionClosed-------") + } +}; + +// 1. Register a mission change listener. +let listenerId = missionManager.on('mission', listener); + +// 2. Obtain the latest 20 missions in the system. +missionManager.getMissionInfos("", 20, (error, missions) => { + console.info("getMissionInfos is called, error.code = " + error.code); + console.info("size = " + missions.length); + console.info("missions = " + JSON.stringify(missions)); +}); + +// 3. Obtain the detailed information about a mission. +let missionId = 11; // The mission ID 11 is only an example. +let mission = missionManager.getMissionInfo("", missionId).catch(function (err) { + console.info(err); +}); + +// 4. Obtain the mission snapshot. +missionManager.getMissionSnapShot("", missionId, (error, snapshot) => { + console.info("getMissionSnapShot is called, error.code = " + error.code); + console.info("bundleName = " + snapshot.ability.bundleName); +}) + +// 5. Obtain the low-resolution mission snapshot. +missionManager.getLowResolutionMissionSnapShot("", missionId, (error, snapshot) => { + console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code); + console.info("bundleName = " + snapshot.ability.bundleName); +}) + +// 6. Lock or unlock the mission. +missionManager.lockMission(missionId).then(() => { + console.info("lockMission is called "); +}); + +missionManager.unlockMission(missionId).then(() => { + console.info("unlockMission is called "); +}); + +// 7. Switch the mission to the foreground. +missionManager.moveMissionToFront(missionId).then(() => { + console.info("moveMissionToFront is called "); +}); + +// 8. Clear a single mission. +missionManager.clearMission(missionId).then(() => { + console.info("clearMission is called "); +}); + +// 9. Clear all missions. +missionManager.clearAllMissions().catch(function (err) { + console.info(err); +}); + +// 10. Deregister the mission change listener. +missionManager.off('mission', listenerId, (error) => { + console.info("unregisterMissionListener"); +}) +``` diff --git a/en/application-dev/application-models/model-switch-overview.md b/en/application-dev/application-models/model-switch-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..e42882ca59b33c65fe6591510954d95e2c49453b --- /dev/null +++ b/en/application-dev/application-models/model-switch-overview.md @@ -0,0 +1,23 @@ +# Model Switching Overview + + +Perform the following operations to switch a declarative paradigm-based application developed based on the FA model to the stage model. + + +- Project switch: Create an application project of the stage model. + ![model-switch-overview1](figures/model-switch-overview1.png) + +- [Configuration file switch](configuration-file-diff.md): Switch **config.json** to **app.json5** and **module.json5**. + ![model-switch-overview2](figures/model-switch-overview2.png) + +- [Component switch](pageability-switch.md): Switch the PageAbility, ServiceAbility, and DataAbility components of the FA model to the UIAbility and ExtensionAbility components of the stage model. The figure below shows only the switching from PageAbility to UIAbility. The left part is the FA model, and **app.ets** is the PageAbility component. The right part is the stage model, and **EntryAbility.ts** is the UIAbility component. + +![model-switch-overview3](figures/model-switch-overview3.png) + +- [Widget switch](widget-switch.md): Switch the FormAbility component of the FA model to the FormExtensionAbility component of the stage model. In the figure below, **Service Widget** is FormAbility in the FA model and FormExtensionAbility in the stage model. + ![model-switch-overview4](figures/model-switch-overview4.png) + + ![model-switch-overview5](figures/model-switch-overview5.png) + +- [API switch](api-switch-overview.md): Switch the APIs with the **FAModelOnly** tag used in the FA model to the recommended APIs in the stage model. + ![model-switch-overview6](figures/model-switch-overview6.png) diff --git a/en/application-dev/application-models/module-switch.md b/en/application-dev/application-models/module-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..a6e532e94827198880cb772c174725b2a89c469b --- /dev/null +++ b/en/application-dev/application-models/module-switch.md @@ -0,0 +1,75 @@ +# Switching of module + + +When switching an application from the FA model to the stage model, you must migrate the configurations under the **module** tag in the **config.json** file to the **module** tag in the **module.json5** file. + +### **Table 1** module comparison + +| Field Name in the FA Model| Field Description| Field Name in the Stage Model| Difference| +| -------- | -------- | -------- | -------- | +| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| mainElement | The field name is changed, and the stage mode does not use the period (.) in ability names.| +| package | Package name of the HAP file, which must be unique in the application.| / | The stage model uses **name** to ensure application uniqueness. To ensure a successful switching from the FA model to the stage model, **name** in the stage model must be the same as **package** in the FA model.| +| name | Class name of the HAP file.| / | This configuration is not enabled in the FA model, and the stage model does not have such a field.| +| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined.| / | This configuration is deprecated in the stage model.| +| moduleName in the distro object| Name of the current HAP file.
moduleName in the distro object.| name | The field name is changed.| +| moduleType in the distro object| Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this field to **har**.| type | The field name is changed.| +| installationFree in the distro object| Whether the HAP file supports the installation-free feature.| installationFree | The field name is changed.| +| deliveryWithInstall in the distro object| Whether the HAP file is installed with the application.| deliveryWithInstall | The field name is changed.| +| metaData | Metadata of the HAP file.| metadata | See [Table 2](#table-2-metadata-comparison).| +| abilities | All abilities in the current module.| abilities | See [Table 5](#table-5-abilities-comparison).| +| js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module.| pages | The stage model retains **pages** under the **module** tag. The window configuration is the lower level of **pages**.| +| shortcuts | Shortcuts of the application.| shortcut_config.json| In the stage model, the **shortcut_config.json** file is defined in **resources/base/profile** in the development view.| +| reqPermissions | Permissions that the application requests from the system when it is running.| requestPermissions | The field name is changed.| +| colorMode | Color mode of the application.| / | This configuration is not supported in the stage model.| +| distroFilter | Distribution rules of the application.| distroFilter_config.json| In the stage model, the **distroFilter_config.json** file is defined in **resources/base/profile** in the development view.| +| reqCapabilities | Device capabilities required for running the application.| / | This configuration is not supported in the stage model.| +| commonEvents | Common events.| common_event_config.json| In the stage model, the **common_event_config.json** file is defined in **resources/base/profile** in the development view.| +| entryTheme | Keyword of an OpenHarmony internal theme.| / | This configuration is not supported in the stage model.| + + +### Table 2 metaData comparison + +| Field Name Under metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| -------- | -------- | -------- | -------- | +| parameters | Metadata of the parameters to be passed for calling the ability.| / | This configuration is not supported in the stage model.| +| results | Metadata of the ability return value.| / | This configuration is not supported in the stage model.| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| metadata | See [Table 3](#table-3-comparison-between-customizedata-under-metadata-in-the-fa-model-and-metadata-in-the-stage-model).| + +### Table 3 Comparison between customizeData under metaData in the FA model and metadata in the stage model + +| Field Name Under customizeData in metaData in the FA Model| Field Description| Field Name Under metaData in the Stage Model| Difference| +| -------- | -------- | -------- | -------- | +| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| name | None.| +| value | Value of the data item. The value is a string with a maximum of 255 bytes.| value | None.| +| extra | Format of the current custom data. The value is the resource value of **extra**.| resource | The field name is changed. For details, see [Table 4](#table 4-metadata-examples).| + + +### Table 4 metaData examples + +| Example in the FA Model| Example in the Stage Model| +| -------- | -------- | +| "meteData": {
"customizeDate": [{
"name": "label",
"value": "string",
"extra": "$string:label",
}]
} | "meteData": [{
"name": "label",
"value": "string",
"resource": "$string:label",
}] | + + +### Table 5 abilities comparison + +| Field Name Under abilities in the FA Model| Field Description| Field Name Under abilities in the Stage Model| Difference| +| -------- | -------- | -------- | -------- | +| process | Name of the process running the application or ability.| / | The stage model does not support configuration of **process** under **abilities**. The configuration of **process** is available under the **module** tag.| +| uri | URI of the ability.| / | This configuration is not supported in the stage model.| +| deviceCapability | Device capabilities required to run the ability.| / | This configuration is not supported in the stage model.| +| metaData | Metadata of the ability.| metadata | See [Table 2](#table-2-metadata-comparison).| +| type | Ability type.| / | This configuration is not supported in the stage model.| +| grantPermission | Whether permissions can be granted for any data in the ability.| / | The stage model does not support such a configuration under **abilities**.| +| readPermission | Permission required for reading data in the ability. This field applies only to the ability using the Data template.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| +| writePermission | Permission required for writing data to the ability.| / | In the stage model, this configuration is available under **extensionAbilities**, but not **abilities**.| +| configChanges | System configurations that the ability concerns.| / | This configuration is not supported in the stage model.| +| mission | Mission stack of the ability.| / | This configuration is not supported in the stage model.| +| targetAbility | Target ability that this ability alias points to.| / | This configuration is not supported in the stage model.| +| multiUserShared | Whether the ability supports data sharing among multiple users. This field applies only to the ability using the Data template.| / | This configuration is not supported in the stage model.| +| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window).| / | This configuration is not supported in the stage model.| +| formsEnabled | Whether the ability can provide widgets.| / | This configuration is not supported in the stage model.| +| forms | Information about the widgets used by the ability. This field is valid only when **formsEnabled** is set to **true**.| form_config.json| In the stage model, the **form_config.json** file is defined in **resources/base/profile** in the development view.| +| srcLanguage | Programming language used to develop the ability.| / | This configuration is not supported in the stage model.| +| srcPath | Path of the JS component code corresponding to the ability.| srcEntrance | Path of the JS code corresponding to the ability.| +| uriPermission | Application data that the ability can access.| / | This configuration is not supported in the stage model.| diff --git a/en/application-dev/application-models/page-mission-stack.md b/en/application-dev/application-models/page-mission-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..702cb9ba928d5266ce6720d10538df6109b0cbeb --- /dev/null +++ b/en/application-dev/application-models/page-mission-stack.md @@ -0,0 +1,51 @@ +# Page Stack and MissionList + + +## Page Stack + +A single UIAbility component can implement multiple pages and redirection between these pages. The redirection relationship inside the UIAbility component is called page stack, which is managed by the ArkUI framework. For example, Page1 -> Page2 -> Page3 of UIAbility1 and PageA -> PageB -> PageC of UIAbility2 in the figure below are two page stacks. + + **Figure 1** Page stack +![mission-record](figures/mission-record.png) + +- A page stack is formed as follows (Steps 2, 3, 5, and 6 are page redirection and managed by ArkUI): + 1. Touch the icon on the home screen. The [startAbility](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability) method is called to start UIAbility1, whose initial page is Page1. + + 2. Touch a button on Page1. The [Navigator](../reference/arkui-ts/ts-container-navigator.md) method is called to redirect you to Page2. + + 3. Touch a button on Page2. The [Navigator](../reference/arkui-ts/ts-container-navigator.md) method is called to redirect you to Page3. + + 4. Touch a button on Page3. The [startAbility](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartability) method is called to start UIAbility2, whose initial page is PageA. + + 5. Touch a button on PageA. The [Navigator](../reference/arkui-ts/ts-container-navigator.md) method is called to redirect you to PageB. + + 6. Touch a button on PageB. The [Navigator](../reference/arkui-ts/ts-container-navigator.md) method is called to redirect you to PageC. + +- The page stack return is as follows (Steps 1, 2, 4, and 5 are page redirection and managed by ArkUI): + 1. Touch the **Back** button on PageC of UIAbility2 to return to PageB. + + 2. Touch the **Back** button on PageB of UIAbility2 to return to PageA. + + 3. Touch the **Back** button on PageA of UIAbility2 to return to Page3 of UIAbility1. + + 4. Touch the **Back** button on Page3 of UIAbility1 to return to Page2. + + 5. Touch the **Back** button on Page2 of UIAbility1 to return to Page1 of UIAbility1. + + 6. Touch the **Back** button on Page1 of UIAbility1 to return to the home screen. + + +## MissionList + +As described above, you can keep touching the **Back** button on the page of Ability2 to return to a page of Ability1. The MissionList records the startup relationship between missions. If Ability1 starts Ability2 through **startAbility()**, a MissionList is formed: Ability1 -> Ability2. Therefore, when you touch the **Back** button on the initial page of Ability2, a page of Ability1 is displayed. + +The mission startup relationship recorded by the MissionList may be broken in the following cases: + +- A user moves a mission in the middle of the MissionList to the foreground. + ![mission-chain1](figures/mission-chain1.png) + +- A user deletes a mission in the MissionList. + ![mission-chain2](figures/mission-chain2.png) + +- A UIAbility singleton is repeatedly started by different missions. For example, AbilityB in the figure below is a singleton. + ![mission-chain3](figures/mission-chain3.png) diff --git a/en/application-dev/application-models/pageability-configuration.md b/en/application-dev/application-models/pageability-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..c11e7b17554844d21e024228bbec51e621d6383d --- /dev/null +++ b/en/application-dev/application-models/pageability-configuration.md @@ -0,0 +1,12 @@ +# PageAbility Component Configuration + + +The PageAbility is configured in **abilities** under **module** in the **config.json** file. The **icon** field indicates the index of the ability icon resource file, and the **label** field indicates the ability name presented to users, and the **skills** field indicates the type of Want that is acceptable to the ability. + +**Table 1** PageAbility configuration items + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)| +| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| skills | Types of the Want that can be accepted by the ability.| Object array| Yes (initial value: left empty)| diff --git a/en/application-dev/application-models/pageability-launch-type.md b/en/application-dev/application-models/pageability-launch-type.md new file mode 100644 index 0000000000000000000000000000000000000000..5241a7cabefbf3e68e6a3f413b8892ef5f6ff8d3 --- /dev/null +++ b/en/application-dev/application-models/pageability-launch-type.md @@ -0,0 +1,39 @@ +# PageAbility Launch Type + + +Depending on the launch type, the action performed when the PageAbility starts differs, as described in the table below. + +**Table 1** PageAbility launch types + +| Launch Type| Description| +| -------- | -------- | +| singleton | Each time **startAbility()** is called, if an ability instance of this type already exists in the application process, the instance is reused. There is only one ability instance of this type in **Recents**.
A typical scenario is as follows: When a user opens a video playback application and watches a video, returns to the home screen, and opens the video playback application again, the video that the user watched before returning to the home screen is still played.| +| standard | Default type. Each time **startAbility()** is called, a new ability instance is created in the application process. Multiple ability instances of this type are displayed in **Recents**.
A typical scenario is as follows: When a user opens a document application and touches **New**, a new document task is created. Multiple new document missions are displayed in **Recents**.| + + +You can set **launchType** in the **config.json** file to configure the launch type. The sample code is as follows: + +```json +{ + "module": { + // ... + "abilities": [ + { + // singleton mode. + // standard mode. + "launchType": "standard", + // ... + } + ] + } +} +``` + + +When the PageAbility is started for the first time (either in standard or singleton mode), the [PageAbility lifecycle callbacks](pageability-lifecycle.md#table13118194914476) are triggered. When it is not started for the first time in singleton mode, the **onNewWant()** callback (as described in the table below) is triggered, but the **onCreate()** callback is not. + +**Table 2** Callbacks specific to the singleton mode + +| API| Description| +| -------- | -------- | +| onNewWant(want: Want) | **onNewWant()** is triggered when the PageAbility is not started for the first time in singleton mode. You can obtain Want from this callback and perform further processing based on Want. For example, in the singleton PageAbility migration scenario, you can specify a page to start the PageAbility.| diff --git a/en/application-dev/application-models/pageability-lifecycle.md b/en/application-dev/application-models/pageability-lifecycle.md new file mode 100644 index 0000000000000000000000000000000000000000..3608346ec5403735a79fdf9a01478be9b86745d9 --- /dev/null +++ b/en/application-dev/application-models/pageability-lifecycle.md @@ -0,0 +1,45 @@ +# PageAbility Lifecycle + + +The PageAbility lifecycle defines all states of a PageAbility, such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**. The figure below shows the lifecycle state transition. + +**Figure 1** PageAbility lifecycle + +![page-ability-lifecycle](figures/page-ability-lifecycle.png) + +**Table 1** PageAbility lifecycle states + +| State| Description| +| -------- | -------- | +| UNINITIALIZED | The PageAbility is not initialized. This is a temporary state, from which a PageAbility changes directly to the **INITIAL** state upon its creation.| +| INITIAL | The PageAbility is initialized but not running. The PageAbility enters the **INACTIVE** state after it is started.| +| INACTIVE | The PageAbility is visible but does not gain focus.| +| ACTIVE | The PageAbility runs in the foreground and has focus.| +| BACKGROUND | The PageAbility runs in the background. After being re-activated, the PageAbility enters the **ACTIVE** state. After being destroyed, it enters the **INITIAL** state.| + + +You can override the lifecycle callbacks (as described in the table below) in **app.js** or **app.ets**. + +**Table 2** PageAbility lifecycle callbacks + +| API| Description| +| -------- | -------- | +| onCreate() | Called when the ability is created for the first time. You can initialize the application in this callback.| +| onDestroy() | Called when the ability is destroyed. In this callback, you can make preparations for application exit, such as recycling resources and clearing the cache.| +| onActive() | Called when the ability is switched to the foreground and gains focus.| +| onInactive() | Called when the ability loses focus. An ability loses focus when it is about to enter the background state.| +| onShow() | Called when the ability is switched from the background to the foreground. In this case, the ability is visible to users.| +| onHide() | Called when the ability is switched from the foreground to the background. In this case, the ability is invisible to users.| + + +The following figure shows the relationship between lifecycle callbacks and lifecycle states of the PageAbility. + +Figure 2 Relationship between lifecycle callbacks and lifecycle states + +![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) + + +> **NOTE** +> +> - The PageAbility lifecycle callbacks are synchronous. +> - The **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks. diff --git a/en/application-dev/application-models/pageability-overview.md b/en/application-dev/application-models/pageability-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..00370ca29056fcb8d23e93de54a38b2003bc6941 --- /dev/null +++ b/en/application-dev/application-models/pageability-overview.md @@ -0,0 +1,7 @@ +# PageAbility Component Overview + + +PageAbility is an application component that has the UI and supports user interaction. + + +When you create a PageAbility in DevEco Studio, DevEco Studio automatically creates template code. The capabilities related to the PageAbility are implemented through the **featureAbility** class, and the lifecycle callbacks are implemented through the callbacks in **app.js** or **app.ets**. diff --git a/en/application-dev/application-models/pageability-switch.md b/en/application-dev/application-models/pageability-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..1953c02c8067a38d1633ae9eb9f768dc60a87e0f --- /dev/null +++ b/en/application-dev/application-models/pageability-switch.md @@ -0,0 +1,56 @@ +# PageAbility Switching + + +The PageAbility component in the FA model corresponds to the UIAbility component in the stage model. To switch a PageAbility to a UIAbility, perform the following operations: + + +1. [Create a UIAbility](uiability-usage.md) in the stage model. + +2. Migrate the PageAbility code to the UIAbility. + +The PageAbility lifecycle is basically the same as the UIAbility lifecycle. The table below describes the details. + + | PageAbility| UIAbility| Mapping Description| + | -------- | -------- | -------- | + | onCreate(): void| onCreate(want: Want, param: AbilityConstant.LaunchParam): void | The two methods have the same meaning and invoking time. In the stage model, parameters are added to the callback so that you can obtain startup-related data during creation.| + | NA | onWindowStageCreate(windowStage: window.WindowStage): void| This method is available only in the stage model. The callback is invoked when a window is created.| + | onActive(): void | on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;
WindowStageEventType.ACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| + | onShow(): void | onForeground(): void | The two methods have the same meaning, invoking time, and parameters.| + | onNewWant(want: Want): void| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void| The two methods have the same meaning and invoking time. In the stage model, the **LaunchParam** parameter is added to notify the application of the startup cause.| + | onInactive(): void| on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void;
WindowStageEventType.INACTIVE | The two methods have the same meaning and invoking time. In the stage model, this method is moved to the window object.| + | onHide(): void | onBackground(): void | The two methods have the same meaning, invoking time, and parameters.| + | NA | onWindowStageDestroy(): void | This method is available only in the stage model. The callback is invoked when a window is destroyed.| +| onDestroy(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.| + +![pageability-switch](figures/pageability-switch.png) + +3. Adjust the migrated code, since the methods of loading pages are different. + + - In the FA model, you can configure the page to be loaded by setting page information in **config.json**. + - In the stage model, you must call **windowStage.loadContent** in the **onWindowStageCreate** callback to load a page. + + For example, to load the **pages/Index** page after the ability is started, use the following code in the **config.json** file in the FA model: + + + ```json + "pages" : [ + "pages/Index" + ] + ``` + + In the stage model, implement the following method in **MainAbility**: + + + ```ts + import Window from '@ohos.window' + + onWindowStageCreate(windowStage: Window.WindowStage) { + // Main window is created. Set a main page for this ability. + windowStage.loadContent('pages/Index', (err, data) => { + if (err.code) { + console.error("loadContent failed") + return; + } + }); + } + ``` diff --git a/en/application-dev/application-models/particleability-switch.md b/en/application-dev/application-models/particleability-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..21ecd96c9a24f1328c20da14abf5cc8f8d079b95 --- /dev/null +++ b/en/application-dev/application-models/particleability-switch.md @@ -0,0 +1,12 @@ +# particleAbility Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| [startAbility(parameter: StartAbilityParameter, callback: AsyncCallback<number>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartability)
[startAbility(parameter: StartAbilityParameter): Promise<number>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartability-1) | application\ServiceExtensionContext.d.ts | [startAbility(want: Want, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability)
[startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-2)
[startAbility(want: Want, options?: StartOptions): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-1)
[startServiceExtensionAbility(want: Want, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartserviceextensionability)
[startServiceExtensionAbility(want: Want): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartserviceextensionability-1) | +| [terminateSelf(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityterminateself)
[terminateSelf(): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityterminateself-1) | application\ServiceExtensionContext.d.ts | [terminateSelf(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself)
[terminateSelf(): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself-1) | +| [connectAbility(request: Want, options:ConnectOptions ): number;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityconnectability) | application\ServiceExtensionContext.d.ts | [connectAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability)
[connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability) | +| [disconnectAbility(connection: number, callback:AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitydisconnectability)
[disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitydisconnectability-1) | application\ServiceExtensionContext.d.ts | [disconnectAbility(connection: number, callback:AsyncCallback<void>): void; ](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability)
[disconnectAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1)
[disconnectServiceExtensionAbility(connection: number, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability)
[disconnectServiceExtensionAbility(connection: number): Promise<void>;](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1) | +| [acquireDataAbilityHelper(uri: string): DataAbilityHelper;](../reference/apis/js-apis-ability-particleAbility.md#particleabilityacquiredataabilityhelper) | \@ohos.data.dataShare.d.ts
[\@ohos.data.fileAccess.d.ts | [createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper)
[createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper>;](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper-1)
[createFileAccessHelper(context: Context): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper-1)
[createFileAccessHelper(context: Context, wants: Array<Want>): FileAccessHelper;](../reference/apis/js-apis-fileAccess.md#fileaccesscreatefileaccesshelper) | +| [startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning)
[startBackgroundRunning(id: number, request: NotificationRequest): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitystartbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningcallback)
[startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunningpromise) | +| [cancelBackgroundRunning(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning)
[cancelBackgroundRunning(): Promise<void>;](../reference/apis/js-apis-ability-particleAbility.md#particleabilitycancelbackgroundrunning-1) | \@ohos.resourceschedule.backgroundTaskManager.d.ts | [stopBackgroundRunning(context: Context, callback: AsyncCallback): void;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningcallback)
[stopBackgroundRunning(context: Context): Promise<void>;](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunningpromise) | diff --git a/en/application-dev/application-models/process-model-fa.md b/en/application-dev/application-models/process-model-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..699643031121521fbf95d26a949df906fa175a18 --- /dev/null +++ b/en/application-dev/application-models/process-model-fa.md @@ -0,0 +1,22 @@ +# Process Model (FA Model) + + +The OpenHarmony process model is shown below. + + +- All PageAbility, ServiceAbility, DataAbility, and FormAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure. + +- WebView has an independent rendering process, which is **Render process** in yellow in the figure. + + **Figure 1** Process model + + ![process-model-fa](figures/process-model-fa.png) + + +OpenHarmony provides two inter-process communication (IPC) mechanisms. + + +- [Common Events](common-event-fa.md): This mechanism is used in one-to-many communication scenarios. Multiple subscribers may receive events at the same time. + +- [Background Services](rpc.md): This mechanism is implemented through [ServiceAbility](serviceability-overview.md). + diff --git a/en/application-dev/application-models/process-model-stage.md b/en/application-dev/application-models/process-model-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..bbfa0602aecb127c5e484f0ebbdcb166f81310f7 --- /dev/null +++ b/en/application-dev/application-models/process-model-stage.md @@ -0,0 +1,31 @@ +# Process Model (Stage Model) + + +The OpenHarmony process model is shown below. + + +- All UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure. + +- The ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, which is **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure. + +- WebView has an independent rendering process, which is **Render process** in yellow in the figure. + + **Figure 1** Process model +![process-model](figures/process-model.png) + +> NOTE +> +> You can create ServiceExtensionAbility and DataShareExtensionAbility only for system applications. + +A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility in the HAP run in the custom process. Different HAPs run in different processes by configuring different process names. + +**Figure 2** Multi-process +![multi-process](figures/multi-process.png) + + +OpenHarmony provides two inter-process communication (IPC) mechanisms. + + +- [Common Events](common-event-overview.md): This mechanism is used in one-to-many communication scenarios. Multiple subscribers may receive events at the same time. + +- [Background Services](background-services.md): This mechanism is implemented through [ServiceExtensionAbility](serviceextensionability.md). diff --git a/en/application-dev/application-models/public_sys-resources/icon-caution.gif b/en/application-dev/application-models/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/application-models/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/application-models/public_sys-resources/icon-danger.gif b/en/application-dev/application-models/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/application-models/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/application-models/public_sys-resources/icon-note.gif b/en/application-dev/application-models/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/application-models/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/application-models/public_sys-resources/icon-notice.gif b/en/application-dev/application-models/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/application-models/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/application-models/public_sys-resources/icon-tip.gif b/en/application-dev/application-models/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/application-models/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/application-models/public_sys-resources/icon-warning.gif b/en/application-dev/application-models/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/application-models/public_sys-resources/icon-warning.gif differ diff --git a/en/application-dev/application-models/redirection-rules.md b/en/application-dev/application-models/redirection-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..d7456653640942bca333a28f7f6d5262ec4d63f3 --- /dev/null +++ b/en/application-dev/application-models/redirection-rules.md @@ -0,0 +1,36 @@ +# Redirection Rules + + +Generally, UI redirection within an application is triggered by users. However, an application can call **startAbility()** to implement UI redirection. + + +The PageAbility has a UI. It can use **startAbility()** to start an ability that has a UI and is visible to users. + + +The **visible** field under **abilities** in the **config.json** file specifies whether an ability can be started by other application components. + +**Table 1** Description of visible + +| Name| Description| Initial Value Allowed| +| -------- | -------- | -------- | +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by any application.
**false**: The ability can be called only by other components of the same application.| Yes (initial value: **false**)| + + +To enable an ability to be called by any application, configure the **config.json** file as follows: + +```ts +{ + "module": { + // ... + "abilities": [ + { + "visible": "true", + // ... + } + ] + } +} +``` + + +If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant. diff --git a/en/application-dev/application-models/request-permissions.md b/en/application-dev/application-models/request-permissions.md new file mode 100644 index 0000000000000000000000000000000000000000..670860d87dbb56adceb02f4ca350c24b61260d30 --- /dev/null +++ b/en/application-dev/application-models/request-permissions.md @@ -0,0 +1,45 @@ +# Requesting Permissions + + +If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from users. + + +During application development, you must declare the required permission in the **config.json** file and call **requestPermissionsFromUser** to request the permission from users in the form of a dialog box. + + +To declare a permission in **config.json**, add **reqPermissions** under **module** and list the permission. + + +For example, to declare the permission to access the calendar, request the **ohos.permission.READ_CALENDAR** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + + +The sample code in the **config.json** file is as follows: + +```json +{ + "module": { + // ... + "reqPermissions": [ + { + "name": "ohos.permission.READ_CALENDAR" + // ... + } + ] + } +} +``` + + +Request the permission from uses in the form of a dialog box: + +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +let context = featureAbility.getContext(); +let permissions: Array = ['ohos.permission.READ_CALENDAR'] +context.requestPermissionsFromUser(permissions, 1).then((data) => { + console.info("Succeed to request permission from user with data: " + JSON.stringify(data)) +}).catch((error) => { + console.info("Failed to request permission from user with error: " + JSON.stringify(error)) +}) +``` diff --git a/en/application-dev/application-models/request-switch.md b/en/application-dev/application-models/request-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..5c9e2f49d48aaba203a6207de37992823ab5ae97 --- /dev/null +++ b/en/application-dev/application-models/request-switch.md @@ -0,0 +1,7 @@ +# request Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| [download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void;](../reference/apis//js-apis-request.md#requestdownload-1)
[download(config: DownloadConfig): Promise<DownloadTask>;](../reference/apis/js-apis-request.md#requestdownload) | \@ohos.request.d.ts | [downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void;](../reference/apis/js-apis-request.md#requestdownloadfile9-1)
[downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask>;](../reference/apis/js-apis-request.md#requestdownloadfile9) | +| [upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void;](../reference/apis/js-apis-request.md#requestupload-1)
[upload(config: UploadConfig): Promise<UploadTask>;](../reference/apis/js-apis-request.md#requestupload) | \@ohos.request.d.ts | [uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void;](../reference/apis/js-apis-request.md#requestuploadfile9-1)
[uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask>;](../reference/apis/js-apis-request.md#requestuploadfile9) | diff --git a/en/application-dev/application-models/resourcemanager-switch.md b/en/application-dev/application-models/resourcemanager-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..34eedb16597e30c76ccaed2c01a3b4c7206c0dfd --- /dev/null +++ b/en/application-dev/application-models/resourcemanager-switch.md @@ -0,0 +1,6 @@ +# resourceManager Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding Field in the Stage Model| +| -------- | -------- | -------- | +| [getResourceManager(callback: AsyncCallback<ResourceManager>): void;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager)
[getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManager>): void;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-1)
[getResourceManager(): Promise<ResourceManager>;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-2)
[getResourceManager(bundleName: string): Promise<ResourceManager>;](../reference/apis/js-apis-resource-manager.md#resourcemanagergetresourcemanager-3) | application\Context.d.ts | [resourceManager: resmgr.ResourceManager;](../reference/apis/js-apis-inner-application-context.md#attributes)| diff --git a/en/application-dev/application-models/rpc.md b/en/application-dev/application-models/rpc.md new file mode 100644 index 0000000000000000000000000000000000000000..69fd10c315c9f3ec007358dad86fef71c4363d53 --- /dev/null +++ b/en/application-dev/application-models/rpc.md @@ -0,0 +1,4 @@ +# Background Services (FA Model) + + +For details, see [Background Services](background-services.md) in the stage model. diff --git a/en/application-dev/application-models/serviceability-configuration.md b/en/application-dev/application-models/serviceability-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..2c8e009a10937140e013d030cf21a1167b1fd3e8 --- /dev/null +++ b/en/application-dev/application-models/serviceability-configuration.md @@ -0,0 +1,16 @@ +# ServiceAbility Component Configuration + + +Similar to a PageAbility, a ServiceAbility is configured in **abilities** under **module** of the **config.json** file. The difference between a ServiceAbility and PageAbility lies in the **type** and **backgroundModes** fields. + + + **Table 1** ServiceAbility configuration items + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| type | Type of the ability. The value **service** indicates that the ability is developed based on the Service template.| String| No| +| backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This field applies only to the ability using the Service template. The value can be:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.
**audioPlayback**: audio playback service.
**audioRecording**: audio recording service.
**pictureInPicture**: picture in picture (PiP) and small-window video playback services.
**voip**: voice/video call and VoIP services.
**location**: location and navigation services.
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services.
**wifiInteraction**: WLAN scanning, connection, and transmission services.
**screenFetch**: screen recording and screenshot services.
**multiDeviceConnection**: multi-device interconnection service.| String array| Yes (initial value: left empty)| + + +For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md). + diff --git a/en/application-dev/application-models/serviceability-lifecycle.md b/en/application-dev/application-models/serviceability-lifecycle.md new file mode 100644 index 0000000000000000000000000000000000000000..cc541c77ea0bec412eee09b7b7b3fe4e7e1008d0 --- /dev/null +++ b/en/application-dev/application-models/serviceability-lifecycle.md @@ -0,0 +1,15 @@ +# ServiceAbility Lifecycle + + +You can override lifecycle callbacks (described in the table below) for ServiceAbility based on service requirements. + + + **Table 1** ServiceAbility lifecycle callbacks + +| API| Description| +| -------- | -------- | +| onStart(): void | Called to initialize a ServiceAbility when the ServiceAbility is being created. This callback is invoked only once in the entire lifecycle of a ServiceAbility.| +| onCommand(want: Want, startId: number): void | Called every time a ServiceAbility is started on the client. You can collect calling statistics and perform initialization operations in this callback.| +| onConnect(want: Want): rpc.RemoteObject | Called when the ServiceAbility is connected.| +| onDisconnect(want: Want): void | Called when the connection to the ServiceAbility is disconnected.| +| onStop(): void | Called when the ServiceAbility is being destroyed. You should override this callback for your ServiceAbility to clear its resources, such as threads and registered listeners.| diff --git a/en/application-dev/application-models/serviceability-overview.md b/en/application-dev/application-models/serviceability-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..ba57633f7bd489dd75ddba4cf8d7e829fa97dae4 --- /dev/null +++ b/en/application-dev/application-models/serviceability-overview.md @@ -0,0 +1,4 @@ +# ServiceAbility Component Overview + + +An ability using the Service template (ServiceAbility for short) is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. A ServiceAbility can be started by another application or a PageAbility. It remains to run in the background even after the user switches to another application. diff --git a/en/application-dev/application-models/serviceability-switch.md b/en/application-dev/application-models/serviceability-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..9752a4a11be4982ab65b4fc17262a39b6190b00b --- /dev/null +++ b/en/application-dev/application-models/serviceability-switch.md @@ -0,0 +1,35 @@ +# ServiceAbility Switching + + +The ServiceAbility component in the FA model corresponds to the ServiceExtensionAbility component in the stage model. The ServiceExtensionAbility class provides system APIs. Only system applications can create ServiceExtensionAbility instances. Therefore, ServiceAbility switching adopts different policies for system applications and third-party applications. + + +## Switching a ServiceAbility of a System Application + +The procedure for switching a ServiceAbility of a system application is similar to the procedure of PageAbility switching. + +1. [Create a ServiceExtensionAbility](serviceextensionability.md) in the stage model. + +2. Migrate the ServiceAbility code to the ServiceExtensionAbility. + +The table below describes the lifecycle comparison of the ServiceAbility and ServiceExtensionAbility. + + | ServiceAbility| ServiceExtensionAbility| Comparison Description| + | -------- | -------- | -------- | + | onStart(): void | onCreate(want: Want): void | The two methods have the same invoking time. In the stage model, the **want** parameter is added so that you can obtain parameters during creation.| + | onCommand(want: Want, startId: number): void | onRequest(want: Want, startId: number): void | The two methods have the same meaning, invoking time, and parameters.| + | onConnect(want: Want): rpc.RemoteObject | onConnect(want: Want): rpc.RemoteObject | The two methods have the same meaning, invoking time, and parameters.| + | onDisconnect(want: Want): void | onDisconnect(want: Want): void | The two methods have the same meaning, invoking time, and parameters.| + | onReconnect(want: Want): void| onReconnect(want: Want): void| The two methods have the same meaning, invoking time, and parameters.| + | onStop(): void | onDestroy(): void | The two methods have the same meaning, invoking time, and parameters.| + + +## Switching a ServiceAbility of a Third-Party Application + +In the stage model, third-party applications cannot provide services for other third-party applications. You can select a switching solution based on your service requirements. + +| Service Type| Switching Solution| +| -------- | -------- | +| Providing services for other third-party applications| Match a scenario-specific [ExtensionAbility](extensionability-overview.md).| +| In-application: providing public use when it is running in the foreground| Extract the component code as a common module for other components to use.| +| In-application: continuing running when it switches to the background| Switch the service to [a background service](serviceextensionability.md).| diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..c4ffdbd980fff4ce568115f92af884da06739ad2 --- /dev/null +++ b/en/application-dev/application-models/serviceextensionability.md @@ -0,0 +1,295 @@ +# 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. + + +ServiceExtensionAbility can be started or connected by other application components to process transactions in the background based on the request of the caller. System applications can call the [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability) method to start background services or call the [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability) method to connect to background services. Third-party applications can call only **connectServiceExtensionAbility()** to connect to background services. The differences between starting and connecting to background services are as follows: + + +- In the case that AbilityA starts ServiceB, they are weakly associated. After AbilityA exits, ServiceB can still exist. + +- In the case that AbilityA connects to ServiceB, they are strongly associated. After AbilityA exits, ServiceB also exits. + + +Each type of ExtensionAbility has its own context. ServiceExtensionAbility has [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md). In this document, the started ServiceExtensionAbility component is called the server, and the component that starts ServiceExtensionAbility is called the client. + + +This topic describes how to use ServiceExtensionAbility in the following scenarios: + + +- [Implementing a Background Service](#implementing-a-background-service) + +- [Starting a Background Service](#starting-a-background-service) + +- [Connecting to a Background Service](#connecting-to-a-background-service) + + +> **NOTE** +> - OpenHarmony does not support third-party applications in implementing ServiceExtensionAbility. If you want to implement transaction processing in the background, use background tasks. For details, see [Background Task](../task-management/background-task-overview.md). +> +> - UIAbility of a third-party application can connect to ServiceExtensionAbility provided by the system through the context. +> +> - Third-party applications can connect to ServiceExtensionAbility provided by the system only when they gain focus in the foreground. + + +## Implementing a Background Service + +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. + + **Figure 1** ServiceExtensionAbility lifecycle +![ServiceExtensionAbility-lifecycle](figures/ServiceExtensionAbility-lifecycle.png) + +- **onCreate** + + +This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. + + > **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. + +- **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. + +- **onDisconnect** + + +This callback is triggered when a component calls the **disconnectServiceExtensionAbility()** method to disconnect from the service. + +- **onDestroy** + + This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener. + + +## How to Develop + +To implement a background service, manually create a ServiceExtensionAbility component in DevEco Studio. The procedure is as follows: + +1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **serviceextability**. + +2. In the **serviceextability** directory, right-click and choose **New > TypeScript File** to create a file named **ServiceExtAbility.ts**. + +3. Open the **ServiceExtAbility.ts** file, import the [RPC module](../reference/apis/js-apis-rpc.md), and reload the **onRemoteMessageRequest()** method to receive messages from the client and return the processing result to the client. **REQUEST_VALUE** is used to verify the service request code sent by the client. + + ```ts + import rpc from '@ohos.rpc'; + + const REQUEST_CODE = 99; + + class StubTest extends rpc.RemoteObject { + constructor(des) { + super(des); + } + + // Receive a message from the client and return the processing result to the client. + onRemoteMessageRequest(code, data, reply, option) { + if (code === REQUEST_CODE) { + // Receive data from the client. + // If the client calls data.writeInt() multiple times to write multiple pieces of data, the server can call data.readInt() multiple times to receive all the data. + let optFir = data.readInt(); + let optSec = data.readInt(); + // The server returns the data processing result to the client. + // In the example, the server receives two pieces of data and returns the sum of the two pieces of data to the client. + reply.writeInt(optFir + optSec); + } + return true; + } + + // Send messages to the client in synchronous or asynchronous mode. + sendRequest(code, data, reply, options) { + return null; + } + } + ``` + +4. In the **ServiceExtAbility.ts** file, add the dependency package for importing ServiceExtensionAbility. Customize a class that inherits from ServiceExtensionAbility and add the required lifecycle callbacks. + + ```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + import rpc from '@ohos.rpc'; + + const TAG: string = "[Example].[Entry].[ServiceExtAbility]"; + const REQUEST_CODE = 99; + + class StubTest extends rpc.RemoteObject { + // ... + } + + export default class ServiceExtAbility extends ServiceExtensionAbility { + onCreate(want) { + console.info(TAG, `onCreate, want: ${want.abilityName}`); + } + + onRequest(want, startId) { + console.info(TAG, `onRequest, want: ${want.abilityName}`); + } + + onConnect(want) { + console.info(TAG, `onConnect, want: ${want.abilityName}`); + return new StubTest("test"); + } + + onDisconnect(want) { + console.info(TAG, `onDisconnect, want: ${want.abilityName}`); + } + + onDestroy() { + console.info(TAG, `onDestroy`); + } + } + ``` + +5. Register ServiceExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"service"** and **srcEntrance** to the code path of the ExtensionAbility component. + + ```json + { + "module": { + // ... + "extensionAbilities": [ + { + "name": "ServiceExtAbility", + "icon": "$media:icon", + "description": "service", + "type": "service", + "visible": true, + "srcEntrance": "./ets/serviceextability/ServiceExtAbility.ts" + } + ] + } + } + ``` + + +## Starting a Background Service + +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. + +> **NOTE** +> +> [startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability), [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability), and [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) of ServiceExtensionContext are system APIs and cannot be called by third-party applications. + +1. Start a new ServiceExtensionAbility in a system application. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). + + ```ts + let want = { + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" + }; + this.context.startServiceExtensionAbility(want).then(() => { + console.info('startServiceExtensionAbility success'); + }).catch((error) => { + console.info('startServiceExtensionAbility failed'); + }) + ``` + +2. Stop ServiceExtensionAbility in the system application. + + ```ts + let want = { + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" + }; + this.context.stopServiceExtensionAbility(want).then(() => { + console.info('stopServiceExtensionAbility success'); + }).catch((error) => { + console.info('stopServiceExtensionAbility failed'); + }) + ``` + +3. ServiceExtensionAbility stops itself. + + ```ts + // this is the current ServiceExtensionAbility component. + this.context.terminateSelf().then(() => { + console.info('terminateSelf success'); + }).catch((error) => { + console.info('terminateSelf failed'); + }) + ``` + + +> **NOTE** +> +> Background services can run in the background for a long time. To minimize resource usage, destroy it in time when a background service finishes the task of the requester. A background service can be stopped in either of the following ways: +> +> - The background service calls the [terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) method to automatically stop itself. +> +> - Another component calls the [stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability) method to stop the background service. +> +> After either method is called, the system destroys the background service. + + +## Connecting to a Background Service + +Either a system application or a third-party application can connect to a service (service specified in the **Want** object) through [connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability). The [onConnect()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonconnect) callback is invoked, and the **Want** object passed by the caller is received through the callback. In this way, a persistent connection is established. + +The ServiceExtensionAbility component returns an IRemoteObject in the **onConnect()** callback. Through this IRemoteObject, you can define communication interfaces for RPC interaction between the client and server. Multiple clients can connect to the same background service at the same time. After a client finishes the interaction, it must call [disconnectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextdisconnectserviceextensionability) to disconnect from the service. If all clients connected to a background service are disconnected, the system destroys the service. + +- Call **connectServiceExtensionAbility()** to establish a connection to a background service. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). + + ```ts + import rpc from '@ohos.rpc'; + + const REQUEST_CODE = 99; + let want = { + "deviceId": "", + "bundleName": "com.example.myapplication", + "abilityName": "ServiceExtAbility" + }; + let options = { + onConnect(elementName, remote) { + console.info('onConnect callback'); + if (remote === null) { + console.info(`onConnect remote is null`); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(100); + data.writeInt(200); + + // @param code Indicates the service request code sent by the client. + // @param data Indicates the {@link MessageParcel} object sent by the client. + // @param reply Indicates the response message object sent by the remote service. + // @param options Specifies whether the operation is synchronous or asynchronous. + // + // @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. + remote.sendRequest(REQUEST_CODE, data, reply, option).then((ret) => { + let msg = reply.readInt(); + console.info(`sendRequest ret:${ret} msg:${msg}`); + }).catch((error) => { + console.info('sendRequest failed'); + }); + }, + onDisconnect(elementName) { + console.info('onDisconnect callback') + }, + onFailed(code) { + console.info('onFailed callback') + } + } + // The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection. + let connectionId = this.context.connectServiceExtensionAbility(want, options); + ``` + +- Use **disconnectServiceExtensionAbility()** to disconnect from the background service. + + ```ts + let connectionId = 1 // ID returned when the service is connected through connectServiceExtensionAbility. + this.context.disconnectServiceExtensionAbility(connectionId).then((data) => { + console.info('disconnectServiceExtensionAbility success'); + }).catch((error) => { + console.error('disconnectServiceExtensionAbility failed'); + }) + ``` + diff --git a/en/application-dev/application-models/stage-model-development-overview.md b/en/application-dev/application-models/stage-model-development-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6fbf06baa44d4c0f2196fa3c1b00a0761a71a161 --- /dev/null +++ b/en/application-dev/application-models/stage-model-development-overview.md @@ -0,0 +1,43 @@ +# Stage Model Development Overview + + +## Basic Concepts + +The following figure shows the basic concepts used in the stage model. + +**Figure 1** Concepts used in the stage model +![stage-concepts](figures/stage-concepts.png) + +- [UIAbility component](uiability-overview.md) and [ExtensionAbility component](extensionability-overview.md) + + The stage model provides two types of application components: UIAbility and ExtensionAbility. Both have specific classes and support object-oriented development. They are the specific implementation of the abstract ability concept on the stage model. They are also units scheduled by the Ability Manager Service (AMS), which schedules their lifecycles as well. + + - UIAbility has the UI and is mainly used for user interaction. For example, with UIAbility, the Gallery application can display images in the liquid layout. After a user selects an image, it uses a new UI to display the image details. The user can touch the **Back** button to return to the liquid layout. The lifecycle of the UIAbility component contains the creation, destruction, foreground, and background states. Display-related states are exposed through WindowStage events. + + - ExtensionAbility is oriented to specific scenarios. You cannot derive directly from ExtensionAbility. Instead, use the derived classes of ExtensionAbility for your scenarios, such as FormExtensionAbility for widget scenarios, InputMethodExtensionAbility for input method scenarios, and WorkSchedulerExtensionAbility for Work Scheduled task scenarios. For example, to enable a user to create an application widget on the home screen, you must derive FormExtensionAbility, implement the callback functions, and configure the capability in the configuration file. The derived class instances are created by developers and their lifecycles are managed by the system. In the stage model, you must use the derived classes of ExtensionAbility to develop custom services based on your service scenarios. +- [WindowStage](../windowmanager/application-window-stage.md) + + Each UIAbility class instance is bound to a WindowStage class instance, which functions as the window manager in the application process. The WindowStage class instance contains a main window. That is, UIAbility holds a main window through WindowStage, and this window provides an area for ArkUI to render. + +- [Context](application-context-stage.md) + + In the stage model, Context and its derived classes provide a variety of capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities. + +- [AbilityStage](abilitystage.md) + + Each HAP of the Entry or Feature type has an AbilityStage class instance during the runtime. When the code in the HAP is loaded to the process for the first time, the system creates an AbilityStage class instance first. Each UIAbility class defined in the HAP is associated with this class instance after instantiation. Through this class instance, you can obtain the runtime information of the UIAbility instances in the HAP. + + +## How to Develop + +During application development based on the stage model, the following tasks are involved in the application model. + +**Table 1** Stage model development process + +| Task| Introduction| Guide| +| -------- | -------- | -------- | +| Application component development| Use the UIAbility and ExtensionAbility components of the stage model to develop applications.| - [Application- or Component-Level Configuration](application-component-configuration-stage.md)
- [UIAbility Component](uiability-overview.md)
- [ExtensionAbility Component](extensionability-overview.md)
- [AbilityStage Container Component](abilitystage.md)
- [Context](application-context-stage.md)
- [Component Startup Rules](component-startup-rules.md)| +| Inter-process communication (IPC)| Learn the process model and common IPC modes of the stage model.| - [Common Events](common-event-overview.md)
- [Background Services](background-services.md)| +| Inter-thread communication| Learn the thread model and common inter-thread communication modes of the stage model.| - [Emitter](itc-with-emitter.md)
- [Worker](itc-with-worker.md)| +| Mission management| Learn the basic concepts and typical scenarios of mission management in the stage model.| - [Mission Management Scenarios](mission-management-overview.md)
- [Mission Management and Launch Type](mission-management-launch-type.md)
- [Page Stack and Mission List](page-mission-stack.md)| +| Application configuration file| Learn the requirements for developing application configuration files in the stage model.| [Application Configuration File](config-file-stage.md)| diff --git a/en/application-dev/application-models/start-dataability.md b/en/application-dev/application-models/start-dataability.md new file mode 100644 index 0000000000000000000000000000000000000000..786a14f91007672e395ed5b754fbaeccb55b3770 --- /dev/null +++ b/en/application-dev/application-models/start-dataability.md @@ -0,0 +1,12 @@ +# Starting a DataAbility + + +When a DataAbility is started, a **DataAbilityHelper** object is obtained. The sample code for starting a DataAbility is as follows: + +```ts +// Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), three slashes in total. +import featureAbility from '@ohos.ability.featureAbility' + +let urivar = "dataability:///com.ix.DataAbility" +let DAHelper = featureAbility.acquireDataAbilityHelper(urivar); +``` diff --git a/en/application-dev/application-models/start-local-pageability.md b/en/application-dev/application-models/start-local-pageability.md new file mode 100644 index 0000000000000000000000000000000000000000..425566ab88d66aecd4690c569dd84d94c46cd568 --- /dev/null +++ b/en/application-dev/application-models/start-local-pageability.md @@ -0,0 +1,35 @@ +# Starting a Local PageAbility + + +The capabilities related to the PageAbility are provided through the **featureAbility** class. For example, **startAbility()** in **featureAbility** is used to the PageAbility. + +**Table 1** featureAbility APIs + +| API| Description| +| -------- | -------- | +| startAbility(parameter: StartAbilityParameter) | Starts an ability.| +| startAbilityForResult(parameter: StartAbilityParameter) | Starts an ability and returns the execution result when the ability is terminated.| + + +The following code snippet shows how to explicitly start a PageAbility through **startAbility()**. The parameters passed in for starting an ability include **want**. For details about the **want** parameter as well as implicit startup and explicit startup, see [Want](want-fa.md). + +```ts +import featureAbility from '@ohos.ability.featureAbility' +(async () => { + try { + console.info('Begin to start ability') + let param = { + want: { + bundleName: "com.example.myapplication", + moduleName: "entry", + abilityName: "com.example.myapplication.EntryAbility" + } + } + await featureAbility.startAbility(param) + console.info(`Start ability succeed`) + } + catch (error) { + console.error('Start ability failed with ' + error) + } +})() +``` diff --git a/en/application-dev/application-models/start-page.md b/en/application-dev/application-models/start-page.md new file mode 100644 index 0000000000000000000000000000000000000000..58966d93cba037eaad141caaed0feaaaa672cde1 --- /dev/null +++ b/en/application-dev/application-models/start-page.md @@ -0,0 +1,142 @@ +# Starting a Specified Page + + +When the launch type of a PageAbility is set to **singleton** (default), the **onNewWant()** callback is triggered if the PageAbility is not started for the first time. For details about the launch type, see [PageAbility Launch Type](pageability-launch-type.md). In this case, you can use the **want** parameter to transfer startup information. For example, if you want to start a PageAbility with a specified page, pass the pages information in **parameters** of **want**. + + +In **app.ets** or **page** of the caller PageAbility, use **startAbility()** to start the PageAbility again, with the page information passed in the **uri** parameter in **want**. + +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +async function restartAbility() { + let wantInfo = { + bundleName: "com.sample.MyApplication", + abilityName: "EntryAbility", + parameters: { + page: "pages/second" + } + }; + featureAbility.startAbility({ + want: wantInfo + }).then((data) => { + console.info('restartAbility success.'); + }); +} +``` + + +Obtain the **want** parameter that contains the page information from the **onNewWant()** callback of the target PageAbility. + +```ts +export default { + onNewWant(want) { + globalThis.newWant = want + } +} +``` + + +Obtain the **want** parameter that contains the page information from the custom component of the target PageAbility and process the route based on the URI. + +```ts +import router from '@ohos.router' +@Entry +@Component +struct Index { + @State message: string = 'Router Page' + newWant = undefined + onPageShow() { + console.info('Index onPageShow') + let newWant = globalThis.newWant + if (newWant.hasOwnProperty("page")) { + router.push({ url: newWant.page }); + globalThis.newWant = undefined + } + } + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + + +When the launch type of a PageAbility is set to **standard** or when the PageAbility with the launch type set to **singleton** is started for the first time, you can use the **parameters** parameter in **want** to transfer the pages information and use the **startAbility()** method to start the PageAbility. For details about the launch type, see [PageAbility Launch Type](pageability-launch-type.md). The target PageAbility can use the **featureAbility.getWant()** method in **onCreate** to obtain the **want** parameter, and then call **router.push** to start a specified page. + + +When a user touches the button on the page of the caller PageAbility, the **startAbility()** method is called to start the target PageAbility. The **want** parameter in **startAbility()** carries the specified page information. + +```ts +import featureAbility from '@ohos.ability.featureAbility' +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + // ... + Button("startAbility") + .onClick(() => { + featureAbility.startAbility({ + want: { + bundleName: "com.exm.myapplication", + abilityName: "com.exm.myapplication.EntryAbility", + parameters: { page: "pages/page1" } + } + }).then((data) => { + console.info("startAbility finish"); + }).catch((err) => { + console.info("startAbility failed errcode:" + err.code) + }) + }) + // ... + Button("page2") + .onClick(() => { + featureAbility.startAbility({ + want: { + bundleName: "com.exm.myapplication", + abilityName: "com.exm.myapplication.EntryAbility", + parameters: { page: "pages/page2" } + } + }).then((data) => { + console.info("startAbility finish"); + }).catch((err) => { + console.info("startAbility failed errcode:" + err.code) + }) + }) + // ... + } +} +``` + + +In the **onCreate()** callback of the target PageAbility, use the **featureAbility.getWant()** method to obtain the **want** parameter, parse the parameter, and start the specified page. + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import router from '@ohos.router'; + +export default { + onCreate() { + featureAbility.getWant().then((want) => { + if (want.parameters.page) { + router.push({ + url: want.parameters.page + }) + } + }) + }, + onDestroy() { + // ... + }, +} +``` diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..9d1b7ed27f6780ce56d1e90b3be5d196cf3b1187 --- /dev/null +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -0,0 +1,122 @@ +# Starting a PageAbility from the Stage Model + + +This topic describes how the two application components of the stage model start the PageAbility component of the FA model. + + +## UIAbility Starting a PageAbility + +A UIAbility starts a PageAbility in the same way as it starts another UIAbility. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.info("EntryAbility onCreate") + } + onDestroy() { + console.info("EntryAbility onDestroy") + } + onWindowStageCreate(windowStage) { + console.info("EntryAbility onWindowStageCreate") + windowStage.loadContent('pages/Index', (err, data) => { + // ... + }); + let want = { + bundleName: "com.ohos.fa", + abilityName: "EntryAbility", + }; + this.context.startAbility(want).then(() => { + console.info('Start Ability successfully.'); + }).catch((error) => { + console.error("Ability failed: " + JSON.stringify(error)); + }); + } + onWindowStageDestroy() { + console.info("EntryAbility onWindowStageDestroy") + } + onForeground() { + console.info("EntryAbility onForeground") + } + onBackground() { + console.info("EntryAbility onBackground") + } +} +``` + + +## UIAbility Accessing a PageAbility (startAbilityForResult) + +Different from **startAbility()**, **startAbilityForResult()** obtains the execution result when the PageAbility is destroyed. + +A UIAbility starts a PageAbility through **startAbilityForResult()** in the same way as it starts another UIAbility through **startAbilityForResult()**. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.info("EntryAbility onCreate") + } + onDestroy() { + console.info("EntryAbility onDestroy") + } + onWindowStageCreate(windowStage) { + console.info("EntryAbility onWindowStageCreate") + windowStage.loadContent('pages/Index', (err, data) => { + // ... + }); + let want = { + bundleName: "com.ohos.fa", + abilityName: "EntryAbility", + }; + this.context.startAbilityForResult(want).then((result) => { + console.info('Ability verify result: ' + JSON.stringify(result)); + }).catch((error) => { + console.error("Ability failed: " + JSON.stringify(error)); + }); + } + onWindowStageDestroy() { + console.info("EntryAbility onWindowStageDestroy") + } + onForeground() { + console.info("EntryAbility onForeground") + } + onBackground() { + console.info("EntryAbility onBackground") + } +} +``` + + +## ExtensionAbility Starting a PageAbility + +The following uses the ServiceExtensionAbility component as an example to describe how an ExtensionAbility starts a PageAbility. A ServiceExtensionAbility starts a PageAbility in the same way as it starts a UIAbility. + + +```ts +import Extension from '@ohos.app.ability.ServiceExtensionAbility' + +export default class ServiceExtension extends Extension { + onCreate(want) { + console.info("ServiceExtension onCreate") + } + onDestroy() { + console.info("ServiceExtension onDestroy") + } + onRequest(want, startId) { + console.info("ServiceExtension onRequest") + let wantFA = { + bundleName: "com.ohos.fa", + abilityName: "EntryAbility", + }; + this.context.startAbility(wantFA).then(() => { + console.info('Start Ability successfully.'); + }).catch((error) => { + console.error("Ability failed: " + JSON.stringify(error)); + }); + } +} +``` diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md new file mode 100644 index 0000000000000000000000000000000000000000..4e998a15d23d298bfdb402bd18ea0db2a9f819eb --- /dev/null +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -0,0 +1,136 @@ +# Starting a Remote PageAbility + + +This feature applies only to system applications. 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. + + +The **getTrustedDeviceListSync** method is available only for system applications. Therefore, non-system applications cannot obtain remote device information or start a remote ability. + +**Table 1** featureAbility APIs + +| API| Description| +| -------- | -------- | +| startAbility(parameter: StartAbilityParameter)| Starts an ability.| +| startAbilityForResult(parameter: StartAbilityParameter)| Starts an ability and returns the execution result when the ability is terminated.| + +**Table 2** deviceManager APIs + +| API| Description| +| -------- | -------- | +| getTrustedDeviceListSync(): Array<DeviceInfo> | Obtains all trusted devices synchronously.| + + +In the cross-device scenario, before starting a remote PageAbility, you must request the data synchronization permission. The related APIs are described in the table below. + +**Table 3** AtManager APIs + +| API| Description| +| -------- | -------- | +| checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> | Verifies whether a permission is granted to an application. This API uses a promise to return the result **GrantStatus**. You are advised to use **checkAccessToken** instead of **verifyAccessToken**, which is deprecated since API version 9.| + +**Table 4** context APIs + +| API| Description| +| -------- | -------- | +| requestPermissionsFromUser(permissions: Array<string>, requestCode: number, resultCallback: AsyncCallback< PermissionRequestResult>): void | Requests permissions from the system. This API uses an asynchronous callback to return the result. For details, see [API Reference](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7-1).| + + +The following sample code shows how to request the data synchronization permission from users: + +```ts +import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle.bundleManager'; +async function RequestPermission() { + console.info('RequestPermission begin'); + let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; + let bundleFlag = 0; + let tokenID = undefined; + let userID = 100; + let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); + tokenID = appInfo.accessTokenId; + let atManager = abilityAccessCtrl.createAtManager(); + let requestPermissions: Array = []; + for (let i = 0;i < array.length; i++) { + let result = await atManager.verifyAccessToken(tokenID, array[i]); + console.info("checkAccessToken result:" + JSON.stringify(result)); + if (result != abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + requestPermissions.push(array[i]); + } + } + console.info("requestPermissions:" + JSON.stringify(requestPermissions)); + if (requestPermissions.length == 0 || requestPermissions == []) { + return; + } + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(requestPermissions, 1, (error, data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data requestCode:" + data.requestCode); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); + console.info('RequestPermission end'); +} +``` + + +After obtaining the data synchronization permission, obtain the trusted device list for device selection. + + +The following sample code shows how to use **getTrustedDeviceListSync()** to obtain the trusted device list. + +```ts +import deviceManager from '@ohos.distributedHardware.deviceManager'; +let dmClass; +function getDeviceManager() { + deviceManager.createDeviceManager('ohos.example.distributedService', (error, dm) => { + if (error) { + console.info('create device manager failed with ' + error) + } + dmClass = dm; + }) +} +function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); + return; + } + console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } +} +``` + + +After a device is selected, call **startAbility()** to explicitly start the remote PageAbility. + + +The following sample code shows how to explicitly start a remote PageAbility through **startAbility()**. + +```ts +import featureAbility from '@ohos.ability.featureAbility'; +function onStartRemoteAbility() { + console.info('onStartRemoteAbility begin'); + let params; + let wantValue = { + bundleName: 'ohos.samples.etsDemo', + abilityName: 'ohos.samples.etsDemo.RemoteAbility', + deviceId: getRemoteDeviceId(), // getRemoteDeviceId is defined in the preceding sample code. + parameters: params + }; + console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); + }); + console.info('onStartRemoteAbility end'); +} +``` diff --git a/en/application-dev/application-models/start-serviceability.md b/en/application-dev/application-models/start-serviceability.md new file mode 100644 index 0000000000000000000000000000000000000000..f3b0f6aeabc8a3ea35c1f6c390ec53239730443c --- /dev/null +++ b/en/application-dev/application-models/start-serviceability.md @@ -0,0 +1,35 @@ +# Starting a ServiceAbility + + +A ServiceAbility is started in the same way other abilities. You can start a ServiceAbility by calling **featureAbility.startAbility()** in the PageAbility or calling **particleAbility.startAbility()** in another ServiceAbility. For details about the startup rules, see [Component Startup Rules](component-startup-rules.md). + + +The following example shows how to use **startAbility()** to start the ServiceAbility whose **bundleName** is **com.example.myapplication** and **abilityName** is **ServiceAbility** in a PageAbility. When starting the ServiceAbility, concatenate the **bundleName** string before **abilityName**. + +```ts +import featureAbility from '@ohos.ability.featureAbility' + +async function startServiceAbility() { + try { + console.info('Begin to start ability') + let param = { + want: { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.ServiceAbility" + } + } + await featureAbility.startAbility(param) + console.info(`Start ability succeed`) + } catch (error) { + console.error('Start ability failed with ' + error) + } +} +``` + + +In the preceding code, **startAbility()** 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. + +- If the ServiceAbility is running, the system directly calls **onCommand()** on the ServiceAbility. diff --git a/en/application-dev/application-models/start-uiability-from-fa.md b/en/application-dev/application-models/start-uiability-from-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..42d8e034cd6519643423bb289217d1aa140a18d4 --- /dev/null +++ b/en/application-dev/application-models/start-uiability-from-fa.md @@ -0,0 +1,71 @@ +# Starting a UIAbility from the FA Model + + +This topic describes how the three application components of the FA model start the UIAbility component of the stage model. + + +## PageAbility Starting a UIAbility + +A PageAbility starts a UIAbility in the same way as it starts another PageAbility. + +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +let parameter = { + "want": { + bundleName: "com.ohos.stage", + abilityName: "com.ohos.stage.EntryAbility" + } +}; +featureAbility.startAbility(parameter).then((code) => { + console.info('Ability verify code: ' + JSON.stringify(code)); +}).catch((error) => { + console.error("Ability failed: " + JSON.stringify(error)); +}); +``` + + +## PageAbility Accessing a UIAbility (startAbilityForResult) + +Different from **startAbility()**, **startAbilityForResult()** obtains the execution result when the UIAbility is destroyed. + +A PageAbility starts a UIAbility through **startAbilityForResult()** in the same way as it starts another PageAbility through **startAbilityForResult()**. + + +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +let parameter = { + "want": { + bundleName: "com.ohos.stage", + abilityName: "com.ohos.stage.EntryAbility" + } +}; +featureAbility.startAbilityForResult(parameter).then((result) => { + console.info('Ability verify result: ' + JSON.stringify(result)); +}).catch((error) => { + console.error("Ability failed: " + JSON.stringify(error)); +}); +``` + + +## ServiceAbility or DataAbility Starting a UIAbility + +A ServiceAbility or DataAbility starts a UIAbility in the same way as it starts a PageAbility. + + +```ts +import particleAbility from '@ohos.ability.particleAbility'; + +let parameter = { + "want": { + bundleName: "com.ohos.stage", + abilityName: "com.ohos.stage.EntryAbility" + } +}; +particleAbility.startAbility(parameter).then(() => { + console.info('Start Ability successfully.'); +}).catch((error) => { + console.error("Ability failed: " + JSON.stringify(error)); +}); +``` diff --git a/en/application-dev/application-models/stop-pageability.md b/en/application-dev/application-models/stop-pageability.md new file mode 100644 index 0000000000000000000000000000000000000000..7258a6b9e1311bcac602209c31710136a90dfb17 --- /dev/null +++ b/en/application-dev/application-models/stop-pageability.md @@ -0,0 +1,29 @@ +# Stopping a PageAbility + + +The **terminateSelf()** method in the **featureAbility** class is used to stop a PageAbility. + +**Table 1** featureAbility APIs + +| API| Description| +| -------- | -------- | +| terminateSelf() | Terminates this ability.| +| terminateSelfWithResult(parameter: AbilityResult) | Terminates this ability and returns the execution result.| + + +The following code snippet shows how to stop an ability. + +```ts +import featureAbility from '@ohos.ability.featureAbility' + +(async () => { + try { + console.info('Begin to terminateSelf') + await featureAbility.terminateSelf() + console.info('terminateSelf succeed') + } + catch (error) { + console.error('terminateSelf failed with ' + error) + } +})() +``` diff --git a/en/application-dev/application-models/storage-switch.md b/en/application-dev/application-models/storage-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..63486fe56fdf3605121711bee423066d9ac6e116 --- /dev/null +++ b/en/application-dev/application-models/storage-switch.md @@ -0,0 +1,13 @@ +# Storage Switching + + + | API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| GetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| +| SetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| +| ClearStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| +| DeleteStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| +| [static get(options: GetStorageOptions): void;](../reference/apis/js-apis-system-storage.md#storageget) | \@ohos.data.preferences.d.ts | [get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void;](../reference/apis/js-apis-data-preferences.md#get)
[get(key: string, defValue: ValueType): Promise<ValueType>;](../reference/apis/js-apis-data-preferences.md#get-1) | +| [static set(options: SetStorageOptions): void;](../reference/apis/js-apis-system-storage.md#storageset) | \@ohos.data.preferences.d.ts | [put(key: string, value: ValueType, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-data-preferences.md#put)
[put(key: string, value: ValueType): Promise<void>;](../reference/apis/js-apis-data-preferences.md#put-1) | +| [static clear(options?: ClearStorageOptions): void;](../reference/apis/js-apis-system-storage.md#storageclear) | \@ohos.data.preferences.d.ts | [clear(callback: AsyncCallback<void>): void;](../reference/apis/js-apis-data-preferences.md#clear)
[clear(): Promise<void>;](../reference/apis/js-apis-data-preferences.md#clear-1) | +| [static delete(options: DeleteStorageOptions): void;](../reference/apis/js-apis-system-storage.md#storagedelete) | \@ohos.data.preferences.d.ts | [delete(key: string, callback: AsyncCallback<void>): void;](../reference/apis/js-apis-data-preferences.md#delete)
[delete(key: string): Promise<void>;](../reference/apis/js-apis-data-preferences.md#delete-1) | diff --git a/en/application-dev/application-models/thread-model-fa.md b/en/application-dev/application-models/thread-model-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..75401be69cba994ac631b6da997fb6ce2ea35a2f --- /dev/null +++ b/en/application-dev/application-models/thread-model-fa.md @@ -0,0 +1,28 @@ +# Thread Model (FA Model) + + +There are three types of threads in the FA model: + + +- Main thread + +Manages other threads. + +- Ability thread + - One ability thread for each ability. + - Distributes input events. + - Draws the UI. + - Invokes application code callbacks (event processing and lifecycle callbacks). + - Receives messages sent by the worker thread. + +- Worker thread + + Performs time-consuming operations + + +Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. Threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. + + +> **NOTE** +> +> The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. diff --git a/en/application-dev/application-models/thread-model-stage.md b/en/application-dev/application-models/thread-model-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..deaab60b7bd7549dcb96bc00d7896d5c67e5c5d2 --- /dev/null +++ b/en/application-dev/application-models/thread-model-stage.md @@ -0,0 +1,25 @@ +# Thread Model (Stage Model) + +For an OpenHarmony application, each process has a main thread to provide the following functionalities: + +- Manage other threads. + +- Enable multiple UIAbility components of the same application to share the same main thread. + +- Distribute input events. + +- Draw the UI. + +- Invoke application code callbacks (event processing and lifecycle callbacks). + +- Receive messages sent by the worker thread. + +In addition to the main thread, there is an independent thread, named worker. The worker thread is mainly used to perform time-consuming operations. It cannot directly operate the UI. The worker thread is created in the main thread and is independent of the main thread. A maximum of seven worker threads can be created. + +![thread-model-stage](figures/thread-model-stage.png) + +Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. In the same process, threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks. + +> **NOTE** +> +> The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the main thread or between the main thread and worker thread. 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 new file mode 100644 index 0000000000000000000000000000000000000000..981a9212892a8bc1a920ac929608685c3eafeb00 --- /dev/null +++ b/en/application-dev/application-models/uiability-data-sync-with-ui.md @@ -0,0 +1,320 @@ +# Data Synchronization Between UIAbility and UI + + +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 + +[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. + +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. + +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**. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + const TAG: string = '[Example].[Entry].[EntryAbility]'; + + export default class EntryAbility extends UIAbility { + func1(...data) { + // Trigger the event to complete the service operation. + console.info(TAG, '1. ' + JSON.stringify(data)); + } + + onCreate(want, launch) { + // Obtain an eventHub object. + let eventhub = this.context.eventHub; + // Subscribe to the event. + eventhub.on('event1', this.func1); + eventhub.on('event1', (...data) => { + // Trigger the event to complete the service operation. + console.info(TAG, '2. ' + JSON.stringify(data)); + }); + } + } + ``` + +2. Call [eventHub.emit()](../reference/apis/js-apis-inner-application-eventHub.md#eventhubemit) on the UI to trigger the event, and pass the parameters as required. + + ```ts + import common from '@ohos.app.ability.common'; + + @Entry + @Component + struct Index { + private context = getContext(this) as common.UIAbilityContext; + + eventHubFunc() { + // Trigger the event without parameters. + this.context.eventHub.emit('event1'); + // Trigger the event with one parameter. + this.context.eventHub.emit('event1', 1); + // Trigger the event with two parameters. + this.context.eventHub.emit('event1', 2, 'test'); + // You can design the parameters based on your service requirements. + } + + // Page display. + build() { + // ... + } + } + ``` + +3. Obtain the event trigger result from the subscription callback of UIAbility. The run log result is as follows: + + ```ts + [] + + [1] + + [2,'test'] + ``` + +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. + 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 +globalThis1 + + +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) +- [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. + +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**. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class EntryAbility extends UIAbility { + onCreate(want, launch) { + globalThis.entryAbilityWant = want; + // ... + } + + // ... + } + ``` + +2. Use **globalThis** on the UI to obtain the **want** parameter information. + + ```ts + let entryAbilityWant; + + @Entry + @Component + struct Index { + aboutToAppear() { + entryAbilityWant = globalThis.entryAbilityWant; + } + + // Page display. + build() { + // ... + } + } + ``` + + +### 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. + +1. AbilityA stores a string and binds it to globalThis. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class AbilityA extends UIAbility { + onCreate(want, launch) { + globalThis.entryAbilityStr = 'AbilityA'; // AbilityA stores the string "AbilityA" to globalThis. + // ... + } + } + ``` + +2. Obtain the data from AbilityB. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class AbilityB extends UIAbility { + onCreate(want, launch) { + // AbilityB reads the name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + // ... + } + } + ``` + + +### 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. + +1. AbilityA stores a string and binds it to globalThis. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class AbilityA extends UIAbility { + onCreate(want, launch) { + // AbilityA stores the string "AbilityA" to globalThis. + globalThis.entryAbilityStr = 'AbilityA'; + // ... + } + } + ``` + +2. Obtain the data from ExtensionAbility. + + ```ts + import Extension from '@ohos.app.ability.ServiceExtensionAbility' + + export default class ServiceExtAbility extends Extension { + onCreate(want) { + / / ServiceExtAbility reads name from globalThis and outputs it. + console.info('name from entryAbilityStr: ' + globalThis.entryAbilityStr); + // ... + } + } + ``` + + +### Precautions for Using globalThis + + **Figure 2** Precautions for globalThis +![globalThis2](figures/globalThis2.png) + +- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten. + +- This problem does not occur in the FA model because each UIAbility component uses an independent engine. + +- The lifecycle of an object bound to **globalThis** is the same as that of the ArkTS engine instance. You are advised to assign the value **null** after using the object to minimize memory usage. + +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**. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class AbilityA extends UIAbility { + onCreate(want, launch) { + globalThis.context = this.context; // AbilityA 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. + + ```ts + @Entry + @Component + struct Index { + onPageShow() { + let ctx = globalThis.context; // Obtain the context from globalThis and use it. + let permissions = ['com.example.permission'] + ctx.requestPermissionsFromUser(permissions,(result) => { + // ... + }); + } + // Page display. + build() { + // ... + } + } + ``` + +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. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class AbilityB extends UIAbility { + onCreate(want, launch) { + // AbilityB overwrites the context stored by AbilityA 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. + + ```ts + @Entry + @Component + struct Index { + onPageShow() { + let ctx = globalThis.context; // Obtain the context from globalThis and use it. + let permissions = ['com.example.permission'] + ctx.requestPermissionsFromUser(permissions,(result) => { + console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); + }); + } + // Page display. + build() { + // ... + } + } + ``` + +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. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class AbilityA extends UIAbility { + onCreate(want, launch) { // AbilityA 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. + + ```ts + @Entry + @Component + struct Index { + onPageShow() { + let ctx = globalThis.context; // The context in globalThis is the context of AbilityB. + let permissions=['com.example.permission']; + ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown. + console.info('requestPermissionsFromUser result:' + JSON.stringify(result)); + }); + } + // Page display. + build() { + // ... + } + } + ``` diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea6b8bbecfa4a9a4f5434fb0aa5aad6184f38c9f --- /dev/null +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -0,0 +1,631 @@ +# Intra-Device Interaction Between UIAbility Components + + +UIAbility is the minimum unit that can be scheduled by the system. Jumping between functional modules in a device involves starting of specific UIAbility components, which belong to the same or a different application (for example, starting UIAbility of a third-party payment application). + + +This topic describes the UIAbility interaction modes in the following scenarios. For details about cross-device application component interaction, see [Inter-Device Application Component Interaction (Continuation)](inter-device-interaction-hop-overview.md). + + +- [Starting UIAbility in the Same Application](#starting-uiability-in-the-same-application) + +- [Starting UIAbility in the Same Application and Obtaining the Return Result](#starting-uiability-in-the-same-application-and-obtaining-the-return-result) + +- [Starting UIAbility of Another Application](#starting-uiability-of-another-application) + +- [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result) + +- [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) + + +## Starting UIAbility in the Same Application + +This scenario is possible when an application contains multiple UIAbility components. For example, in a payment application, you may need to start the payment UIAbility from the entry UIAbility. + +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). + + ```ts + let wantInfo = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, + } + // context is the ability-level context of the initiator UIAbility. + this.context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) + ``` + +2. Use the FuncAbility lifecycle callback to receive the parameters passed from EntryAbility. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + import window from '@ohos.window'; + + export default class FuncAbility extends UIAbility { + onCreate(want, launchParam) { + // Receive the parameters passed by the caller UIAbility. + let funcAbilityWant = want; + let info = funcAbilityWant?.parameters?.info; + // ... + } + } + ``` + +3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility. + + ```ts + // context is the ability context of the UIAbility instance to stop. + this.context.terminateSelf((err) => { + // ... + }); + ``` + + +## 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). + + ```ts + let wantInfo = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', // moduleName is optional. + parameters: {// Custom information. + info: 'From the Index page of EntryAbility', + }, + } + // context is the ability-level context of the initiator UIAbility. + this.context.startAbilityForResult(wantInfo).then((data) => { + // ... + }).catch((err) => { + // ... + }) + ``` + +2. Call **terminateSelfWithResult()** 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; + let abilityResult = { + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', + parameters: { + info: 'From the Index page of FuncAbility', + }, + }, + } + // context is the ability 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. + + ```ts + const RESULT_CODE: number = 1001; + + // ... + + // context is the ability-level context of the initiator UIAbility. + this.context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the callee UIAbility. + let info = data.want?.parameters?.info; + // ... + } + }).catch((err) => { + // ... + }) + ``` + + +## Starting UIAbility of Another Application + +Generally, the user only needs to do a common operation (for example, selecting a document application to view the document content) to start the UIAbility of another application. The [implicit Want launch mode](want-overview.md#types-of-want) is recommended. The system identifies a matched UIAbility and starts it based on the **want** parameter of the caller. + +There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md). + +- 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. + +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**. + + ```json + { + "module": { + "abilities": [ + { + // ... + "skills": [ + { + "entities": [ + // ... + "entity.system.default" + ], + "actions": [ + // ... + "ohos.want.action.viewData" + ] + } + ] + } + ] + } + } + ``` + +2. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. 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. 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 = { + deviceId: '', // An empty deviceId indicates the local device. + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.viewData', + // entities can be omitted. + entities: ['entity.system.default'], + } + + // context is the ability-level context of the initiator UIAbility. + this.context.startAbility(wantInfo).then(() => { + // ... + }).catch((err) => { + // ... + }) + ``` + + The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. + + uiability-intra-device-interaction + +3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. + + ```ts + // context is the ability context of the UIAbility instance to stop. + this.context.terminateSelf((err) => { + // ... + }); + ``` + + +## 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. + +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**. + + ```json + { + "module": { + "abilities": [ + { + // ... + "skills": [ + { + "entities": [ + // ... + "entity.system.default" + ], + "actions": [ + // ... + "ohos.want.action.editData" + ] + } + ] + } + ] + } + } + ``` + +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. + + ```ts + let wantInfo = { + deviceId: '', // An empty deviceId indicates the local device. + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.editData', + // entities can be omitted. + entities: ['entity.system.default'], + } + + // context is the ability-level context of the initiator UIAbility. + this.context.startAbilityForResult(wantInfo).then((data) => { + // ... + }).catch((err) => { + // ... + }) + ``` + +3. After the payment is finished, call the **terminateSelfWithResult()** method to stop the payment UIAbility and return the **abilityResult** parameter. + + ```ts + const RESULT_CODE: number = 1001; + let abilityResult = { + resultCode: RESULT_CODE, + want: { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + moduleName: 'entry', + parameters: { + payResult: 'OKay', + }, + }, + } + // context is the ability 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()**. + + ```ts + const RESULT_CODE: number = 1001; + + let want = { + // Want parameter information. + }; + + // context is the ability-level context of the initiator UIAbility. + this.context.startAbilityForResult(want).then((data) => { + if (data?.resultCode === RESULT_CODE) { + // Parse the information returned by the callee UIAbility. + let payResult = data.want?.parameters?.payResult; + // ... + } + }).catch((err) => { + // ... + }) + ``` + + +## Starting a Specified Page of UIAbility + +A UIAbility component can have multiple pages. When it is started in different scenarios, different pages can be displayed. For example, when a user jumps from a page of a UIAbility component to another UIAbility, you want to start a specified page of the target UIAbility. This section describes how to specify a startup page and start the specified page when the target UIAbility is started for the first time or when the target UIAbility is not started for the first time. + + +### Specifying a Startup Page + +When the caller UIAbility starts another UIAbility, it usually needs to redirect to a specified page. For example, FuncAbility contains two pages: Index (corresponding to the home page) and Second (corresponding to function A page). You can configure the specified page URL in the **want** parameter by adding a custom parameter to **parameters** in **want**. 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 = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + moduleName: 'module1', // moduleName is optional. + parameters: {// Custom parameter used to pass the page information. + router: 'funcA', + }, +} +// context is the ability-level context of the initiator UIAbility. +this.context.startAbility(wantInfo).then(() => { + // ... +}).catch((err) => { + // ... +}) +``` + + +### Starting a Page When the Target UIAbility Is Started for the First Time + +When the target UIAbility is started for the first time, in the **onWindowStageCreate()** callback of the target UIAbility, parse the **want** parameter passed by EntryAbility to obtain the URL of the page to be loaded, and pass the URL to the **windowStage.loadContent()** method. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility' +import Window from '@ohos.window' + +export default class FuncAbility extends UIAbility { + funcAbilityWant; + + onCreate(want, launchParam) { + // Receive the parameters passed by the caller UIAbility. + this.funcAbilityWant = want; + } + + onWindowStageCreate(windowStage: Window.WindowStage) { + // Main window is created. Set a main page for this ability. + let url = 'pages/Index'; + if (this.funcAbilityWant?.parameters?.router) { + if (this.funcAbilityWant.parameters.router === 'funA') { + url = 'pages/Second'; + } + } + windowStage.loadContent(url, (err, data) => { + // ... + }); + } +} +``` + + +### Starting a Page When the Target UIAbility Is Not Started for the First Time + +You start application A, and its home page is displayed. Then you return to the home screen and start application B. Now you need to start application A again from application B and have a specified page of application A displayed. An example scenario is as follows: When you open the home page of the SMS application and return to the home screen, the SMS application is in the opened state and its home page is displayed. Then you open the home page of the Contacts application, access user A's details page, and touch the SMS icon to send an SMS message to user A. The SMS application is started again and the sending page is displayed. + +![uiability_not_first_started](figures/uiability_not_first_started.png) + +In summary, when a UIAbility instance of application A has been created and the main page of the UIAbility instance is displayed, you need to start the UIAbility of application A from application B and have a different page displayed. + +1. In the target UIAbility, the **Index** page is loaded by default. The UIAbility instance has been created, and the **onNewWant()** callback rather than **onCreate()** and **onWindowStageCreate()** will be invoked. In the **onNewWant()** callback, parse the **want** parameter and bind it to the global variable **globalThis**. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class FuncAbility extends UIAbility { + onNewWant(want, launchParam) { + // Receive the parameters passed by the caller UIAbility. + globalThis.funcAbilityWant = want; + // ... + } + } + ``` + +2. In FuncAbility, use the router module to implement redirection to the specified page on the **Index** page. Because the **Index** page of FuncAbility is active, the variable will not be declared again and the **aboutToAppear()** callback will not be triggered. Therefore, the page routing functionality can be implemented in the **onPageShow()** callback of the **Index** page. + + ```ts + import router from '@ohos.router'; + + @Entry + @Component + struct Index { + onPageShow() { + let funcAbilityWant = globalThis.funcAbilityWant; + let url2 = funcAbilityWant?.parameters?.router; + if (url2 && url2 === 'funcA') { + router.replaceUrl({ + url: 'pages/Second', + }) + } + } + + // Page display. + build() { + // ... + } + } + ``` + +> **NOTE** +> +> 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 + +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. + +The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: + +- **startAbilityByCall** supports ability launch in the foreground and background, whereas **startAbility** supports ability launch in the foreground only. + +- The caller ability can use the caller object returned by **startAbilityByCall** to communicate with the callee ability, but **startAbility** does not provide the communication capability. + +Ability call is usually used in the following scenarios: + +- Communicating with the callee ability + +- Starting the callee ability in the background + +**Table 1** Terms used in the ability call + +| **Term**| Description| +| -------- | -------- | +| CallerAbility | UIAbility that triggers the ability call.| +| CalleeAbility | UIAbility invoked by the ability call.| +| Caller | Object returned by **startAbilityByCall** and used by the caller ability to communicate with the callee ability.| +| Callee | Object held by the callee ability to communicate with the caller ability.| + +The following figure shows the ability call process. + +**Figure 1** Ability call process + +call + +- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. + +- The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. + +> **NOTE** +> 1. Currently, only system applications can use the ability call. +> +> 2. The launch type of the callee ability must be **singleton**. +> +> 3. Both local (intra-device) and cross-device ability calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device ability call, see [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call). + + +### Available APIs + +The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). + +**Table 2** Ability call APIs + +| API| Description| +| -------- | -------- | +| startAbilityByCall(want: Want): Promise<Caller> | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| +| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| +| off(method: string): void | Callback invoked when the callee ability deregisters a method.| +| call(method: string, data: rpc.Sequenceable): Promise<void> | Sends agreed sequenceable data to the callee ability.| +| callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel> | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| +| release(): void | Releases the caller object.| +| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| + +The implementation of using the ability call for UIAbility interaction involves two parts. + +- [Creating a Callee Ability](#creating-a-callee-ability) + +- [Accessing the Callee Ability](#accessing-the-callee-ability) + + +### Creating a Callee Ability + +For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. + +1. Configure the ability launch type. + + 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**.| + +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 + }] + ``` + +2. Import the **UIAbility** module. + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + ``` + +3. Define the agreed sequenceable data. + + 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 + str: string = "" + + constructor(num, string) { + this.num = num + this.str = string + } + + marshalling(messageParcel) { + messageParcel.writeInt(this.num) + messageParcel.writeString(this.str) + return true + } + + unmarshalling(messageParcel) { + this.num = messageParcel.readInt() + this.str = messageParcel.readString() + return true + } + } + ``` + +4. Implement **Callee.on** and **Callee.off**. + + 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'; + + 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)}`); + } + } + } + ``` + + +### Accessing the Callee Ability + +1. Import the **UIAbility** module. + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; + ``` + +2. Obtain the caller interface. + + 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) { + try { + caller.on("release", (msg) => { + console.info(`caller onRelease is called ${msg}`); + }) + console.info('caller register OnRelease succeed'); + } catch (error) { + console.info(`caller register OnRelease failed with ${error}`); + } + } + + async onButtonGetCaller() { + try { + this.caller = await context.startAbilityByCall({ + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }) + if (this.caller === undefined) { + console.info('get caller failed') + return + } + console.info('get caller success') + this.regOnRelease(this.caller) + } catch (error) { + console.info(`get caller failed with ${error}`) + } + } + ``` diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md new file mode 100644 index 0000000000000000000000000000000000000000..cda8307ddd3dae6f7cceac3fad134ef510d7383c --- /dev/null +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -0,0 +1,162 @@ +# UIAbility Component Launch Type + + +The launch type of the UIAbility component refers to the state of the UIAbility instance at startup. The system provides three launch types: + + +- [Singleton](#singleton) + +- [Standard](#standard) + +- [Specified](#specified) + + +## Singleton + +**singleton** is the default launch type. + +Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. + +**Figure 1** Demonstration effect in singleton mode + +uiability-launch-type1 + +> **NOTE** +> +> Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. + +To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**. + + +```json +{ + "module": { + // ... + "abilities": [ + { + "launchType": "singleton", + // ... + } + ] + } +} +``` + + +## Standard + +In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**. + +**Figure 2** Demonstration effect in standard mode + +standard-mode + +To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**. + + +```json +{ + "module": { + // ... + "abilities": [ + { + "launchType": "standard", + // ... + } + ] + } +} +``` + + +## Specified + +The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. + +**Figure 3** Demonstration effect in specified mode + +uiability-launch-type2 + +For example, there are EntryAbility and SpecifiedAbility, and the launch type of SpecifiedAbility is set to **specified**. You are required to start SpecifiedAbility from EntryAbility. + +1. In SpecifiedAbility, set the **launchType** field in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **specified**. + + ```json + { + "module": { + // ... + "abilities": [ + { + "launchType": "specified", + // ... + } + ] + } + } + ``` + +2. Before a UIAbility instance is created, you can create a unique string key for the instance. The key is bound to the UIAbility instance when it is created. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the application is asked which UIAbility instance is used to respond to the [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) request. + In EntryAbility, add a custom parameter, for example, **instanceKey**, to the [want](want-overview.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances. + + ```ts + // Configure an independent key for each UIAbility instance. + // For example, in the document usage scenario, use the document path as the key. + function getInstance() { + // ... + } + + let want = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'SpecifiedAbility', + moduleName: 'module1', // moduleName is optional. + parameters: {// Custom information. + instanceKey: getInstance(), + }, + } + // context is the ability-level context of the initiator UIAbility. + this.context.startAbility(want).then(() => { + // ... + }).catch((err) => { + // ... + }) + ``` + +3. During running, the internal service of UIAbility determines whether to create multiple instances. If the key is matched, the UIAbility instance bound to the key is started. Otherwise, a new UIAbility instance is created. + The launch type of SpecifiedAbility is set to **specified**. Before SpecifiedAbility is started, the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the corresponding AbilityStage instance is invoked to parse the input **want** parameter and obtain the custom parameter **instanceKey**. A string key identifier is returned through the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of the AbilityStage instance. [If the returned key corresponds to a started UIAbility instance](mission-management-launch-type.md#fig14520125175314), that UIAbility instance is switched to the foreground and gains focus again. Otherwise, a new instance is created and started. + + ```ts + import AbilityStage from '@ohos.app.ability.AbilityStage'; + + export default class MyAbilityStage extends AbilityStage { + onAcceptWant(want): string { + // In the AbilityStage instance of the callee, a key value corresponding to a UIAbility instance is returned for UIAbility whose launch type is specified. + // In this example, SpecifiedAbility of module1 is returned. + if (want.abilityName === 'SpecifiedAbility') { + // The returned string key is a custom string. + return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; + } + + return ''; + } + } + ``` + + > **NOTE** + > + > 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. + > 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). + + For example, in the document application, different key values are bound to different document instances. Each time a document is created, a new key value (for example, file path) is passed, and a new UIAbility instance is created when UIAbility is started in AbilityStage. However, when you open an existing document, the same UIAbility instance is started again in AbilityStage. + + +The following steps are used as an example. + 1. Open file A. A UIAbility instance, for example, UIAbility instance 1, is started. + + 2. Close the process of file A in **Recents**. UIAbility instance 1 is destroyed. Return to the home screen and open file A again. A new UIAbility instance is started, for example, UIAbility instance 2. + + 3. Return to the home screen and open file B. A new UIAbility instance is started, for example, UIAbility instance 3. + + 4. Return to the home screen and open file A again. UIAbility instance 2 is started. + + \ No newline at end of file diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md new file mode 100644 index 0000000000000000000000000000000000000000..9ec701cbffd4da51098d5dc448addd88f26ee47e --- /dev/null +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -0,0 +1,147 @@ +# UIAbility Component Lifecycle + + +## Overview + +When a user opens, switches, and returns to an application, the UIAbility instances in the application transit in their different states. The UIAbility class provides a series of callbacks. Through these callbacks, you can know the state changes of the UIAbility instance, for example, being created or destroyed, or running in the foreground or background. + +The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below. + +**Figure 1** UIAbility lifecycle states +Ability-Life-Cycle + + +## Description of Lifecycle States + + +### Create + +The **Create** state is triggered when the UIAbility instance is created during application loading. The system invokes the **onCreate()** callback. In this callback, you can perform application initialization operations, for example, defining variables or loading resources. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // Initialize the application. + } + // ... +} +``` + + +### WindowStageCreate and WindowStageDestory + +After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback. + +**Figure 2** WindowStageCreate and WindowStageDestory +Ability-Life-Cycle-WindowStage + +In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + // ... + + onWindowStageCreate(windowStage: Window.WindowStage) { + // Subscribe to the WindowStage events (having or losing focus, or becoming visible or invisible). + try { + windowStage.on('windowStageEvent', (data) => { + console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + + JSON.stringify(data)); + }); + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; + + // Set the UI loading. + windowStage.loadContent('pages/Index', (err, data) => { + // ... + }); + } +} +``` + +> **NOTE** +> +> For details about how to use WindowStage, see [Window Development](../windowmanager/application-window-stage.md). + +Before the UIAbility instance is destroyed, the **onWindowStageDestroy()** callback is invoked to release UI resources. In this callback, you can unsubscribe from the WindowStage events. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + // ... + + onWindowStageDestroy() { + // Release UI resources. + // Unsubscribe from the WindowStage events such as having or losing focus in the onWindowStageDestroy() callback. + try { + windowStage.off('windowStageEvent'); + } catch (exception) { + console.error('Failed to disable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; + } +} +``` + + +### Foreground and Background + +The **Foreground** and **Background** states are triggered when the UIAbility instance is switched to the foreground and background respectively. They correspond to the **onForeground()** and **onBackground()** callbacks. + +The **onForeground()** callback is triggered before the UI of the UIAbility instance becomes visible, for example, when the UIAbility instance is switched to the foreground. In this callback, you can apply for resources required by the system or re-apply for resources that have been released in the **onBackground()** callback. + +The **onBackground()** callback is triggered after the UI of the UIAbility component is completely invisible, for example, when the UIAbility instance is switched to the background. In this callback, you can release useless resources or perform time-consuming operations such as saving the status. + +For example, an application needs to use positioning, and the application has requested the positioning permission from the user. Before the UI is displayed, you can enable positioning in the **onForeground()** callback to obtain the location information. + +When the application is switched to the background, you can disable positioning in the **onBackground()** callback to reduce system resource consumption. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... + + onForeground() { + // Apply for the resources required by the system or re-apply for the resources released in onBackground(). + } + + onBackground() { + // Release useless resources when the UI is invisible, or perform time-consuming operations in this callback, + // for example, saving the status. + } +} +``` + + +### Destroy + +The **Destroy** state is triggered when the UIAbility instance is destroyed. You can perform operations such as releasing system resources and saving data in the **onDestroy()** callback. + +The UIAbility instance is destroyed when **terminateSelf()** is called or the user closes the instance in **Recents**. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + // ... + + onDestroy() { + // Release system resources and save data. + } +} +``` diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..14cb5c4652749c97dd6e50c4232b6f65fb6feaab --- /dev/null +++ b/en/application-dev/application-models/uiability-overview.md @@ -0,0 +1,39 @@ +# UIAbility Component Overview + + +## Overview + +UIAbility has the UI and is mainly used 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**. + + +## Privacy Statement Configuration + +To enable an application to properly use a UIAbility component, declare the UIAbility name, entry, and tags under [abilities](../quick-start/module-configuration-file.md#abilities) in the [module.json5 configuration file](../quick-start/module-configuration-file.md). + + +```json +{ + "module": { + // ... + "abilities": [ + { + "name": "EntryAbility", // Name of the UIAbility component. + "srcEntrance": "./ets/entryability/EntryAbility.ts", // Code path of the UIAbility component. + "description": "$string:EntryAbility_desc", // Description of the UIAbility component. + "icon": "$media:icon", // Icon of the UIAbility component. + "label": "$string:EntryAbility_label", // Label of the UIAbility component. + "startWindowIcon": "$media:icon", // Index of the icon resource file. + "startWindowBackground": "$color:start_window_background", // Index of the background color resource file. + // ... + } + ] + } +} +``` + +> **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/uiability-usage.md b/en/application-dev/application-models/uiability-usage.md new file mode 100644 index 0000000000000000000000000000000000000000..fa8badc6d48c7e550922cb60a15d02eab9cc80b6 --- /dev/null +++ b/en/application-dev/application-models/uiability-usage.md @@ -0,0 +1,99 @@ +# UIAbility Component Usage + + +When using the UIAbility component, you must specify a startup page and obtain the context, [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md). + + +## Specifying the Startup Page of UIAbility + +If no startup page is specified, a white screen occurs after the application is started. You can use **loadContent()** of [WindowStage](../reference/apis/js-apis-window.md#windowstage9) to set the startup page in the **onWindowStageCreate()** callback of the UIAbility instance. + + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created. Set a main page for this ability. + windowStage.loadContent('pages/Index', (err, data) => { + // ... + }); + } + + // ... +} +``` + +> **NOTE** +> +> When you create UIAbility in DevEco Studio, the UIAbility instance loads the **Index** page by default. Therefore, you only need to replace the **Index** page path with the required startup page path. + + +## Obtaining the Context of UIAbility + +The UIAbility class has its own context, which is an instance of the [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) class. The UIAbilityContext class has attributes such as **abilityInfo** and **currentHapModuleInfo**. UIAbilityContext can be used to obtain the UIAbility configuration information, such as the bundle code path, bundle name, ability name, and environment status required by the application. It can also be used to obtain methods to operate the UIAbility instance, such as **startAbility()**, **connectServiceExtensionAbility()**, and **terminateSelf()**. + +- You can use **this.context** to obtain the context of a UIAbility instance. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // Obtain the context of the UIAbility instance. + let context = this.context; + + // ... + } + } + ``` + +- Import the context module and define the **context** variable in the component. + + ```ts + import common from '@ohos.app.ability.common'; + + @Entry + @Component + struct Index { + private context = getContext(this) as common.UIAbilityContext; + + startAbilityTest() { + let want = { + // Want parameter information. + }; + this.context.startAbility(want); + } + + // Page display. + build() { + // ... + } + } + ``` + + You can also define variables after importing the context module but before using [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md). + + + ```ts + import common from '@ohos.app.ability.common'; + + @Entry + @Component + struct Index { + + startAbilityTest() { + let context = getContext(this) as common.UIAbilityContext; + let want = { + // Want parameter information. + }; + context.startAbility(want); + } + + // Page display. + build() { + // ... + } + } + ``` diff --git a/en/application-dev/application-models/want-fa.md b/en/application-dev/application-models/want-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..5ef82daf1f6ac353200131fd8195cbea35725e3c --- /dev/null +++ b/en/application-dev/application-models/want-fa.md @@ -0,0 +1,4 @@ +# Want (FA Model) + + +For details, see "[Want](want-overview.md)" in the stage model. diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..f8239c64cf43a0df0acca0bc1ec0e3be914eecfe --- /dev/null +++ b/en/application-dev/application-models/want-overview.md @@ -0,0 +1,49 @@ +# Want Overview + + +## 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. + +**Figure 1** Want usage +usage-of-want + + +## 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. + + ```ts + let wantInfo = { + deviceId: '', // An empty deviceId indicates the local device. + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + } + ``` + +- **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. + + + ```ts + let wantInfo = { + // Uncomment the line below if you want to implicitly query data only in the specific bundle. + // bundleName: 'com.example.myapplication', + action: 'ohos.want.action.search', + // entities can be omitted. + entities: [ 'entity.system.browsable' ], + uri: 'https://www.test.com:8080/query/student', + type: 'text/plain', + }; + ``` + + > **NOTE** + > - Depending on the ability matching result, the following cases may be possible when you attempt to use implicit Want to start the ability. + > - No ability is matched. The startup fails. + > - An ability that meets the conditions is matched. That ability is started. + > - Multiple abilities that meet the conditions are matched. A dialog box is displayed for users to select one of them. + > + > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want. + > + > - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned. diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..17f9ee7234865b5d01e2a5f68e52cf7928739db7 --- /dev/null +++ b/en/application-dev/application-models/widget-development-fa.md @@ -0,0 +1,546 @@ +# Widget Development + + +## Widget Overview + +A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. + +A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. + +Before you get started, it would be helpful if you have a basic understanding of the following concepts: + +- Widget host: an application that displays the widget content and controls the widget location. + +- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. + +- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. + + +## Working Principles + +Figure 1 shows the working principles of the widget framework. + +**Figure 1** Widget framework working principles in the FA model +![form-extension](figures/form-extension.png) + +The widget host consists of the following modules: + +- Widget usage: provides operations such as creating, deleting, or updating a widget. + +- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. + +The Widget Manager consists of the following modules: + +- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. + +- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. + +- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. + +- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. + +- Communication adapter: communicates with the widget host and provider through RPCs. + +The widget provider consists of the following modules: + +- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. + +- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. + +- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. + +> **NOTE** +> +> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. + + +## Available APIs + +The **FormAbility** has the following APIs. + +| API| Description| +| -------- | -------- | +| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| +| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| +| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated.| +| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| +| onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed.| +| onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget.| +| onShare?(formId: string): {[key: string]: any} | Called by the widget provider to receive shared widget data.| + +The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). + + +| API| Description| +| -------- | -------- | +| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void;| Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result.| +| setFormNextRefreshTime(formId: string, minute: number): Promise<void>;| Sets the next refresh time for a widget. This API uses a promise to return the result.| +| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.| +| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result.| + + +The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis/js-apis-app-form-formBindingData.md). + + +| API| Description| +| -------- | -------- | +| createFormBindingData(obj?: Object \ string): FormBindingData| | Creates a **FormBindingData** object.| + + +## How to Develop + +The widget provider development based on the [FA model](fa-model-development-overview.md) involves the following key steps: + +- [Implementing Widget Lifecycle Callbacks](#implementing-widget-lifecycle-callbacks): Develop the **FormAbility** lifecycle callback functions. + +- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **config.json**. + +- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. + +- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. + +- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. + +- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. + + +### Implementing Widget Lifecycle Callbacks + +To create a widget in the FA model, implement the widget lifecycle callbacks. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). + +1. Import related modules to **form.ts**. + + ```ts + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; + import dataStorage from '@ohos.data.storage'; + ``` + +2. Implement the widget lifecycle callbacks in **form.ts**. + + ```ts + export default { + onCreate(want) { + console.info('FormAbility onCreate'); + // Called when the widget is created. The widget provider should return the widget data binding class. + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + }, + onCastToNormal(formId) { + // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + console.info('FormAbility onCastToNormal'); + }, + onUpdate(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('FormAbility onUpdate'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + formProvider.updateForm(formId, formData).catch((error) => { + console.info('FormAbility updateForm, error:' + JSON.stringify(error)); + }); + }, + onVisibilityChange(newStatus) { + // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. + console.info('FormAbility onVisibilityChange'); + }, + onEvent(formId, message) { + // If the widget supports event triggering, override this method and implement the trigger. + console.info('FormAbility onEvent'); + }, + onDestroy(formId) { + // Delete widget data. + console.info('FormAbility onDestroy'); + }, + onAcquireFormState(want) { + console.info('FormAbility onAcquireFormState'); + return formInfo.FormState.READY; + }, + } + ``` + +> **NOTE** +> +> FormAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. + +### Configuring the Widget Configuration File + +The widget configuration file is named **config.json**. Find the **config.json** file for the widget and edit the file depending on your need. + +- The **js** module in the **config.json** file provides JavaScript resources of the widget. The internal structure is described as follows: + | Name| Description| Data Type| Initial Value Allowed| + | -------- | -------- | -------- | -------- | + | name | Name of a JavaScript component. The default value is **default**.| String| No| + | pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array| No| + | window | Window-related configurations.| Object| Yes| + | type | Type of the JavaScript component. The value can be:
**normal**: indicates an application instance.
**form**: indicates a widget instance.| String| Yes (initial value: **normal**)| + | mode | Development mode of the JavaScript component.| Object| Yes (initial value: left empty)| + + Example configuration: + + + ```json + "js": [{ + "name": "widget", + "pages": ["pages/index/index"], + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "type": "form" + }] + ``` + +- The **abilities** module in the **config.json** file corresponds to **FormAbility** of the widget. The internal structure is described as follows: + | Name| Description| Data Type| Initial Value Allowed| + | -------- | -------- | -------- | -------- | + | name | Class name of a widget. The value is a string with a maximum of 127 bytes.| String| No| + | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| + | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| + | type | Type of the widget. The value can be:
**JS**: indicates a JavaScript-programmed widget.| String| No| + | colorMode | Color mode of the widget.
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| + | supportDimensions | Grid styles supported by the widget.
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No| + | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| + | updateEnabled | Whether the widget can be updated periodically.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean| No| + | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)| + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| + | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| + | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes.| String| No| + | metaData | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| + | customizeData | Custom information about the widget.| Object array| Yes (initial value: left empty)| + + Example configuration: + + + ```json + "abilities": [{ + "name": "FormAbility", + "description": "This is a FormAbility", + "formsEnabled": true, + "icon": "$media:icon", + "label": "$string:form_FormAbility_label", + "srcPath": "FormAbility", + "type": "service", + "srcLanguage": "ets", + "formsEnabled": true, + "formConfigAbility": "ability://com.example.entry.EntryAbility", + "forms": [{ + "colorMode": "auto", + "defaultDimension": "2*2", + "description": "This is a widget.", + "formVisibleNotify": true, + "isDefault": true, + "jsComponentName": "widget", + "name": "widget", + "scheduledUpdateTime": "10:30", + "supportDimensions": ["2*2"], + "type": "JS", + "updateEnabled": true + }] + }] + ``` + + +### Persistently Storing Widget Data + +A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. + + +```ts +const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; +async function storeFormInfo(formId: string, formName: string, tempFlag: boolean) { + // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. + let formInfo = { + "formName": formName, + "tempFlag": tempFlag, + "updateCount": 0 + }; + try { + const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); + // Put the widget information. + await storage.put(formId, JSON.stringify(formInfo)); + console.info(`storeFormInfo, put form info successfully, formId: ${formId}`); + await storage.flush(); + } catch (err) { + console.error(`failed to storeFormInfo, err: ${JSON.stringify(err)}`); + } +} + +// ... + onCreate(want) { + console.info('FormAbility onCreate'); + + let formId = want.parameters["ohos.extra.param.key.form_identity"]; + let formName = want.parameters["ohos.extra.param.key.form_name"]; + let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; + // Persistently store widget data for subsequent use, such as instance acquisition and update. + // Implement this API based on project requirements. + storeFormInfo(formId, formName, tempFlag); + + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + } +// ... +``` + +You should override **onDestroy** to implement widget data deletion. + + +```ts +const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; +async function deleteFormInfo(formId: string) { + try { + const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); + // Delete the widget information. + await storage.delete(formId); + console.info(`deleteFormInfo, del form info successfully, formId: ${formId}`); + await storage.flush(); + } catch (err) { + console.error(`failed to deleteFormInfo, err: ${JSON.stringify(err)}`); + } +} + +// ... + onDestroy(formId) { + console.info('FormAbility onDestroy'); + // Delete the persistent widget instance data. + // Implement this API based on project requirements. + deleteFormInfo(formId); + } +// ... +``` + +For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). + +The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. + +- Normal widget: a widget persistently used by the widget host + +- Temporary widget: a widget temporarily used by the widget host + +Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. + + +### Updating Widget Data + +When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget. + + +```ts +onUpdate(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('FormAbility onUpdate'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. + formProvider.updateForm(formId, formData).catch((error) => { + console.info('FormAbility updateForm, error:' + JSON.stringify(error)); + }); +} +``` + + +### Developing the Widget UI Page + +You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. + +![widget-development-fa](figures/widget-development-fa.png) + +> **NOTE** +> +> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. + +- HML: uses web-like paradigm components to describe the widget page information. + + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + +- CSS: defines style information about the web-like paradigm components in HML. + + ```css + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + + .bg-img { + flex-shrink: 0; + height: 100%; + } + + .container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; + } + + .title { + font-size: 19px; + font-weight: bold; + color: white; + text-overflow: ellipsis; + max-lines: 1; + } + + .detail_text { + font-size: 16px; + color: white; + opacity: 0.66; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; + } + ``` + +- JSON: defines data and event interaction on the widget UI page. + + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "com.example.entry.EntryAbility", + "params": { + "message": "add detail" + } + } + } + } + ``` + + +### Developing Widget Events + +You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: + +1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. + +2. Set the router event. + - **action**: **"router"**, which indicates a router event. + - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.EntryAbility. + - **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the EntryAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. + +3. Set the message event. + - **action**: **"message"**, which indicates a message event. + - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. + +The following is an example: + +- HML file: + + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + +- CSS file: + + ```css + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + + .bg-img { + flex-shrink: 0; + height: 100%; + } + + .container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; + } + + .title { + font-size: 19px; + font-weight: bold; + color: white; + text-overflow: ellipsis; + max-lines: 1; + } + + .detail_text { + font-size: 16px; + color: white; + opacity: 0.66; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; + } + ``` + +- JSON file: + + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "com.example.entry.EntryAbility", + "params": { + "message": "add detail" + } + }, + "messageEvent": { + "action": "message", + "params": { + "message": "add detail" + } + } + } + } + ``` + diff --git a/en/application-dev/application-models/widget-development-stage.md b/en/application-dev/application-models/widget-development-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..3e542956072a31fbc8dbca097ae264dfe8ebfc5f --- /dev/null +++ b/en/application-dev/application-models/widget-development-stage.md @@ -0,0 +1,599 @@ +# FormExtensionAbility (Widget) + + +## Widget Overview + +FormExtensionAbility provides a service widget (also called widget), which is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. + +A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. + +Before you get started, it would be helpful if you have a basic understanding of the following concepts: + +- Widget host: an application that displays the widget content and controls the widget location. + +- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. + +- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. + + +## Working Principles + +Figure 1 shows the working principles of the widget framework. + +**Figure 1** Widget framework working principles in the stage model +![form-extension](figures/form-extension.png) + +The widget host consists of the following modules: + +- Widget usage: provides operations such as creating, deleting, or updating a widget. + +- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. + +The Widget Manager consists of the following modules: + +- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. + +- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. + +- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. + +- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. + +- Communication adapter: communicates with the widget host and provider through RPCs. + +The widget provider consists of the following modules: + +- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. + +- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. + +- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. + +> **NOTE** +> +> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. + + +## Available APIs + +The **FormExtensionAbility** class has the following APIs. For details, see [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). + +| API| Description| +| -------- | -------- | +| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| +| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| +| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget has been updated.| +| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| +| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| +| onRemoveForm(formId: string): void| Called to notify the widget provider that a widget has been destroyed.| +| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is updated.| +| onShareForm?(formId: string): { [key: string]: any }| Called by the widget provider to receive shared widget data.| + +The **FormExtensionAbility** class also has a member context, that is, the FormExtensionContext class. For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). + +| API| Description| +| -------- | -------- | +| startAbility(want: Want, callback: AsyncCallback<void>): void | Starts UIAbility of the application to which a widget belongs. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications. You must apply for the permission to use the API.)| +| startAbility(want: Want): Promise<void> | Starts UIAbility of the application to which a widget belongs. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications. You must apply for the permission to use the API.)| + +The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). + +| API| Description| +| -------- | -------- | +| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; | Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result.| +| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.| +| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.| +| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>;| Updates a widget. This API uses a promise to return the result.| + +The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis/js-apis-app-form-formBindingData.md). + +| API| Description| +| -------- | -------- | +| createFormBindingData(obj?: Object \ string): FormBindingData| | Creates a **FormBindingData** object.| + + +## How to Develop + +The widget provider development based on the [stage model](stage-model-development-overview.md) involves the following key steps: + +- [Creating a FormExtensionAbility Instance](#creating-a-formextensionability-instance): Develop the lifecycle callback functions of FormExtensionAbility. + +- [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. + +- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. + +- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. + +- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. + + +### Creating a FormExtensionAbility Instance + +To create a widget in the stage model, implement the lifecycle callbacks of **FormExtensionAbility**. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). + +1. Import related modules to **EntryFormAbility.ts**. + + ```ts + import FormExtension from '@ohos.app.form.FormExtensionAbility'; + import formBindingData from '@ohos.app.form.formBindingData'; + import formInfo from '@ohos.app.form.formInfo'; + import formProvider from '@ohos.app.form.formProvider'; + import dataStorage from '@ohos.data.storage'; + ``` + +2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. + + ```ts + export default class EntryFormAbility extends FormExtension { + onAddForm(want) { + console.info('[EntryFormAbility] onAddForm'); + // Called when the widget is created. The widget provider should return the widget data binding class. + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + } + onCastToNormalForm(formId) { + // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + console.info('[EntryFormAbility] onCastToNormalForm'); + } + onUpdateForm(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('[EntryFormAbility] onUpdateForm'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + formProvider.updateForm(formId, formData).catch((error) => { + console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); + }); + } + onChangeFormVisibility(newStatus) { + // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. + console.info('[EntryFormAbility] onChangeFormVisibility'); + } + onFormEvent(formId, message) { + // If the widget supports event triggering, override this method and implement the trigger. + console.info('[EntryFormAbility] onFormEvent'); + } + onRemoveForm(formId) { + // Delete widget data. + console.info('[EntryFormAbility] onRemoveForm'); + } + onConfigurationUpdate(config) { + console.info('[EntryFormAbility] nConfigurationUpdate, config:' + JSON.stringify(config)); + } + onAcquireFormState(want) { + return formInfo.FormState.READY; + } + } + ``` + +> **NOTE** +> +> FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. + +### Configuring the Widget Configuration File + +1. Configure ExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). For a FormExtensionAbility, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. + Example configuration: + + + ```json + { + "module": { + // ... + "extensionAbilities": [ + { + "name": "EntryFormAbility", + "srcEntrance": "./ets/entryformability/EntryFormAbility.ts", + "label": "$string:EntryFormAbility_label", + "description": "$string:EntryFormAbility_desc", + "type": "form", + "metadata": [ + { + "name": "ohos.extension.form", + "resource": "$profile:form_config" + } + ] + } + ] + } + } + ``` + +2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if resource is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal field structure. + **Table 1** Widget profile configuration file + + | Field| Description| Data Type| Initial Value Allowed| + | -------- | -------- | -------- | -------- | + | name | Class name of a widget. The value is a string with a maximum of 127 bytes.| String| No| + | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| + | src | Full path of the UI code corresponding to the widget.| String| No| + | window | Window-related configurations.| Object| Yes| + | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| + | colorMode | Color mode of the widget.
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| + | supportDimensions | Grid styles supported by the widget.
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No| + | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| + | updateEnabled | Whether the widget can be updated periodically.
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean| No| + | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)| + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| + | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| + | metaData | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| + + Example configuration: + + ```json + { + "forms": [ + { + "name": "widget", + "description": "This is a widget.", + "src": "./js/widget/pages/index/index", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2" + ] + } + ] + } + ``` + + +### Persistently Storing Widget Data + +A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. + + +```ts +const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; +async function storeFormInfo(formId: string, formName: string, tempFlag: boolean) { + // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. + let formInfo = { + "formName": formName, + "tempFlag": tempFlag, + "updateCount": 0 + }; + try { + const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); + // Put the widget information. + await storage.put(formId, JSON.stringify(formInfo)); + console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); + await storage.flush(); + } catch (err) { + console.error(`[EntryFormAbility] failed to storeFormInfo, err: ${JSON.stringify(err)}`); + } +} + +export default class EntryFormAbility extends FormExtension { + // ... + onAddForm(want) { + console.info('[EntryFormAbility] onAddForm'); + + let formId = want.parameters["ohos.extra.param.key.form_identity"]; + let formName = want.parameters["ohos.extra.param.key.form_name"]; + let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; + // Persistently store widget data for subsequent use, such as instance acquisition and update. + // Implement this API based on project requirements. + storeFormInfo(formId, formName, tempFlag); + + let obj = { + "title": "titleOnCreate", + "detail": "detailOnCreate" + }; + let formData = formBindingData.createFormBindingData(obj); + return formData; + } +} +``` + +You should override **onRemoveForm** to implement widget data deletion. + + +```ts +const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; +async function deleteFormInfo(formId: string) { + try { + const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); + // Delete the widget information. + await storage.delete(formId); + console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); + await storage.flush(); + } catch (err) { + console.error(`[EntryFormAbility] failed to deleteFormInfo, err: ${JSON.stringify(err)}`); + } +} + +// ... + +export default class EntryFormAbility extends FormExtension { + // ... + onRemoveForm(formId) { + console.info('[EntryFormAbility] onRemoveForm'); + // Delete the persistent widget instance data. + // Implement this API based on project requirements. + deleteFormInfo(formId); + } +} +``` + +For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). + +The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. + +- Normal widget: a widget persistently used by the widget host + +- Temporary widget: a widget temporarily used by the widget host + +Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. + + +### Updating Widget Data + +When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget. + + +```ts +onUpdateForm(formId) { + // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. + console.info('[EntryFormAbility] onUpdateForm'); + let obj = { + "title": "titleOnUpdate", + "detail": "detailOnUpdate" + }; + let formData = formBindingData.createFormBindingData(obj); + // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. + formProvider.updateForm(formId, formData).catch((error) => { + console.info('[EntryFormAbility] updateForm, error:' + JSON.stringify(error)); + }); +} +``` + + +### Developing the Widget UI Page + +You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. + +![widget-development-stage](figures/widget-development-stage.png) + +> **NOTE** +> +> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI. + +- HML: uses web-like paradigm components to describe the widget page information. + + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + +- CSS: defines style information about the web-like paradigm components in HML. + + ```css + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + + .bg-img { + flex-shrink: 0; + height: 100%; + } + + .container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; + } + + .title { + font-size: 19px; + font-weight: bold; + color: white; + text-overflow: ellipsis; + max-lines: 1; + } + + .detail_text { + font-size: 16px; + color: white; + opacity: 0.66; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; + } + ``` + +- JSON: defines data and event interaction on the widget UI page. + + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "EntryAbility", + "params": { + "message": "add detail" + } + } + } + } + ``` + + +### Developing Widget Events + +You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. + +The key steps are as follows: + +1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. + +2. Set the router event. + - **action**: **"router"**, which indicates a router event. + - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. + - **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. + +3. Set the message event. + - **action**: **"message"**, which indicates a message event. + - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. + +The following is an example: + +- HML file: + + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + +- CSS file: + + ```css + .container { + flex-direction: column; + justify-content: center; + align-items: center; + } + + .bg-img { + flex-shrink: 0; + height: 100%; + } + + .container-inner { + flex-direction: column; + justify-content: flex-end; + align-items: flex-start; + height: 100%; + width: 100%; + padding: 12px; + } + + .title { + font-size: 19px; + font-weight: bold; + color: white; + text-overflow: ellipsis; + max-lines: 1; + } + + .detail_text { + font-size: 16px; + color: white; + opacity: 0.66; + text-overflow: ellipsis; + max-lines: 1; + margin-top: 6px; + } + ``` + +- JSON file: + + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "EntryAbility", + "params": { + "info": "router info", + "message": "router message" + } + }, + "messageEvent": { + "action": "message", + "params": { + "detail": "message detail" + } + } + } + } + ``` + +- Receive the router event and obtain parameters in UIAbility. + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility' + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // Obtain the info parameter passed in the router event. + if (want.parameters.info === "router info") { + // Do something. + // console.log("router info:" + want.parameters.info) + } + // Obtain the message parameter passed in the router event. + if (want.parameters.message === "router message") { + // Do something. + // console.log("router message:" + want.parameters.message) + } + } + // ... + }; + ``` + +- Receive the message event in FormExtensionAbility and obtain parameters. + + ```ts + import FormExtension from '@ohos.app.form.FormExtensionAbility'; + + export default class FormAbility extends FormExtension { + // ... + onFormEvent(formId, message) { + // Obtain the detail parameter passed in the message event. + let msg = JSON.parse(message) + if (msg.params.detail === "message detail") { + // Do something. + // console.log("message info:" + msg.params.detail) + } + } + // ... + }; + ``` + diff --git a/en/application-dev/application-models/widget-switch.md b/en/application-dev/application-models/widget-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..8d9823385a8a05f71c742327dc966054427a6718 --- /dev/null +++ b/en/application-dev/application-models/widget-switch.md @@ -0,0 +1,48 @@ +# Widget Switching + + +Widget switching involves the following parts: + + +- Widget UI layout: Both the FA model and stage model use the web-like paradigm to develop the widget UI layout. Therefore, the UI layout of a widget in the FA model can be directly reused in the stage mode. +- Widget configuration file: Widgets are configured in the **config.json** file in the FA model and in **module.json5** and **form_config.json** files in the stage model (as shown in Figure 1 and Figure 2). +- Widget service logic: The widget entry file and lifecycle of the FA model are slightly different from those of the stage model, as shown in Figure 3 and Figure 4. + +| Configuration Item | FA Model | Stage Model | +| ---------------- | ------------------------------------------- | ------------------------------------------------------------ | +| Configuration item location | **formAbility** and **forms** are in the **config.json** file.| **extensionAbilities** (configuration for **formExtensionAbility**) is in the **module.json5** file in the level-1 directory, and **forms** (configuration for **forms** contained in **formExtensionAbility**) is in the **form_config.json** file in the level-2 directory.| +| Widget code path | Specified by **srcPath**, without the file name. | Specified by **srcEntrance**, with the file name. | +| Programming language | **srcLanguage** can be set to **js** or **ets**. | This configuration item is unavailable. Only ets is supported. | +| Whether to enable widgets | formsEnabled | This configuration item is unavailable. The setting of **type** set to **form** means that the widgets are enabled. | +| Ability type | type: service | type: form | +| Level-2 directory configuration tag| This configuration item is unavailable. | **metadata**, which consists of **name**, **value**, and **resource**, where **resource** points to the location of the **form_config.json** file in the level-2 directory.| + + +Figure 1 Entry configuration differences + + +![widget-switch1](figures/widget-switch1.png) + + +Figure 2 Widget configuration differences + + +![widget-switch2](figures/widget-switch2.png) + + +| Item| FA Model| Stage Model| +| -------- | -------- | -------- | +| Entry file| **form.ts** in the directory pointed to by **srcPath**| File pointed to by **srcEntrance**| +| Lifecycle| export default| import FormExtension from '\@ohos.app.form.FormExtensionAbility';
export default class FormAbility extends FormExtension| + + +Figure 3 Entry file differences + + +![widget-switch3](figures/widget-switch3.png) + + +Figure 4 Lifecycle differences (The lifecycle callbacks are the same and require no adjustment.) + + +![widget-switch4](figures/widget-switch4.png) diff --git a/en/application-dev/application-models/window-properties.md b/en/application-dev/application-models/window-properties.md new file mode 100644 index 0000000000000000000000000000000000000000..250476f05f7fc66b5deaa52ee2e4905f8de0edf6 --- /dev/null +++ b/en/application-dev/application-models/window-properties.md @@ -0,0 +1,4 @@ +# Window Properties + + +For details about the APIs for obtaining a window instance and setting window properties, see [Application Window Development (FA Model)](../windowmanager/application-window-fa.md). diff --git a/en/application-dev/application-models/window-switch.md b/en/application-dev/application-models/window-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..379f0282b1e50e856d0010a9087622e2e1363d89 --- /dev/null +++ b/en/application-dev/application-models/window-switch.md @@ -0,0 +1,8 @@ +# window Switching + + +| API in the FA Model| Corresponding d.ts File in the Stage Model| Corresponding API in the Stage Model| +| -------- | -------- | -------- | +| [create(id: string, type: WindowType, callback: AsyncCallback<Window>): void;](../reference/apis/js-apis-window.md#windowcreatedeprecated)
[create(id: string, type: WindowType): Promise<Window>;](../reference/apis/js-apis-window.md#windowcreatedeprecated-1) | \@ohos.window.d.ts | [createSubWindow(name: string, callback: AsyncCallback<Window>): void;](../reference/apis/js-apis-window.md#createsubwindow9)
[createSubWindow(name: string): Promise;](../reference/apis/js-apis-window.md#createsubwindow9-1)
An application developed on the FA model uses **window.create(id, WindowType.TYPE_APP)** to create a subwindow, whereas an application developed on the stage model uses **WindowStage.CreateSubWindow()** to create a subwindow.| +| [getTopWindow(callback: AsyncCallback<Window>): void;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated)
[getTopWindow(): Promise<Window>;](../reference/apis/js-apis-window.md#windowgettopwindowdeprecated-1) | \@ohos.window.d.ts | [getLastWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void;](../reference/apis/js-apis-window.md#windowgetlastwindow9)
[getLastWindow(ctx: BaseContext): Promise<Window>;](../reference/apis/js-apis-window.md#windowgetlastwindow9-1) | + diff --git a/en/application-dev/application-test/Readme.md b/en/application-dev/application-test/Readme-EN.md similarity index 100% rename from en/application-dev/application-test/Readme.md rename to en/application-dev/application-test/Readme-EN.md diff --git a/en/application-dev/connectivity/figures/IPC_RPC_communication.PNG b/en/application-dev/connectivity/figures/IPC_RPC_communication.PNG new file mode 100644 index 0000000000000000000000000000000000000000..63f193ade7b3932279295641a5612bc5720befef Binary files /dev/null and b/en/application-dev/connectivity/figures/IPC_RPC_communication.PNG differ diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index 0eeef8040da8abd9710f3996f0b5f2c65ecf71e2..5512d7a016754c94174fe269d5ed58424a218fb6 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -1,135 +1,316 @@ -# IPC & RPC Development +# IPC & RPC Development Guidelines -## When to Use +## When to Use IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices. -## Available APIs -**Table 1** Native IPC APIs +## Available APIs -| Class/Interface | Function | Description | -| --------------- | -------- | ----------- | -| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | -| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | -| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | +Table 1 Native IPC APIs -## How to Develop +| Class| API| Description| +| -------- | -------- | -------- | +| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr<IRemoteObject> AsObject() | Holder of a remote proxy object. If you call this API on the stub, the **RemoteObject** is returned; if you call this API on the proxy, the proxy object is returned.| +| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Callback used to process a request from the proxy and return the result. Derived classes need to override this API.| +| IRemoteProxy | | Service proxy class, which is derived from the **IRemoteProxy** class.| -**Using Native APIs** -1. Define the IPC interface **ITestAbility**. +## How to Develop - **ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub. +### **Using Native APIs** - ``` - class ITestAbility : public IRemoteBroker { - public: +1. Add dependencies. + + SDK dependency: + + ``` + #IPC scenario + external_deps = [ + "ipc:ipc_single", + ] + + #RPC scenario + external_deps = [ + "ipc:ipc_core", + ] + ``` + + In addition, the refbase implementation on which IPC/RPC depends is stored in **//utils**. Add the dependency on the Utils source code. + + ``` + external_deps = [ + "c_utils:utils", + ] + ``` + +2. Define the IPC interface **ITestAbility**. + + **ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub. + + ```c++ + #include "iremote_broker.h" + + // Define message codes. + const int TRANS_ID_PING_ABILITY = 5 + + const std::string DESCRIPTOR = "test.ITestAbility"; + + class ITestAbility : public IRemoteBroker { + public: // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. - DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); - int TRANS_ID_PING_ABILITY = 1; // Define the message code. + DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR)); virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. - }; - ``` + }; + ``` -2. Define and implement service provider **TestAbilityStub**. +3. Define and implement service provider **TestAbilityStub**. - This class is related to the IPC framework and needs to inherit **IRemoteStub**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. + This class is related to the IPC framework and needs to inherit **IRemoteStub<ITestAbility>**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. - ``` - class TestAbilityStub : public IRemoteStub { - public: - virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - int TestPingAbility(const std::u16string &dummy) override; + ```c++ + #include "iability_test.h" + #include "iremote_stub.h" + + class TestAbilityStub : public IRemoteStub { + public: + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int TestPingAbility(const std::u16string &dummy) override; }; - - int TestServiceStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - switch (code) { - case TRANS_ID_PING_ABILITY: { - std::u16string dummy = data.ReadString16(); - int result = TestPingAbility(dummy); - reply.WriteInt32(result); - return 0; - } - default: - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - } - ``` - -3. Define the **TestAbility** class that implements functions for the stub. - - ``` - class TestAbility : public TestAbilityStub { - public: - int TestPingAbility(const std::u16string &dummy); - } - - int TestAbility::TestPingAbility(const std::u16string &dummy) { - return 0; - } - ``` - -4. Define and implement **TestAbilityProxy**. - - This class is implemented on the proxy and inherits **IRemoteProxy**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. - - ``` - class TestAbilityProxy : public IRemoteProxy { - public: - explicit TestAbilityProxy(const sptr &impl); - int TestPingService(const std::u16string &dummy) override; - private: - static inline BrokerDelegator delegator_; // Use the iface_cast macro. - } - - TestAbilityProxy::TestAbilityProxy(const sptr &impl) - : IRemoteProxy(impl) - { - } - - int TestAbilityProxy::TestPingService(const std::u16string &dummy) { - MessageOption option; - MessageParcel dataParcel, replyParcel; - dataParcel.WriteString16(dummy); - int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); - int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; - return result; - } - ``` - -5. Register and start an SA. - - Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA. - - ``` - // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - samgr->AddSystemAbility(saId, new TestAbility()); - - // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - ISystemAbilityManager::SAExtraProp saExtra; - saExtra.isDistributed = true; // Set a distributed SA. - int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra); - ``` - -6. Obtain the SA. - - Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance. - - ``` - // Obtain the proxy of the SA registered on the local device. - sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(saId); - sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. - - // Obtain the proxies of the SAs registered with other devices. - sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(saId, deviceId); // deviceId identifies a device. - sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. - ``` + + int TestAbilityStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + switch (code) { + case TRANS_ID_PING_ABILITY: { + std::u16string dummy = data.ReadString16(); + int result = TestPingAbility(dummy); + reply.WriteInt32(result); + return 0; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + ``` + +4. Define the **TestAbility** class that implements functions for the stub. + + ```c++ + #include "iability_server_test.h" + + class TestAbility : public TestAbilityStub { + public: + int TestPingAbility(const std::u16string &dummy); + } + + int TestAbility::TestPingAbility(const std::u16string &dummy) { + return 0; + } + ``` + +5. Define and implement **TestAbilityProxy**. + + This class is implemented on the proxy and inherits **IRemoteProxy<ITestAbility>**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. + + ```c++ + #include "iability_test.h" + #include "iremote_proxy.h" + #include "iremote_object.h" + + class TestAbilityProxy : public IRemoteProxy { + public: + explicit TestAbilityProxy(const sptr &impl); + int TestPingAbility(const std::u16string &dummy) override; + private: + static inline BrokerDelegator delegator_; // Use the iface_cast macro. + } + + TestAbilityProxy::TestAbilityProxy(const sptr &impl) + : IRemoteProxy(impl) + { + } + + int TestAbilityProxy::TestPingAbility(const std::u16string &dummy){ + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.WriteString16(dummy); + int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; + } + ``` + +6. Register and start an SA. + + Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA. + + ```c++ + // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + samgr->AddSystemAbility(saId, new TestAbility()); + + // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + ISystemAbilityManager::SAExtraProp saExtra; + saExtra.isDistributed = true; // Set a distributed SA. + int result = samgr->AddSystemAbility(saId, new TestAbility(), saExtra); + ``` + +7. Obtain the SA. + + Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance. + + ```c++ + // Obtain the proxy of the SA registered on the local device. + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + sptr remoteObject = samgr->GetSystemAbility(saId); + sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. + + // Obtain the proxy of the SA registered with any other devices. + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + + // networkId is the device identifier and can be obtained through GetLocalNodeDeviceInfo. + sptr remoteObject = samgr->GetSystemAbility(saId, networkId); + sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. + ``` + +### **Using JS APIs** + +1. Add dependencies. + + ```ts + import rpc from "@ohos.rpc" + import featureAbility from "@ohos.ability.featureAbility" + ``` + + + +2. Bind the desired ability. + + Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **deviceManager**. Then, construct the **connect** variable, and specify the callback that is called when the binding is successful, the binding fails, or the ability is disconnected. After that, call the API provided by **featureAbility** to bind an ability. + + ```ts + import rpc from "@ohos.rpc" + import featureAbility from "@ohos.ability.featureAbility" + + let proxy = null + let connectId = null + + // Bind the ability on a single device. + let want = { + // Enter the bundle name and ability name. + "bundleName": "ohos.rpc.test.server", + "abilityName": "ohos.rpc.test.server.ServiceAbility", + } + let connect = { + onConnect:function(elementName, remote) { + proxy = remote + }, + onDisconnect:function(elementName) { + }, + onFailed:function() { + proxy = null + } + } + connectId = featureAbility.connectAbility(want, connect) + + // If you're binding the ability across devices, use deviceManager to obtain the network ID of the target device. + import deviceManager from '@ohos.distributedHardware.deviceManager' + function deviceManagerCallback(deviceManager) { + let deviceList = deviceManager.getTrustedDeviceListSync() + let networkId = deviceList[0].networkId + let want = { + "bundleName": "ohos.rpc.test.server", + "abilityName": "ohos.rpc.test.service.ServiceAbility", + "networkId": networkId, + "flags": 256 + } + connectId = featureAbility.connectAbility(want, connect) + } + // The first parameter specifies the bundle name of the application, and the second parameter specifies the callback used to return the device ID obtained by using DeviceManager. + deviceManager.createDeviceManager("ohos.rpc.test", deviceManagerCallback) + ``` + + + +3. Process requests sent from the client. + + Call the **onConnect** API to return a proxy object inherited from **rpc.RemoteObject** after the ability is successfully bound. Implement the **onRemoteMessageRequest** API for the proxy object to process requests sent from the client. + + ```ts + onConnect(want: Want) { + var robj:rpc.RemoteObject = new Stub("rpcTestAbility") + return robj + } + class Stub extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor) + } + onRemoteMessageRequest(code, data, reply, option) { + // Process requests sent from the client based on the code. + return true + } + } + ``` + + + +4. Process responses sent from the server. + + Obtain the proxy object from the **onConnect** callback, call **sendRequestAsync** to send a request, and receive the response using a callback or a promise (an object representing the eventual completion or failure of an asynchronous operation and its result value). + + ```ts + // Use a promise. + let option = new rpc.MessageOption() + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + // Write parameters to data. + proxy.sendRequestAsync(1, data, reply, option) + .then(function(result) { + if (result.errCode != 0) { + console.error("send request failed, errCode: " + result.errCode) + return + } + // Read the result from result.reply. + }) + .catch(function(e) { + console.error("send request got exception: " + e) + } + .finally(() => { + data.reclaim() + reply.reclaim() + }) + + // Use a callback. + function sendRequestCallback(result) { + try { + if (result.errCode != 0) { + console.error("send request failed, errCode: " + result.errCode) + return + } + // Read the result from result.reply. + } finally { + result.data.reclaim() + result.reply.reclaim() + } + } + let option = new rpc.MessageOption() + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + // Write parameters to data. + proxy.sendRequest(1, data, reply, option, sendRequestCallback) + ``` + +5. Tear down the connection. + Use the API provided by **featureAbility** to tear down the connection when the communication is over. + ```ts + import rpc from "@ohos.rpc" + import featureAbility from "@ohos.ability.featureAbility" + function disconnectCallback() { + console.info("disconnect ability done") + } + featureAbility.disconnectAbility(connectId, disconnectCallback) + ``` diff --git a/en/application-dev/connectivity/ipc-rpc-overview.md b/en/application-dev/connectivity/ipc-rpc-overview.md index e75536863b1ae1b5c5371f51b0d7e26e4db97ed6..29fdec791c9a6b96d2ae2138b47a9b8dc48c050b 100755 --- a/en/application-dev/connectivity/ipc-rpc-overview.md +++ b/en/application-dev/connectivity/ipc-rpc-overview.md @@ -3,20 +3,42 @@ ## Basic Concepts -Inter-process communication (IPC) and remote procedure call (RPC) are used to implement cross-process communication. IPC uses the Binder driver to implement inter-process communication within a device, whereas RPC uses the intelligent software bus driver to implement inter-process communication across devices. +The inter-process communication (IPC) and remote procedure call (RPC) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the DSoftBus driver to implement cross-process communication across devices. -IPC and RPC generally use the client-server model for communication. The client (service requester) obtains the proxy of the server (service provider) and uses this proxy to read and write data. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides interfaces for clients. To interact with an SA, the client must obtain the proxy of the SA from SAMgr. +The reason why cross-process communication is needed is that each process has its own independent resources and memory space and one process is not allowed to access the resources and memory space of other processes. IPC and RPC usually use the client-server model, where the client (service requester, that is, the process that requests a service) obtains the proxy of the server (service provider, that is, the process that provides the service) and uses the proxy to read and write data to implement data communication across processes. More specifically, the client constructs a proxy object of the server. The proxy object has the same functions as the server. To access a certain API of the server, you only need to access the corresponding API in the proxy object. The proxy object sends the request to the server, and the server processes the received request and returns the processing result to the proxy object through the driver. Then, the proxy object forwards the processing result to the client. The server registers system abilities (SAs) with the system ability manager (SAMgr), which manages the SAs and provides APIs for clients. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr. -In OpenHarmony documents, proxy represents the service requester, and stub represents the service provider. +In the following sections, proxy represents the service requester, and stub represents the service provider. + +![IPC&RPC communication mechanisms](figures/IPC_RPC_communication.PNG) ## Constraints -- The data transmitted for inter-process communication within a device cannot exceed 1 MB. If more data needs to be transmitted, use the anonymous shared memory. +- During cross-process communication within a single device, the maximum amount of data to be transmitted is about 1 MB. If the amount of data to be transmitted exceeds this limit, use the [anonymous shared memory](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-rpc.md#ashmem8). +- Subscription to death notifications of anonymous stub objects (not registered with SAMgr) is prohibited in RPC. +- During cross-process communication across processes, a proxy object cannot be passed back to the device that hosts the stub object pointed by the proxy object. That is, the proxy object pointing to the stub object of the remote device cannot be passed across processes twice on the local device. + +## **Recommendations** + +First, compile an API class and define message codes in the API class for both communication parties to identify operations. Unimplemented APIs are allowed in the API class because it must be inherited by both communication parties and its inheritance classes cannot be abstract classes. When inheriting the API class, both communication parties must implement the unimplemented APIs, so as to make sure that the inheritance classes are not abstract classes. + +Then, implement the API class specific to the stub, and override the **AsObject** and **OnRemoteRequest** APIs. In addition, compile the proxy to implement the APIs in the API class and override the **AsObject** API. You can also encapsulate an additional API for calling **SendRequest** to send data to the peer. + +After the preceding operations are done, register a system ability (SA) with SAMgr. Note that the registration should be completed in the process that hosts the stub. Then, obtain the proxy from SAMgr as needed to implement cross-process communication with the stub. + +Related steps are as follows: + +- Implementing the API class: Inherit **IRemoteBroker**, define message codes, and declare APIs that are not implemented in the API class. + +- Implementing the service provider (stub): Inherit **IRemoteStub** or **RemoteObject**, and override the **AsObject** and **OnRemoteRequest** APIs. + +- Implementing the service requester (proxy): Inherit **IRemoteProxy** or **RemoteProxy**, override the **AsObject** API, and encapsulate the required API to call **SendRequest**. + +- Registering the SA: Apply for a unique ID for the SA, and register the SA with SAMgr. -- The cross-device proxy object cannot be passed to the device hosting the stub object pointed by this proxy object. +- Obtaining the SA: Obtain the proxy based on the SA ID and device ID, and use the proxy to communicate with the remote end. ## Related Modules -[Distributed Scheduler](https://gitee.com/openharmony/ability_dmsfwk) +[Distributed Ability Manager Service Framework](https://gitee.com/openharmony/ability_dmsfwk) diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 8d9365d6bbba940bb85d9ac7493b7069c48845eb..4168d4645a8dd122eaf331017a91da0d8ecc2594 100755 --- a/en/application-dev/connectivity/subscribe-remote-state.md +++ b/en/application-dev/connectivity/subscribe-remote-state.md @@ -1,30 +1,172 @@ # Subscribing to State Changes of a Remote Object -IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** callback and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. +IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. -Note that the proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. +## When to Use +This subscription mechanism is applicable when the local proxy object needs to detect death of the process hosting the remote stub object or network detach of the device hosting the remote stub object. When the proxy detects death of the remote stub object, the proxy can clear local resources. Currently, IPC supports death notification for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr. +## **Using Native APIs** -## **Development Using Native APIs** +| API| Return Value Type| Feature Description| +| -------- | -------- | -------- | +| AddDeathRecipient(const sptr\ &recipient); | bool | Adds a recipient for death notifications of a remote stub object.| +| RemoveDeathRecipient(const sptr\ &recipient); | bool | Removes the recipient for death notifications of a remote stub object.| +| OnRemoteDied(const wptr\ &object); | void | Called when the remote stub object dies.| -| API| Description| -| -------- | -------- | -| AddDeathRecipient(const sptr\ &recipient); | Adds a recipient for death notifications of a remote stub object.| -| RemoveDeathRecipient(const sptr\ &recipient); | Removes the recipient for death notifications of a remote stub object.| -| OnRemoteDied(const wptr\ &object); | Called when the remote stub object dies.| +### Sample Code +```C++ +#include "iremote_broker.h" +#include "iremote_stub.h" -## Sample Code +// Define message codes. +enum { + TRANS_ID_PING_ABILITY = 5, + TRANS_ID_REVERSED_MONITOR +}; +const std::string DESCRIPTOR = "test.ITestAbility"; + +class ITestService : public IRemoteBroker { +public: + // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. + DECLARE_INTERFACE_DESCRIPTOR(to_utf16(DESCRIPTOR)); + virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. +}; + +class TestServiceProxy : public IRemoteProxy { +public: + explicit TestAbilityProxy(const sptr &impl); + virtual int TestPingAbility(const std::u16string &dummy) override; + int TestAnonymousStub(); +private: + static inline BrokerDelegator delegator_; // Use the iface_cast macro. +}; + +TestServiceProxy::TestServiceProxy(const sptr &impl) + : IRemoteProxy(impl) +{ +} + +int TestServiceProxy::TestPingAbility(const std::u16string &dummy){ + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.WriteString16(dummy); + int error = PeerHolder::Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; +} ``` + + + + +```c++ +#include "iremote_object.h" + class TestDeathRecipient : public IRemoteObject::DeathRecipient { public: virtual void OnRemoteDied(const wptr& remoteObject); } + +void TestDeathRecipient::OnRemoteDied(const wptr& remoteObject) +{ +} +``` + +```c++ +sptr object = new IPCObjectProxy(1, to_utf16(DESCRIPTOR)); sptr deathRecipient (new TestDeathRecipient());// Construct a death notification recipient. -bool result = proxy->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications. -result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications. +bool result = object->AddDeathRecipient(deathRecipient); // Add a recipient for death notifications. +result = object->RemoveDeathRecipient(deathRecipient); // Remove the recipient for death notifications. +``` + +## **Using JS APIs** + +| API | Return Value Type| Feature Description | +| -------------------- | ---------- | ------------------------------------------------------------ | +| addDeathRecippient | boolean | Adds a recipient for death notifications of the remote object, including death notifications of the remote proxy.| +| removeDeathRecipient | boolean | Removes the recipient for death notifications of the remote object. | +| onRemoteDied | void | Called to perform subsequent operations when a death notification of the remote object is received.| + +### Sample Code + +```ts +import FA from "@ohos.ability.featureAbility"; +let proxy; +let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } +}; +let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.EntryAbility", +}; +FA.connectAbility(want, connect); +class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } +} +let deathRecipient = new MyDeathRecipient(); +proxy.addDeathRecippient(deathRecipient, 0); +proxy.removeDeathRecipient(deathRecipient, 0); +``` + +## Reverse Death Notification (Anonymous Stub) + +Forward dead notification is a mechanism that allows the proxy to detect death notifications of the stub. To achieve reverse dead notification, we can leverage the forward dead notification mechanism to allow the stub to detect death notifications of the proxy. + +Suppose there are two processes, A (the process hosting the original stub) and B (the process hosting the original proxy). After obtaining the proxy object of process A, process B creates an anonymous stub object (that is, a stub object not registered with SAMgr), which can be called a callback stub. Then, process B calls **SendRequest** to send the callback stub to the original stub of process A. As a result, process A obtains the callback proxy of process B. When process B dies or the device hosting process B detaches from the network, the callback stub dies. The callback proxy detects the death of the callback stub and sends a death notification to the original stub. In this way, reverse death notification is implemented. + +> NOTE +> - Reverse death notification can only be used for cross-process communication within a device. +> - When an anonymous stub object is not pointed by any proxy, the kernel automatically reclaims the object. + +### Sample Code + +```c++ +// Proxy +int TestAbilityProxy::TestAnonymousStub() +{ + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.UpdateDataVersion(Remote()); + dataParcel.WriteRemoteObject(new TestAbilityStub()); + int error = Remote()->SendRequest(TRANS_ID_REVERSED_MONITOR,dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; +} + +// Stub + +int TestAbilityStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + switch (code) { + case TRANS_ID_REVERSED_MONITOR: { + sptr obj = data.ReadRemoteObject(); + if (obj == nullptr) { + reply.WriteInt32(ERR_NULL_OBJECT); + return ERR_NULL_OBJECT; + } + bool result = obj->AddDeathRecipient(new TestDeathRecipient()); + result ? reply.WriteInt32(ERR_NONE) : reply.WriteInt32(-1); + break; + } + default: + break; + } + return ERR_NONE; +} ``` diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 064c3e393fe27cedceb1f3f7d2d1e03b8ec22db6..95001df839e0d5ef56bc12126f0fdcd59c72db30 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share |query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.| |delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.| -For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). +For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md). **Table 2** APIs of the data consumer @@ -29,7 +29,7 @@ For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataS ## When to Use -There are two roles in **DataShare**: +There are two roles in **DataShare**: - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data consumer: accesses the data provided by the provider using **DataShareHelper**. @@ -108,8 +108,8 @@ Examples are given below. | ------------ | ------------------------------------------------------------ | | "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**.| + | "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**. | **module.json5 example** @@ -129,10 +129,10 @@ Examples are given below. ### Data Consumer Application Development -1. Import the dependencies. +1. Import dependencies. ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; import dataShare from '@ohos.data.dataShare'; import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` @@ -150,7 +150,7 @@ Examples are given below. let dsHelper; let abilityContext; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { abilityContext = this.context; dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{ @@ -180,7 +180,7 @@ Examples are given below. dsHelper.query(dseUri, predicates, valArray, (err, data) => { console.log("dsHelper query result: " + data); }); - // Delete data. + // Delete specified data. dsHelper.delete(dseUri, predicates, (err, data) => { console.log("dsHelper delete result: " + data); }); diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 53e3ca5aeaa25ecea55f3e27272043e6b533e594..df633d8449281b12557bb3d39f333f97148af1a4 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ A relational database (RDB) store allows you to operate local data with or witho ## Available APIs -Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). +Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md). ### Creating or Deleting an RDB Store @@ -17,8 +17,8 @@ The following table describes the APIs for creating and deleting an RDB store. | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> | Obtains an **RdbStoreV9** instance. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store. Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported.| -| deleteRdbStoreV9(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: context of the application or function.
- **name**: name of the RDB store to delete.| +| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | Obtains an **RdbStore** object. This API uses a promise to return the result. You can set parameters for the **RdbStore** object based on service requirements and use **RdbStore** APIs to perform data operations.
- **context**: application context.
- **config**: configuration of the RDB store.| +| deleteRdbStore(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: application context.
- **name**: name of the RDB store to delete.| ### Managing Data in an RDB Store @@ -33,29 +33,29 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating Data** - Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicatesV9**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. + 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. **Table 3** API for updating data - | Class | API | Description | + | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | update(values: ValuesBucket, predicates: RdbPredicatesV9): Promise<number> | Updates data based on the specified **RdbPredicatesV9** 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** - Call **delete()** to delete the data that meets the conditions specified by **RdbPredicatesV9**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. + Call **delete()** to delete the data that meets the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. **Table 4** API for deleting data - | Class | API | Description | + | Class | API | Description | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | - | RdbStoreV9 | delete(predicates: RdbPredicatesV9): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **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** @@ -66,50 +66,48 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 5** APIs for querying data - -| Class | API | Description | -| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | query(predicates: RdbPredicatesV9, columns?: Array<string>): Promise<ResultSetV9> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| -| RdbStoreV9 | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSetV9> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| -| RdbStoreV9 | remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicatesV9** that specifies the query conditions.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | Class | API | Description | + | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates -The **RDB** module provides **RdbPredicatesV9** for you to set database operation conditions. +The **RDB** module provides **RdbPredicates** for you to set database operation conditions. -The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). +The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-relationalStore.md#rdbpredicates). **Table 6** APIs for using RDB store predicates -| Class | API | Description | +| Class | API | Description | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbPredicatesV9 | equalTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | -| RdbPredicatesV9 | notEqualTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | -| RdbPredicatesV9 | or(): RdbPredicatesV9 | Adds the OR condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the OR condition. | -| RdbPredicatesV9 | and(): RdbPredicatesV9 | Adds the AND condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the AND condition. | -| RdbPredicatesV9 | contains(field: string, value: string): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. | +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the OR condition.| +| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| ### Using the Result Set -You can use the APIs provided by **ResultSetV9** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. +You can use the APIs provided by **ResultSet** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. -For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md). +For details about how to use **ResultSet** APIs, see [ResultSet](../reference/apis/js-apis-data-relationalStore.md#resultset). -> **NOTICE** -> +> **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set | Class | API | Description | | ----------- | ---------------------------------------- | ------------------------------------------ | -| ResultSetV9 | goToFirstRow(): boolean | Moves to the first row of the result set. | -| ResultSetV9 | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | -| ResultSetV9 | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| -| ResultSetV9 | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | -| ResultSetV9 | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | -| ResultSetV9 | close(): void | Closes the result set. | +| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. | +| ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | +| ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | +| ResultSet | close(): void | Closes the result set. | @@ -117,7 +115,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis > **NOTE** > -> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore V9**. +> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore**. > - The devices must be connected over network before the distributed tables are used. For details about the APIs and usage, see [Device Management](../reference/apis/js-apis-device-manager.md). **Setting Distributed Tables** @@ -126,7 +124,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** @@ -136,7 +134,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -144,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** @@ -152,7 +150,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -160,7 +158,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.| +| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.| ### Backing Up and Restoring an RDB Store @@ -170,7 +168,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| +| RdbStore | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| **Restoring an RDB Store** @@ -178,17 +176,17 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| +| RdbStore | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| -**Transaction** +### Transaction Table 15 Transaction APIs | Class | API | Description | | -------- | ----------------------- | --------------------------------- | -| RdbStoreV9 | beginTransaction(): void | Starts the transaction before executing SQL statements.| -| RdbStoreV9 | commit(): void | Commits the executed SQL statements. | -| RdbStoreV9 | rollBack(): void | Rolls back the SQL statements that have been executed. | +| RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.| +| RdbStore | commit(): void | Commits the executed SQL statements. | +| RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. | ## How to Develop @@ -203,27 +201,27 @@ Table 15 Transaction APIs FA model: ```js - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext() const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIGV9 = { name: "RdbTest.db", + const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` Stage model: ```ts - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // Obtain the context. - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; let context = null - class MainAbility extends Ability { + class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { context = this.context } @@ -231,10 +229,10 @@ Table 15 Transaction APIs const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIGV9 = { name: "rdbstore.db", + const STORE_CONFIG = { name: "rdbstore.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` @@ -248,14 +246,29 @@ Table 15 Transaction APIs The sample code is as follows: ```js - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - let insertPromise = rdbStoreV9.insert("test", valueBucket) + let insertPromise = rdbStore.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() + } ``` 3. Query data. - (1) Create an **RdbPredicatesV9** object to specify query conditions. + (1) Create an **RdbPredicates** object to specify query conditions. (2) Call the **query()** API to query data. @@ -264,17 +277,17 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let predicatesV9 = new data_rdb.RdbPredicatesV9("test"); - predicatesV9.equalTo("name", "Tom") - let promisequery = rdbStoreV9.query(predicatesV9) - promisequery.then((resultSetV9) => { - resultSetV9.goToFirstRow() - const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) - const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) - const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) - const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) - const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) - resultSetV9.close() + let predicates = new data_rdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let promisequery = rdbStore.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() }) ``` @@ -302,7 +315,7 @@ Table 15 Transaction APIs context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { console.info(`result.requestCode=${result.requestCode}`) }) - let promise = rdbStoreV9.setDistributedTables(["test"]) + let promise = rdbStore.setDistributedTables(["test"]) promise.then(() => { console.info("setDistributedTables success.") }).catch((err) => { @@ -312,7 +325,7 @@ Table 15 Transaction APIs 5. Synchronize data across devices. - (1) Construct an **RdbPredicatesV9** object to specify remote devices within the network to be synchronized. + (1) Construct an **RdbPredicates** object to specify remote devices within the network to be synchronized. (2) Call **rdbStore.sync()** to synchronize data. @@ -321,9 +334,9 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let predicateV9 = new data_rdb.RdbPredicatesV9('test') - predicateV9.inDevices(['12345678abcde']) - let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicateV9) + let predicate = new data_rdb.RdbPredicates('test') + predicate.inDevices(['12345678abcde']) + let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { @@ -350,7 +363,7 @@ Table 15 Transaction APIs } try { - rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('register observer failed') } @@ -365,8 +378,8 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let tableName = rdbStoreV9.obtainDistributedTableName(deviceId, "test"); - let resultSetV9 = rdbStoreV9.querySql("SELECT * FROM " + tableName) + let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); + let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` 8. Query data of a remote device. @@ -379,17 +392,17 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let rdbPredicateV9 = new data_rdb.RdbPredicatesV9('employee') - predicatesV9.greaterThan("id", 0) - let promiseQuery = rdbStoreV9.remoteQuery('12345678abcde', 'employee', rdbPredicateV9) - promiseQuery.then((resultSetV9) => { - while (resultSetV9.goToNextRow()) { - let idx = resultSetV9.getLong(0); - let name = resultSetV9.getString(1); - let age = resultSetV9.getLong(2); + let rdbPredicate = new data_rdb.RdbPredicates('employee') + predicates.greaterThan("id", 0) + let promiseQuery = rdbStore.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); } - resultSetV9.close(); + resultSet.close(); }).catch((err) => { console.info("failed to remoteQuery, err: " + err) }) @@ -402,7 +415,7 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let promiseBackup = rdbStoreV9.backup("dbBackup.db") + let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(() => { console.info('Backup success.') }).catch((err) => { @@ -414,7 +427,7 @@ Table 15 Transaction APIs The sample code is as follows: ```js - let promiseRestore = rdbStoreV9.restore("dbBackup.db") + let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { console.info('Restore success.') }).catch((err) => { diff --git a/en/application-dev/device/device-location-geocoding.md b/en/application-dev/device/device-location-geocoding.md deleted file mode 100644 index c29b1a0ed206cde027d3002d8b110722a473bfda..0000000000000000000000000000000000000000 --- a/en/application-dev/device/device-location-geocoding.md +++ /dev/null @@ -1,81 +0,0 @@ -# Geocoding and Reverse Geocoding Capabilities - - -## When to Use - -Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. - -The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address. - - -## Available APIs - -The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md). - - **Table1** APIs for geocoding and reverse geocoding - -| API | Description | -| -------- | -------- | -| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result.| -| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result.| -| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>> | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. | - - -## How to Develop - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> -> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network. - -1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. - - ```ts - import geolocation from '@ohos.geolocation'; - ``` - -2. Query whether geocoder service is available. - - Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3. - ```ts - geolocation.isGeoServiceAvailable((err, data) => { - if (err) { - console.log('isGeoServiceAvailable err: ' + JSON.stringify(err)); - } else { - console.log('isGeoServiceAvailable data: ' + JSON.stringify(data)); - } - }); - ``` - -3. Obtain the conversion result. - - Call **getAddressesFromLocation** to convert coordinates into geographical location information. - - ```ts - var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; - geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); - } - }); - ``` - - Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). - - Call **getAddressesFromLocationName** to convert geographic description into coordinates. - - ```ts - var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; - geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { - if (err) { - console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); - } else { - console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); - } - }); - ``` - - Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). - - To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**. diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md deleted file mode 100644 index 235ef590861ceb1a8b2f9b878954ea3d3cecccc9..0000000000000000000000000000000000000000 --- a/en/application-dev/device/device-location-info.md +++ /dev/null @@ -1,146 +0,0 @@ -# Obtaining Device Location Information - - -## When to Use - -You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device. - -Real-time location of the device is recommended for location-sensitive services. If you want to lower power consumption when the real-time location of the device is not needed, you may consider obtaining the last known location of the device. - - -## Available APIs - -For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geolocation.md). - -## How to Develop - -To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md). - -1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. - The system provides the following location permissions: - - ohos.permission.LOCATION - - - ohos.permission.APPROXIMATELY_LOCATION - - - ohos.permission.LOCATION_IN_BACKGROUND - - If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: - - API versions earlier than 9: Apply for **ohos.permission.LOCATION**. - - API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. - - | Target API Level| Location Permission| Permission Application Result| Location Accuracy| - | -------- | -------- | -------- | -------- | - | Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| - | 9 and later| ohos.permission.LOCATION | Failure| No location obtained| - | 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| - | 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| - - If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. - - You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md). - -2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. - - ``` - import geolocation from '@ohos.geolocation'; - ``` - -3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
- **Method 1:** - - To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported. - - - ``` - export enum LocationRequestScenario { - UNSET = 0x300, - NAVIGATION, - TRAJECTORY_TRACKING, - CAR_HAILING, - DAILY_LIFE_SERVICE, - NO_POWER, - } - ``` - - - **Table 2** Common use cases of the location function - - | Use Case | Constant | Description | - | ------------ | ------------------- | ------------------------------------------------------------ | - | Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - - Sample code for initializing **requestInfo** for navigation: - - ```ts - var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - ``` - - **Method 2:** - - If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system. - - - ```ts - export enum LocationRequestPriority { - UNSET = 0x200, - ACCURACY, - LOW_POWER, - FIRST_FIX, - } - ``` - - - **Table 3** Location priority policies - - | Policy | Constant | Description | - | ------------------ | -------------- | ------------------------------------------------------------ | - | Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.| - - Sample code for initializing **requestInfo** for the location accuracy priority policy: - - ```ts - var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; - ``` - -4. Instantiate the **Callback** object for the system to report location results. - Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic. - - ```ts - var locationChange = (location) => { - console.log('locationChanger: data: ' + JSON.stringify(location)); - }; - ``` - -5. Start device location. - - ```ts - geolocation.on('locationChange', requestInfo, locationChange); - ``` - -6. (Optional) Stop device location. - - ```ts - geolocation.off('locationChange', locationChange); - ``` - -If your application does not need the real-time device location, it can use the last known device location cached in the system instead. - - ```ts - geolocation.getLastLocation((err, data) => { - if (err) { - console.log('getLastLocation: err: ' + JSON.stringify(err)); - } else { - console.log('getLastLocation: data: ' + JSON.stringify(data)); - } - }); - ``` - - To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user. diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md deleted file mode 100644 index a26f0c5a7003a14c13cf4fc697e3a55a202f1eec..0000000000000000000000000000000000000000 --- a/en/application-dev/device/device-location-overview.md +++ /dev/null @@ -1,48 +0,0 @@ -# Location Overview - - -People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices. - - -With the location awareness capability offered by , mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users. - - -Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording. - - -## Basic Concepts - -Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors. - -- **Coordinate** - - A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - -- **GNSS positioning** - GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - -- **Base station positioning** - - Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. - -- **WLAN or Bluetooth positioning** - - WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. - - -## Working Principles - -Location awareness is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a location request to the system and stop the location request when the service scenario ends. In this process, the system reports the location information to the application on a real-time basis. - - -## Limitations and Constraints - -Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application. - -Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information. - -## Samples - -The following sample is provided to help you better understand how to develop location services: - --[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) diff --git a/en/application-dev/device/inputdevice-guidelines.md b/en/application-dev/device/inputdevice-guidelines.md index 1037520e553246d42d2da80f572637af310b4adc..da6eef71d750b74e01d1ea8a9eaaf49b1bf598cb 100644 --- a/en/application-dev/device/inputdevice-guidelines.md +++ b/en/application-dev/device/inputdevice-guidelines.md @@ -16,8 +16,8 @@ The following table lists the common APIs for input device management. For detai | Instance| API | Description| | ----------- | ------------------------------------------------------------ | -------------------------- | -| inputDevice | function getDeviceList(callback: AsyncCallback\>): void; | Obtains the list of input devices.| -| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\): void; | Obtains the keyboard type of the input device.| +| inputDevice | function getDeviceList(): Promise\>; | Obtains the list of input devices.| +| inputDevice | function getKeyboardType(deviceId: number): Promise\; | Obtains the keyboard type of the input device.| | inputDevice | function on(type: "change", listener: Callback\): void; | Enables listening for device hot swap events.| | inputDevice | function off(type: "change", listener?: Callback\): void; | Disables listening for device hot swap events.| @@ -40,8 +40,8 @@ try { // 1. Obtain the list of input devices and check whether a physical keyboard is connected. inputDevice.getDeviceList().then(data => { for (let i = 0; i < data.length; ++i) { - inputDevice.getKeyboardType(data[i]).then(res => { - if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) { + inputDevice.getKeyboardType(data[i]).then(type => { + if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) { // The physical keyboard is connected. isPhysicalKeyboardExist = true; } @@ -51,9 +51,9 @@ try { // 2. Listen for device hot swap events. inputDevice.on("change", (data) => { console.log(`Device event info: ${JSON.stringify(data)}`); - inputDevice.getKeyboardType(data.deviceId, (error, type) => { + inputDevice.getKeyboardType(data.deviceId).then((type) => { console.log("The keyboard type is: " + type); - if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { + if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { // The physical keyboard is inserted. isPhysicalKeyboardExist = true; } else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { diff --git a/en/application-dev/device/pointerstyle-guidelines.md b/en/application-dev/device/pointerstyle-guidelines.md index d8ceab11829f1d5e717a61ec53ecfec19261226d..06a904a5c5ed3a52dba9bf93bc0fa5a9e8a48690 100644 --- a/en/application-dev/device/pointerstyle-guidelines.md +++ b/en/application-dev/device/pointerstyle-guidelines.md @@ -7,7 +7,7 @@ Mouse pointer management provides the functions such as displaying or hiding the ## Modules to Import ```js -import inputDevice from '@ohos.multimodalInput.pointer'; +import pointer from '@ohos.multimodalInput.pointer'; ``` ## Available APIs diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 768866b4974eb59a81aa3d17f9d099d03fbdc415..56e63cd47e1267a1acb08b240162dd96396c2215 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -14,11 +14,10 @@ The following table lists the USB APIs currently available. For details, see the | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | -| requestRight(deviceName: string): Promise\ | Requests the temporary permission for a given application to access the USB device. | -| removeRight(deviceName: string): boolean | Removes the permission for a given application to access the USB device. | -| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device information returned by `getDevices()`. | -| getDevices(): Array> | Obtains the USB device list. | +| hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions. | +| requestRight(deviceName: string): Promise\ | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. | +| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device list returned by `getDevices()`. | +| getDevices(): Array> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. | @@ -37,7 +36,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ```js // Import the USB API package. - import usb from '@ohos.usb'; + import usb from '@ohos.usbV9'; // Obtain the USB device list. let deviceList = usb.getDevices(); /* @@ -82,16 +81,17 @@ You can set a USB device as the USB host to connect to other USB devices for dat number: 1, type: 3, interfaceId: 0, - } - ] - } - ] - } - ] - } - ] + } + ] + } + ] + } + ] + } + ] */ ``` + 2. Obtain the device operation permissions. diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index af9e5d190ab515b61be1c7441d72e264c87ca310..b8a4496e09420b3a7557e5c8b8996deaf14ce1c9 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,14 +1,8 @@ # DFX -- Application Event Logging - - [Overview of Application Event Logging](hiappevent-overview.md) - - [Development of Application Event Logging](hiappevent-guidelines.md) -- Performance Tracing - - [Overview of Performance Tracing](hitracemeter-overview.md) - - [Development of Performance Tracing](hitracemeter-guidelines.md) -- Distributed Call Chain Tracing - - [Overview of Distributed Call Chain Tracing](hitracechain-overview.md) - - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) +- [Development of Application Event Logging](hiappevent-guidelines.md) +- [Development of Performance Tracing](hitracemeter-guidelines.md) +- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) - Error Management - [Development of Error Manager](errormanager-guidelines.md) - [Development of Application Recovery](apprecovery-guidelines.md) diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index 835a6ab9ce3c0beacd19f7c76f5a1eec68bf36cd..631445b862097d5aa71320ff154d6e235660a95e 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -48,28 +48,28 @@ var callback = { export default class MainAbility extends Ability { onCreate(want, launchParam) { console.log("[Demo] MainAbility onCreate") + registerId = errorManager.registerErrorObserver(callback); globalThis.abilityWant = want; } onDestroy() { console.log("[Demo] MainAbility onDestroy") + errorManager.unregisterErrorObserver(registerId, (result) => { + console.log("[Demo] result " + result.code + ";" + result.message) + }); } onWindowStageCreate(windowStage) { // Main window is created for this ability. console.log("[Demo] MainAbility onWindowStageCreate") - globalThis.registerObserver = (() => { - registerId = errorManager.registerErrorObserver(callback); - }) - - globalThis.unRegisterObserver = (() => { - errorManager.unregisterErrorObserver(registerId, (result) => { - console.log("[Demo] result " + result.code + ";" + result.message) - }); - }) - - windowStage.setUIContent(this.context, "pages/index", null) + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)) + }); } onWindowStageDestroy() { diff --git a/en/application-dev/dfx/figures/fault_rectification.png b/en/application-dev/dfx/figures/fault_rectification.png index 63ac5e5f666d5c23c9e9ea3123a9566013336aba..67aa40592f7bcad23e216222e898c1f1327a4efb 100644 Binary files a/en/application-dev/dfx/figures/fault_rectification.png and b/en/application-dev/dfx/figures/fault_rectification.png differ diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 067b9b8c915417b93340ab55bf34a74bca422a3d..6343b502fad6e7572f1d08eee1debd6cd8407061 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -1,12 +1,29 @@ # Development of Application Event Logging -## When to Use +## Introduction -The event logging function helps applications log various information generated during running. +A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage. -## Available APIs +HiAppEvent is a module that provides the event logging function for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of applications. + +## Basic Concepts + +- **Logging** + + Logs changes caused by user operations to provide service data for development, product, and O&M analysis. + +## Event Design Specifications -JS application event logging APIs are provided by the **hiAppEvent** module. +- Event domain: identifies the domain of an event. You are advised to set this parameter to the service module name to differentiate service modules. +- Event name: specifies the name of an event. You are advised to set this parameter to a specific service name to differentiate services. +- Event type: specifies the type of an event. Four event types are supported: + - Behavior event: used to record the daily operation behavior of a user, for example, button click and page redirection. + - Fault event: used to locate and analyze application faults, for example, frame freezing, network disconnection, and call drop. + - Statistical event: used to collect statistics on key application behaviors, for example, usage duration and number of visits. + - Security event: used to record events related to application security, for example, password change and user authorization. +- Event parameter: specifies the parameters of an event. Each event can contain a group of parameters. You are advised to set this parameter to an event attribute or event context to depict the event details. + +## Available APIs The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiviewdfx-hiappevent.md). @@ -17,33 +34,68 @@ The following table provides only a brief description of related APIs. For detai | write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.| | write(AppEventInfo info): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | -**Table 2** APIs for event logging configuration - -| API | Description | -| ------------------------------------ | ---------------------------------------------------- | -| configure(ConfigOption config): void | Sets the configuration options for application event logging.| - **Table 3** APIs for watcher management -| API | Description | -| -------------------------------------------------- | -------------------- | -| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher.| -| removeWatcher(Watcher watcher): void | Removes an event watcher.| +| API | Description | +| -------------------------------------------------- | -------------------------------------------- | +| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher to subscribe to expected application events.| +| removeWatcher(Watcher watcher): void | Adds an event watcher to unsubscribe from expected application events.| -**Table 4** APIs for clearing logging data +## How to Develop -| API | Description | -| ----------------- | -------------------- | -| clearData(): void | Clears local logging data.| +The following example illustrates how to log and subscribe to button click events of users. -## How to Develop +1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **entryability** > **EntryAbility.ts**, and double-click **EntryAbility.ts**. Then, add an event watcher to subscribe to button click events. The complete sample code is as follows: -The following uses a one-time event watcher as an example to illustrate the development procedure. + ```js + import hilog from '@ohos.hilog'; + import Ability from '@ohos.application.Ability' + import Window from '@ohos.window' + import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' + + export default class EntryAbility extends Ability { + onCreate(want, launchParam) { + hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); + hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); + hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); + hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? ''); + + hiAppEvent.addWatcher({ + // Add a watcher. You can customize the watcher name. The system identifies different watchers based on their names. + name: "watcher1", + // Subscribe to application events you are interested in, for example, button click events. + appEventFilters: [{ domain: "button" }], + // Set the subscription callback trigger condition. In this example, a callback is triggered if one event is logged. + triggerCondition: { row: 1 }, + // Implement the subscription callback function to apply custom processing to the event logging data obtained through subscription. + onTrigger: function (curRow, curSize, holder) { + // If the watcher incurs an error while it is working, return a null holder object after recording the error in the log. + if (holder == null) { + hilog.error(0x0000, 'testTag', "HiAppEvent holder is null") + return + } + let eventPkg = null + // Fetch the subscription event package based on the specified threshold (512 KB by default) until all subscription event data is fetched. + // If all subscription event data is fetched, return a null event package object. The subscription callback process is ended. + while ((eventPkg = holder.takeNext()) != null) { + // Apply custom processing to the event logging data in the event package, for example, print the event logging data in the log. + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId) + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row) + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size) + for (const eventInfo of eventPkg.data) { + hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo) + } + } + } + }) + } + } -1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows: +2. Choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add a button, and enable logging of button click events in its **onClick** function. The complete sample code is as follows: - ```ts - import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'; + ```js + import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' + import hilog from '@ohos.hilog' @Entry @Component @@ -57,61 +109,21 @@ The following uses a one-time event watcher as an example to illustrate the deve .fontSize(50) .fontWeight(FontWeight.Bold) - Button("1 writeTest").onClick(()=>{ - // Perform event logging based on the input event parameters. + Button("writeTest").onClick(()=>{ + // Enable event logging in the button click function to log button click events. hiAppEvent.write({ - domain: "test_domain", - name: "test_event", - eventType: hiAppEvent.EventType.FAULT, - params: { - int_data: 100, - str_data: "strValue" - } + // Define the event domain. + domain: "button", + // Define the event name. + name: "click", + // Define the event type. + eventType: hiAppEvent.EventType.BEHAVIOR, + // Define event parameters. + params: { click_time: 100 } }).then(() => { - console.log(`HiAppEvent success to write event`); + hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) }).catch((err) => { - console.error(`code: ${err.code}, message: ${err.message}`); - }); - }) - - Button("2 addWatcherTest").onClick(()=>{ - // Add an event watcher based on the input subscription parameters. - hiAppEvent.addWatcher({ - name: "watcher1", - appEventFilters: [{ domain: "test_domain" }], - triggerCondition: { - row: 2, - size: 1000, - timeOut: 2 - }, - onTrigger: function (curRow, curSize, holder) { - // If the holder object is null, return an error after recording it in the log. - if (holder == null) { - console.error("HiAppEvent holder is null"); - return; - } - // Set the size threshold to 1,000 bytes for obtaining an event package. - holder.setSize(1000); - let eventPkg = null; - // Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained. - while ((eventPkg = holder.takeNext()) != null) { - // Parse the obtained event package and display the result on the Log page. - console.info(`HiAppEvent eventPkg.packageId=${eventPkg.packageId}`); - console.info(`HiAppEvent eventPkg.row=${eventPkg.row}`); - console.info(`HiAppEvent eventPkg.size=${eventPkg.size}`); - // Traverse and parse event string arrays in the obtained event package. - for (const eventInfo of eventPkg.data) { - console.info(`HiAppEvent eventPkg.data=${eventInfo}`); - } - } - } - }); - }) - - Button("3 removeWatcherTest").onClick(()=>{ - // Remove the specified event watcher. - hiAppEvent.removeWatcher({ - name: "watcher1" + hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) }) }) } @@ -121,26 +133,20 @@ The following uses a one-time event watcher as an example to illustrate the deve } } ``` + +3. Touch the run button on the IDE to run the project. Then, touch the **writeTest** button on the application UI to trigger application event logging. -2. Touch the run button on the IDE to run the project. - -3. Touch button 1 on the application UI to start application event logging. If the logging is successful, you'll see the following message in the **Log** window: - - ``` - success to write event: 0 - ``` - -4. On the application UI, touch button 2 to add an event watcher, and touch button 1 for multiple times to perform application event logging. If any callback trigger condition (event count, event data size, and timeout duration) is met, the event watcher will invoke a callback and the event package obtained through the callback will be displayed in the **Log** window. +4. View the information printed in the **Log** window. If logging of the button click event is successful, you will see a message indicating successful event logging as well as the log information specific to processing of the event logging data in the subscription callback. - ``` + ```js + HiAppEvent success to write event + HiAppEvent eventPkg.packageId=0 - HiAppEvent eventPkg.row=2 - HiAppEvent eventPkg.size=308 - HiAppEvent eventPkg.data={"domain_":"test_domain","name_":"test_event","type_":1,"time_":1502096107556,"tz_":"+0000","pid_":4204,"tid_":4223,"int_data":100,"str_data":"strValue"} + HiAppEvent eventPkg.row=1 + HiAppEvent eventPkg.size=124 + HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1670268234523,"tz_":"+0800","pid_":3295,"tid_":3309,"click_time":100} ``` -5. On the application UI, touch button 3 to remove the event watcher. Then, touch button 1 for multiple times to perform application event logging. In such a case, there will be no log information about the callback invoked by the event watcher. - ## Samples The following sample is provided to help you better understand how to develop the application event logging feature: diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md deleted file mode 100644 index 2e54f28d8a69623accc2aff1b8dc96f30045f8ed..0000000000000000000000000000000000000000 --- a/en/application-dev/dfx/hiappevent-overview.md +++ /dev/null @@ -1,11 +0,0 @@ -# Overview of Application Event Logging - -The HiAppEvent module provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application. - -You can use this module to develop application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. - -## Basic Concepts - -**Logging** - - A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis. \ No newline at end of file diff --git a/en/application-dev/dfx/hitracechain-guidelines.md b/en/application-dev/dfx/hitracechain-guidelines.md index 06d849872941ab84a894224ef4e3d17ddb8d491d..affd260b0503f3c4f4c4b748d5911d94f7fef9e3 100644 --- a/en/application-dev/dfx/hitracechain-guidelines.md +++ b/en/application-dev/dfx/hitracechain-guidelines.md @@ -1,8 +1,16 @@ # Development of Distributed Call Chain Tracing -## When to Use +## Introduction -HiTraceChain is the module that provides APIs to implement call chain tracing throughout a service process. With HiTraceChain, you can quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. +The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. + +hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process. + +## Basic Concepts + +- **chainId** + + Distributed call chain tracing ID, which is a part of **HiTraceId** and is used to identify the service process being traced. ## Available APIs diff --git a/en/application-dev/dfx/hitracechain-overview.md b/en/application-dev/dfx/hitracechain-overview.md deleted file mode 100644 index 64eae517ace23beb6e3ad80bc7b6f0df1ef9b34a..0000000000000000000000000000000000000000 --- a/en/application-dev/dfx/hitracechain-overview.md +++ /dev/null @@ -1,17 +0,0 @@ -# Overview of Distributed Call Chain Tracing - -hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. - -## Basic Concepts - -- **chainId** - - Distributed call chain tracing ID, which is a part of **HiTraceId** and is used to identify the service process being traced. - -## Working Principles - -The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process. - -## Constraints - -All APIs provided by the hiTraceChain module work in synchronous mode. diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md index 1b45886ca4c593bbfff1b1b07d5892ad20ba58ae..2b8b7a562a7e896db40faba9de194777c4d1c170 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines.md +++ b/en/application-dev/dfx/hitracemeter-guidelines.md @@ -1,8 +1,23 @@ # Development of Performance Tracing -## When to Use +## Introduction -HiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by HiTraceMeter module in your own service logic to effectively track service processes and check the system performance. +hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance. + +## Basic Concepts + +- **hiTraceMeter Tag** + + Tag used for tracing data categorization. It is also known as **hiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed as the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the tracing data specified by the **Tag** parameter is collected. + +## Working Principles + +- The application calls hiTraceMeter APIs to perform performance tracing. The APIs output the tracing data to the kernel's ftrace data buffer through the kernel's sysfs file interface. +- The hiTraceMeter CLI tool reads the tracing data in the ftrace data buffer and saves the trace data as a text file on the device. + +## Constraints + +Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs. ## Available APIs diff --git a/en/application-dev/dfx/hitracemeter-overview.md b/en/application-dev/dfx/hitracemeter-overview.md deleted file mode 100644 index 649fa7704dd566ab8bc02776de6f62756d7f26a6..0000000000000000000000000000000000000000 --- a/en/application-dev/dfx/hitracemeter-overview.md +++ /dev/null @@ -1,18 +0,0 @@ -# Overview of Performance Tracing - -hiTraceMeter is a tool for you to trace service processes and monitor system performance. Through encapsulating and extending the ftrace inside the kernel, hiTraceMeter supports performance tracing for code execution in the user space. You can use hiTraceMeter APIs to implement performance tracing and use the hiTraceMeter CLI tool to collect traced data. - -## Basic Concepts - -- **hiTraceMeter Tag** - - Tag used for tracing data categorization. It is also known as **hiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed as the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the tracing data specified by the **Tag** parameter is collected. - -## Working Principles - -- The application calls hiTraceMeter APIs to perform performance tracing. The APIs output the tracing data to the kernel's ftrace data buffer through the kernel's sysfs file interface. -- The hiTraceMeter CLI tool reads the tracing data in the ftrace data buffer and saves the trace data as a text file on the device. - -## Constraints - -Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs. diff --git a/en/application-dev/faqs/faqs-ability.md b/en/application-dev/faqs/faqs-ability.md index ed3cfcc4412379ea61974895ca111256b68ae696..aab3ecc19aff704dbc34b9f7aa4d174344735453 100644 --- a/en/application-dev/faqs/faqs-ability.md +++ b/en/application-dev/faqs/faqs-ability.md @@ -60,7 +60,7 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file. -Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md) +Reference: [Application Package Structure (Stage Model)](../quick-start/module-configuration-file.md) Example: @@ -83,17 +83,15 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change. -Reference: [Ability Development](../ability/stage-ability.md) - ## Can I obtain the context through globalThis in the stage model? Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 Do not use **globalThis** to obtain the context in the stage model. This is because all the processes of an application share a JS VM instance in the stage model. Multiple abilities can run on these processes and share the same global object. If **globalThis** is used, the context of different abilities of the same JS VM instance may be returned. -For details about the recommended operation, see [Context in the Stage Model](../ability/context-userguide.md#context-in-the-stage-model). +Reference of the recommended operation: [Context (Stage Model)](../application-models/application-context-stage.md) -## How do I obtain the HAP file installation path of application B from application A? +## How do I obtain the HAP installation path of application B from application A? Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9 @@ -109,7 +107,7 @@ The callee uses **AbilityContext.terminateSelfWithResult** to destroy its abilit Applicable to: OpenHarmony SDK 3.2.5.5, FA model of API version 8 -After a widget is added, the **onCreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed. +After a widget is added, the **oncreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed. ## How do I obtain the context? diff --git a/en/application-dev/faqs/faqs-development-board.md b/en/application-dev/faqs/faqs-development-board.md index 79e5fc390f934f82eb3d70468f9ed41faed68947..0a2a29db5ba68e57e2eee790485ae682ac78b6c0 100644 --- a/en/application-dev/faqs/faqs-development-board.md +++ b/en/application-dev/faqs/faqs-development-board.md @@ -9,7 +9,6 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 - Method 2: Run the screenshot script. Connect to the development board to a computer running Windows. Create a text file on the computer, copy the following script content to the file, change the file name extension to **.bat** (the HDC environment variables must be configured in advance), and click **Run**. The screenshot is saved to the same directory as the **.bat** script file. Example: - ``` set filepath=/data/%date:~0,4%%date:~5,2%%date:~8,2%%time:~1,1%%time:~3,2%%time:~6,2%.png echo %filepath% @@ -29,10 +28,11 @@ Applicable to: DevEco Studio 3.0.0.991 ![en-us_image_0000001361254285](figures/en-us_image_0000001361254285.png) 2. Set the profile parameters as follows: + Device type : default - + Resolution: 720\*1280 - + DPI: 240 ## What should I do if Device Manager incorrectly identifies a development board as FT232R USB UART even when the development board already has a driver installed? diff --git a/en/application-dev/faqs/faqs-event-notification.md b/en/application-dev/faqs/faqs-event-notification.md index 06a811e0ca13d1bf8f634a65593a2424ad3999bd..1197745d9038b3ac15995ba467e939def1db1ac6 100644 --- a/en/application-dev/faqs/faqs-event-notification.md +++ b/en/application-dev/faqs/faqs-event-notification.md @@ -16,15 +16,15 @@ Reference: [Notification](../reference/apis/js-apis-notification.md#notification Example: -``` -import WantAgent from '@ohos.wantAgent'; +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; async function publishNotification() { let wantAgentInfo = { wants: [ { - bundleName: "com.example.notification", - abilityName: "MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", } ], operationType: WantAgent.OperationType.START_ABILITIES, diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md index 7752d9d746fc3cfe3d8b7028ada2c4d3c5af2136..7eeba0644721dbf77174680f3c6c6d0ac0db05cf 100644 --- a/en/application-dev/faqs/faqs-graphics.md +++ b/en/application-dev/faqs/faqs-graphics.md @@ -18,10 +18,10 @@ Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 1. Use the **onWindowStageCreate** to obtain a **windowClass** object. - ``` + ```ts onWindowStageCreate(windowStage) { // When the main window is created, set the main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") windowStage.getMainWindow((err, data) => { if (err.code) { console.error('Failed to obtain the main window.') @@ -35,7 +35,7 @@ Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 2. Enable the full-screen mode for the window and hide the status bar. - ``` + ```ts globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { if (err.code) { console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); @@ -54,7 +54,7 @@ Use **window.getProperties()** to obtain the window properties. The **windowRect Example: -``` +```ts let promise = windowClass.getProperties(); promise.then((data)=> { console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data.windowRect)); @@ -70,7 +70,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 Refer to the following code: -``` +```ts window.getTopWindow(globalThis.mainContext).then(win => { var systemBarProperties = { statusBarColor: '#19B6FF', // Set the background color of the status bar. diff --git a/en/application-dev/faqs/faqs-language.md b/en/application-dev/faqs/faqs-language.md index db7e95d5ede5c3bead52e16bceb16e90c6188b79..22a450b4c8e37dc85a28c2ea3b972b03d6ea16ae 100644 --- a/en/application-dev/faqs/faqs-language.md +++ b/en/application-dev/faqs/faqs-language.md @@ -155,7 +155,9 @@ The global function **encodeURI** is used for URI encoding, and **decodeURI** is Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 -Yes. The **convert** API of the **convertxml** module can be used to convert XML text into JavaScript objects. Reference: [@ohos.convertxml](../reference/apis/js-apis-convertxml.md) +Yes. The **convert** API of the **convertxml** module can be used to convert XML text into JavaScript objects. + +Reference: [@ohos.convertxml](../reference/apis/js-apis-convertxml.md) ## How do I configure application icons to be used across devices? @@ -287,4 +289,4 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 No. Relational database operations cannot be performed in the worker thread. - \ No newline at end of file + \ No newline at end of file diff --git a/en/application-dev/faqs/faqs-media.md b/en/application-dev/faqs/faqs-media.md index 9f465834a0951246f822ef2b5f8a5bf619ec1c5a..0e88cf4e94aafa20e47a6ebd8fe3688d26a5e52a 100644 --- a/en/application-dev/faqs/faqs-media.md +++ b/en/application-dev/faqs/faqs-media.md @@ -42,7 +42,7 @@ cameraInput = await this.cameraManager.createCameraInput(cameraId) Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 1. Create an **ImageSource** instance based on the input URI. - + ``` let path = this.context.getApplicationContext().fileDirs + "test.jpg"; const imageSourceApi = image.createImageSource(path); @@ -52,7 +52,7 @@ Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 - Set **desiredSize** to specify the target size after scaling. If the values are all set to **0**, scaling will not be performed. - Set **desiredRegion** to specify the target rectangular area after cropping. If the values are all set to **0**, cropping will not be performed. - Set **rotateDegrees** to specify the rotation angle. The image will be rotated clockwise at the center. - + ``` const decodingOptions = { desiredSize: { @@ -85,7 +85,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 1. Configure the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** in the **module.json5** file. Example: - + ``` { "module" : { @@ -104,10 +104,14 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 ``` 2. Call **requestPermissionsFromUser** to request the permissions from end users in the form of a dialog box. This operation is required because the grant mode of both permissions is **user_grant**. - + ``` + import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; + let permissions: Array = ['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] - context.requestPermissionsFromUser(permissions).then((data) => { + let atManager = abilityAccessCtrl.createAtManager(); + // context is the ability-level context of the initiator UIAbility. + atManager.requestPermissionsFromUser(context, permissions).then((data) => { console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) }).catch((error) => { console.log("Failed to request permission from user with error: " + JSON.stringify(error)) diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md index 074a404683bda39d3e5499c66bb193d97784c4dd..8564d2f0969a2cf6eac9bb2d9ac521e62045d162 100644 --- a/en/application-dev/faqs/faqs-ui-ets.md +++ b/en/application-dev/faqs/faqs-ui-ets.md @@ -165,9 +165,9 @@ Before the window content is loaded, enable listening for the **systemAvoidAreaC Example: -``` -// MainAbility.ts -import window from '@ohos.window'; +```ts +import Window from '@ohos.window'; +import UIAbility from '@ohos.app.ability.UIAbility'; /** * Set the immersive window and obtain the height of the status bar and navigation bar. @@ -187,7 +187,7 @@ async function enterImmersion(mainWindow: window.Window) { statusBarContentColor: "#FF0000" }) } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { // do something async onWindowStageCreate(windowStage: window.WindowStage) { let mainWindow = await windowStage.getMainWindow() @@ -213,7 +213,7 @@ You can obtain the changes in the width and height of a component through **onAr Example: -``` +```ts Column() { Text(this.value) .backgroundColor(Color.Green).margin(30).fontSize(20) @@ -235,7 +235,7 @@ Bind the **\** component to a **Scoller** object and obtain the offset thr Example: -``` +```ts Column() { List({ space: 20, initialIndex: 0,scroller: this.scroller}) { ForEach(this.arr, (item) => { @@ -259,7 +259,7 @@ Column() { Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 -``` +```ts // In versions earlier than 3.1.5.5, obtain the value through router.getParams().key. private value: string = router.getParams().value; // In 3.1.6.5 and later versions, obtain the value through router.getParams()['key']. @@ -299,7 +299,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 The color can be represented in two formats, for example, 0x7F000000 or '\#7F000000'. The first two digits indicate opacity, and the last six digits indicate RGB. -``` +```ts fontColor(0x7F000000) fontColor( '#7F000000' ) ``` diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md index 4bb5fe54817e245807612eaac1a0b6d235101f7a..4aa7c9af2c977aac2a987de80bad2b6f164b1215 100644 --- a/en/application-dev/file-management/Readme-EN.md +++ b/en/application-dev/file-management/Readme-EN.md @@ -3,4 +3,8 @@ - [MediaLibrary Overview](medialibrary-overview.md) - [Media Asset Management](medialibrary-resource-guidelines.md) - [File Path Management](medialibrary-filepath-guidelines.md) - - [Album Management](medialibrary-album-guidelines.md) \ No newline at end of file + - [Album Management](medialibrary-album-guidelines.md) + +- File Access Framework + - [File Access Framework Overview](file-access-framework-overview.md) +- [FilePicker Guide](filepicker-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/file-management/figures/faf-data-flow.png b/en/application-dev/file-management/figures/faf-data-flow.png new file mode 100644 index 0000000000000000000000000000000000000000..d3c6fd90b59712bf2728208f247d531b919b4b3b Binary files /dev/null and b/en/application-dev/file-management/figures/faf-data-flow.png differ diff --git a/en/application-dev/file-management/figures/public-file-operation.png b/en/application-dev/file-management/figures/public-file-operation.png new file mode 100644 index 0000000000000000000000000000000000000000..bb434a499da63e2245bd806bfc6e0d42686d883d Binary files /dev/null and b/en/application-dev/file-management/figures/public-file-operation.png differ diff --git a/en/application-dev/file-management/file-access-framework-overview.md b/en/application-dev/file-management/file-access-framework-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..1cdf4f6c3513606c7361b951f24d3424bb065113 --- /dev/null +++ b/en/application-dev/file-management/file-access-framework-overview.md @@ -0,0 +1,44 @@ +# File Access Framework Overview + +On devices running OpenHarmony 3.2 (API version 9) or later, applications can access public files on the local device, remote device, and external storage device, as well as files shared by multiple users, based on the File Access Framework (FAF). + +To ensure user data privacy, this framework allows users to create, open, delete, rename, and move files on the file access server only through the **File Manager** and **File Picker** applications. + +The user data of an application is stored on the device even after the application is uninstalled. + +If a system application needs to access public files on the local device, use [File Path Management](medialibrary-filepath-guidelines.md). + +> **NOTE** +> 1. For a non-management system application, for example, **Gallery**, use the **mediaLibrary** APIs for direct file operation. +> 2. In principle, do not mix use the FAF APIs with the mediaLibrary APIs. + +## FAF Mechanism +Based on the OpenHarmony [ExtensionAbility mechanism](../application-models/extensionability-overview.md), the FAF provides unified APIs for external systems. With these APIs, applications can preview and operate public files to implement their own logic. + +You can visit the [source repository](https://gitee.com/openharmony/filemanagement_user_file_service) for more details. + +The following figure shows the FAF-based file operation process. + +**Figure 1** Hierarchy of public file operations + +![](figures/public-file-operation.png) + +- **File access client**: an application that needs to access or operate public files. By starting the file selector application, it enables users to perform file operations on the UI. +- **File selector application**: a system application that allows users to access all shared datasets. You can use the FAF APIs to operate the datasets. +- **File access server**: a service that supports dataset sharing in the system. Currently, [UserFileManager](https://gitee.com/openharmony/multimedia_medialibrary_standard) and ExternalFileManager are available. UserFileManager manages datasets on local disks and distributed devices, and ExternalFileManager manages datasets on external storage devices such as SD cards and USB flash drives. You can also share your own datasets based on the FAF server configuration. + +The FAF has the following features: +- Users can browse the datasets provided by all file server applications in the system, rather than those provided by a single application. +- The file access client can operate files through the file selector application, without obtaining the permission to use the FAF. +- Multiple temporarily mounted devices, such as external storage cards and distributed devices, can be accessed at the same time. + +## Data Models +Data models in the FAF are transferred through URI, FileInfo, and RootInfo. For details, see [fileExtension](../reference/apis/js-apis-fileExtensionInfo.md). Applications on the file access server can use the **FileAccessExtensionAbility** APIs to securely share their data. + +**Figure 2** Data flow of the public file access framework + +![](figures/faf-data-flow.png) + +NOTE +- In the FAF, the file access client does not directly interact with the file access server. The client only needs to have the permission to start the file selector application. +- The file selector application provides a standard document access UI for users, even if the underlying file access servers differ greatly. diff --git a/en/application-dev/file-management/filepicker-guidelines.md b/en/application-dev/file-management/filepicker-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..8fcf96b2219151a9c197cd1f6bc2e738775646b7 --- /dev/null +++ b/en/application-dev/file-management/filepicker-guidelines.md @@ -0,0 +1,68 @@ +# FilePicker Guide + +FilePicker is a system application preset in OpenHarmony. You can use it to select and save files. For details about the implementation of FilePicker, see [applications_filepicker](https://gitee.com/openharmony/applications_filepicker). + +FilePicker provides the following modes: +- **choose**: Use this mode when an application needs to select and upload or send files (including media resources such as images, and audio and video clips) in the device. When this mode is selected, the FilePicker **choose** mode window will be triggered to display a dialog box for you to select a file. You can select the target file and tap **Upload**. The application will receive the URI of the target file returned by FilePicker. +- **save**: Use this mode when an application needs to download and save files (including media resources such as images and audio and video clips). When this mode is selected, the FilePicker **save** mode window will be triggered to display a dialog box for you to select the destination path of the file to save. You can select the destination path and tap **Save**. The application will receive the URI of the saved file returned by FilePicker. + +## 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 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. + +You also need to set **Want.parameters** to specify the FilePicker mode to start and the name of the file to save. +- To select a file, set **'startMode': 'choose'**. +- To save a file, set **'startMode': 'save'** and **'saveFile'**. + +You can set **options** of the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) type to specify the dialog box style. The recommended value is **windowMode: 102**, which indicates a floating window. + +> **CAUTION** +> - In the **save** mode, a strong verification is performed on the file path based on the name of the file to save. For details about the file path format, see [File Path Management](medialibrary-filepath-guidelines.md). +> - If a file with the same name exists, a dialog box will be displayed asking you whether to overwrite the existing file. + +ArkTS sample code: +```ts +// Start FilePicker to select a file. +globalThis.context.startAbilityForResult( + { + bundleName: "com.ohos.filepicker", + abilityName: "EntryAbility", + parameters: { + 'startMode': 'choose', //choose or save + } + }, + { windowMode: 102 } +) + +// Start FilePicker to save a file. +globalThis.context.startAbilityForResult( + { + bundleName: "com.ohos.filepicker", + abilityName: "EntryAbility", + parameters: { + 'startMode': 'save', //choose or save + 'saveFile': 'test.jpg', + } + }, + { windowMode: 102 } +) + +// Data returned by FilePicker to startAbilityForResult. +let abilityResult = { + resultCode: resultCode, + want: { + parameters: { + 'startMode': startMode, + 'result': result + } + } +} +globalThis.context.terminateSelfWithResult(abilityResult) +``` diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md index fc9b327031cfee8ea6de601b3c3d268bbf161c53..23b7604f4dde99c832b59305595e94b06ea1baa2 100644 --- a/en/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -69,7 +69,7 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o **How to Develop** -1. Call [Context.getFilesDir](../reference/apis/js-apis-Context.md#contextgetfilesdir) to obtain the directory of the application sandbox. +1. Call [Context.getFilesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) 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. 4. Call **fileAsset.open** to open the file in the public directory. diff --git a/en/application-dev/internationalization/Readme-EN.md b/en/application-dev/internationalization/Readme-EN.md index d7042968cf5c6824e49f77911e207e4cbb4be443..6c89740e15daf19fcb712aba339484caad2ed7c3 100644 --- a/en/application-dev/internationalization/Readme-EN.md +++ b/en/application-dev/internationalization/Readme-EN.md @@ -1,6 +1,6 @@ # Internationalization - [Internationalization Overview](international-overview.md) -- [Internationalization Development (intl)](intl-guidelines.md) -- [Internationalization Development (i18n)](i18n-guidelines.md) +- [intl Development](intl-guidelines.md) +- [i18n Development](i18n-guidelines.md) diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 62bf66fd7cabb7e30c765126ddacba639bd951f5..8218f2561376c4119f66be0175c5c9ea16c7d024 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -1,391 +1,732 @@ -# Internationalization Development (I18N) +# i18n Development -This 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. For more details about APIs and their usage, see [I18N](../reference/apis/js-apis-i18n.md). +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. For more details about APIs and their usage, see [i18n](../reference/apis/js-apis-i18n.md). -## Obtaining System Language and Region Information +The [intl](intl-guidelines.md) module provides basic i18n capabilities through the standard i18n interfaces defined in ECMA 402. It works with the **i18n** module to provide a complete suite of i18n capabilities. -You can use APIs provided in the following table to obtain the system language and region information. +## Obtaining and Setting i18n Information +The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | - +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------- | +| System | getDisplayCountry(country:string,locale:string,sentenceCase?:boolean):string9+ | Obtains the localized representation of a country. | +| System | getDisplayLanguage(language:string,locale:string,sentenceCase?:boolean):string9+ | Obtains the localized representation of a language. | +| System | getSystemLanguages():Array9+ | Obtains the system language list. | +| System | getSystemCountries(language: string):Array9+ | Obtains the list of countries and regions supported for the specified language. | +| System | isSuggested(language: string, region?: string): boolean9+ | Checks whether the system language matches the specified region. | +| System | getSystemLanguage():string9+ | Obtains the system language. | +| System | setSystemLanguage(language: string)9+ | Sets the system language. | +| System | getSystemRegion():string9+ | Obtains the system region. | +| System | setSystemRegion(region: string)9+ | Sets the system region. | +| System | getSystemLocale():string9+ | Obtains the system locale. | +| System | setSystemLocale(locale: string)9+ | Sets the system locale. | +| System | is24HourClock():boolean9+ | Checks whether the 24-hour clock is used. | +| System | set24HourClock():boolean9+ | Sets the 24-hour clock. | +| System | addPreferredLanguage(language: string, index?: number)9+ | Adds a preferred language to the specified position on the preferred language list. | +| System | removePreferredLanguage(index: number)9+ | Deletes a preferred language from the specified position on the preferred language list. | +| System | getPreferredLanguageList()9+ | Obtains the preferred language list. | +| System | getFirstPreferredLanguage()9+ | Obtains the first language in the preferred language list. | +| System | getAppPreferredLanguage()9+ | Obtains the preferred language of an application. | +| System | setUsingLocalDigit(flag: boolean)9+ | Sets whether to enable the local digit switch. | +| System | getUsingLocalDigit()9+ | Checks whether the local digit switch is turned on. | +| | isRTL(locale:string):boolean9+ | Checks whether the locale uses a right-to-left (RTL) language.| ### How to Develop +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Obtain and set the system language. + + Call **setSystemLanguage** to set the system language. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call the **getSystemLanguage** API to obtain the system language. + + ```js + try { + I18n.System.setSystemLanguage("en"); // Set the system language to en. + let language = I18n.System.getSystemLanguage(); // language = "en" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` -1. Obtain the system language. +3. Obtain and set the system locale. + + Call **setSystemRegion** to set the system country or region. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call **getSystemRegion** to obtain the system country or region. + + ```js + try { + I18n.System.setSystemRegion("CN"); // Set the system country to CN. + let region = I18n.System.getSystemRegion(); // region = "CN" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` - Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). +4. Obtain and set the system locale. + Call **setSystemLocale** to set the system locale. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) For details about how to set a locale, see [Setting Locale Information](../internationalization/intl-guidelines.md#setting-locale-information). + Call **getSystemLocale** to obtain the system locale. - ```js - var language = i18n.getSystemLanguage(); + ```js + try { + I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN. + let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -2. Obtain the system region. +5. Check whether the locale uses a right-to-left (RTL) language. + + Call **isRTL** to check whether the locale uses an RTL language. - Call the **getSystemRegion** method to obtain the system region. - - ```js - var region = i18n.getSystemRegion(); + ```js + try { + let rtl = I18n.isRTL("zh-CN"); // rtl = false + rtl = I18n.isRTL("ar"); // rtl = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -3. Obtain the system locale. +6. Obtain and set the 24-hour clock. - Call the **getSystemLocale** method to obtain the system locale. - - ```js - var locale = i18n.getSystemLocale(); + Call **set24HourClock** to enable the 24-hour clock. + Call **is24HourClock** to check whether the 24-hour clock is enabled. + + ```js + try { + I18n.System.set24HourClock(true); + let hourClock = I18n.System.is24HourClock(); // hourClock = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -4. Check whether the locale's language is RTL. +7. Obtain the localized representation of a language. + + Call **getDisplayLanguage** to obtain the localized representation of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - Call the **isRTL** method to check whether the locale's language is RTL. + ```js + try { + let language = "en"; + let locale = "zh-CN"; + let sentenceCase = false; + let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` +8. Obtain the localized representation of a country. - ```js - var rtl = i18n.isRTL("zh-CN"); + Call **getDisplayCountry** to obtain the localized representation of a country. **country** indicates the country to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. + + ```js + try { + let country = "US"; + let locale = "zh-CN"; + let sentenceCase = false; + let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S." + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -5. Check whether the system uses a 24-hour clock. +9. Obtain the list of system languages and the list of countries supported by a system language. - Call the **is24HourClock** method to check whether the system uses a 24-hour clock. - - ```js - var hourClock = i18n.is24HourClock(); + Call **getSystemLanguages** to obtain the list of system languages. + Call **getSystemCountries** to obtain the list of countries and regions supported by a system language. + ```js + + try { + let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] + let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -6. Obtain the localized display of a language. +10. Check whether the language matches a country or region. - Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - - ```js - var language = "en"; - var locale = "zh-CN"; - var sentenceCase = false; - var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase); + Call **isSuggested** to check whether the language matches a country or region. + + ```js + try { + let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -7. Obtain the localized display of a country. +11. Obtain and set the preferred language. - Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - - ```js - var country = "US"; - var locale = "zh-CN"; - var sentenceCase = false; - var localizedCountry = i18n.getDisplayCountry(country, locale, sentenceCase); + Call **addPreferredLanguage** to add a preferred language to the preferred language list. + Call **removePreferredLanguage** to remove a preferred language from the preferred language list. (**addPreferredLanguage** and **removePreferredLanguage** are system APIs and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call **getPreferredLanguageList** to obtain the preferred language list. + Call **getFirstPreferredLanguage** to obtain the first preferred language in the preferred language list. + Call **getAppPreferredLanguageList** to obtain the preferred language of the application. It is the first language that matches the application resource in the preferred language list. + + ```js + try { + I18n.System.addPreferredLanguage("en-GB", 0); // Set the first language in the preferred language list to en-GB. + let list = I18n.System.getPreferredLanguageList(); // Obtain the preferred language list. Example: list = ["en-GB", ...] + I18n.System.removePreferredLanguage(list.length - 1); // Remove the last preferred language from the preferred language list. + let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" + let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources. + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` +12. Obtain and set the local digit switch. -## Obtaining Calendar Information + Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.) + Call **getUsingLocalDigit** to check whether the local digit switch is enabled. + Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur". -[Calendar](../reference/apis/js-apis-i18n.md#calendar8) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. +```js +try { + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. + let status = I18n.System.getUsingLocalDigit(); // status = true +} catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) +} +``` +## Obtain the calendar information. -### Available APIs +[Calendar](../reference/apis/js-apis-i18n.md#calendar8) provides APIs to obtain calendar information, for example, localized representation of the calendar, the start day of a week, and the minimum number of days in the first week of a year. -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getCalendar(locale: string, type?: string): Calendar8+ | Obtains the **Calendar** object for a specific locale and type. | -| ohos.i18n | setTime(date: Date): void8+ | Sets the date for the **Calendar** object. | -| ohos.i18n | setTime(time: number): void8+ | Sets the time for the **Calendar** object. | -| ohos.i18n | set(year: number, month: number, date: number, hour?: number, minute?: number, second?: number): void8+ | Sets the year, month, day, hour, minute, and second for the **Calendar** object. | -| ohos.i18n | setTimeZone(timezone: string): void8+ | Sets the time zone for the **Calendar** object. | -| ohos.i18n | getTimeZone(): string8+ | Obtains the time zone for the **Calendar** object. | -| ohos.i18n | getFirstDayOfWeek(): number8+ | Obtains the first day of a week for the **Calendar** object. | -| ohos.i18n | setFirstDayOfWeek(value: number): void8+ | Sets the first day of a week for the **Calendar** object. | -| ohos.i18n | getMinimalDaysInFirstWeek(): number8+ | Obtains the minimum count of days in the first week of a year. | -| ohos.i18n | setMinimalDaysInFirstWeek(value: number): void8+ | Sets the minimum count of days in the first week of a year. | -| ohos.i18n | getDisplayName(locale: string): string8+ | Obtains the localized display of the **Calendar** object. | -| ohos.i18n | isWeekend(date?: Date): boolean8+ | Checks whether a given date is a weekend. | +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------- | +| | getCalendar(locale:string,type?:string):Calendar8+ | Obtains the **Calendar** object for a specific locale and type.| +| Calendar | setTime(date:Date): void8+ | Sets the date for this **Calendar** object. | +| Calendar | setTime(time:number): void8+ | Sets the date for this **Calendar** object. | +| Calendar | set(year:number,month:number,date:number,hour?:number,minute?:number,second?:number): void8+ | Sets the year, month, day, hour, minute, and second for this **Calendar** object. | +| Calendar | setTimeZone(timezone:string): void8+ | Sets the time zone of this **Calendar** object. | +| Calendar | getTimeZone():string8+ | Obtains the time zone of this **Calendar** object. | +| Calendar | getFirstDayOfWeek():number8+ | Obtains the start day of a week for this **Calendar** object. | +| Calendar | setFirstDayOfWeek(value:number): void8+ | Sets the first day of a week for the **Calendar** object. | +| Calendar | getMinimalDaysInFirstWeek():number8+ | Obtains the minimum number of days in the first week of a year. | +| Calendar | setMinimalDaysInFirstWeek(value:number): void8+ | Sets the minimum number of days in the first week of a year. | +| Calendar | getDisplayName(locale:string):string8+ | Obtains the localized display of the **Calendar** object. | +| Calendar | isWeekend(date?:Date):boolean8+ | Checks whether the specified date in this **Calendar** object is a weekend. | ### How to Develop -1. Instantiate a **Calendar** object. +1. Import the **i18n** module. - Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. + ```js + import I18n from '@ohos.i18n' + ``` + +2. Instantiate a **Calendar** object. + Call **getCalendar** to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - ```js - var calendar = i18n.getCalendar("zh-CN", "gregory"); + ```js + let calendar = I18n.getCalendar("zh-CN", "chinese"); // Create the Calendar object for the Chinese lunar calendar. ``` -2. Set the time for the **Calendar** object. +3. Set the time for the **Calendar** object. + + Call **setTime** to set the time of the **Calendar** object. Two types of parameters are supported. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - - ```js - var date1 = new Date(); + ```js + let date1 = new Date(); calendar.setTime(date1); - var date2 = 1000; + let date2 = 1000; calendar.setTime(date2); ``` -3. Set the year, month, day, hour, minute, and second for the **Calendar** object. +4. Set the year, month, day, hour, minute, and second for this **Calendar** object. - Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - - ```js + Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object. + + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` -4. Set and obtain the time zone for the **Calendar** object. - - Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. +5. Set and obtain the time zone for the **Calendar** object. + Call **setTimeZone** and **getTimeZone** to set and obtain the time zone of the **Calendar** object. Note that **setTimeZone** requires an input string to indicate the time zone to be set. - ```js + ```js calendar.setTimeZone("Asia/Shanghai"); - var timezone = calendar.getTimeZone(); + let timezone = calendar.getTimeZone(); // timezone = "China Standard Time" ``` -5. Set and obtain the first day of a week for the **Calendar** object. +6. Set and obtain the first day of a week for the **Calendar** object. - Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. + Call **setFirstDayOfWeek** and **getFirstDayOfWeek** to set and obtain the start day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. - - ```js + ```js calendar.setFirstDayOfWeek(1); - var firstDayOfWeek = calendar.getFirstDayOfWeek(); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` -6. Set and obtain the minimum count of days in the first week for the **Calendar** object. +7. Set and obtain the minimum count of days in the first week for the **Calendar** object. + Call **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** to set and obtain the minimum number of days in the first week for the **Calendar** object. - Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - - ```js + ```js calendar.setMinimalDaysInFirstWeek(3); - var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` -7. Obtain the localized display of the **Calendar** object. +8. Obtain the localized representation of the **Calendar** object. + Call **getDisplayName** to obtain the localized representation of the **Calendar** object. + + ```js + let localizedName = calendar.getDisplayName("zh-CN"); // localizedName = " Lunar Calendar" + ``` - Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. +9. Check whether a date is a weekend. + Call **isWeekend** to determine whether the input date is a weekend. - ```js - var localizedName = calendar.getDisplayName("zh-CN"); + ```js + let date = new Date(2022, 12, 12, 12, 12, 12); + let weekend = calendar.isWeekend(date); // weekend = false ``` -8. Check whether a date is a weekend. +## Formatting a Phone Number + +[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) provides APIs to format phone numbers of different countries or regions and check whether the phone number format is correct. - Call the **isWeekend** method to determine whether the input date is a weekend. +### Available APIs - - ```js - var date = new Date(); - var weekend = calendar.isWeekend(date); +| Class | API | Description | +| --------- | ---------------------------------------- | ----------------------- | +| PhoneNumberFormat | constructor(country:string,options?:PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object.| +| PhoneNumberFormat | isValidNumber(number:string):boolean8+ | Checks whether the value of **number** is a phone number in the correct format.| +| PhoneNumberFormat | format(number:string):string8+ | Formats the value of **number** based on the specified country and style. | +| PhoneNumberFormat | getLocationName(number: string, locale: string): string9+ | Obtains the home location of a phone number. | + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` +2. Instantiate a **PhoneNumberFormat** object. -## Formatting a Phone Number + Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. -[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. + ```js + let phoneNumberFormat = new I18n.PhoneNumberFormat("CN", {type: "E164"}); + ``` +3. Check whether the phone number format is correct. + + Call **isValidNumber** to check whether the format of the input phone number is correct. + + ```js + let validNumber = phoneNumberFormat.isValidNumber("15812341234"); // validNumber = true + ``` + +4. Format a phone number. + + Call **format** to format the input phone number. + + ```js + let formattedNumber = phoneNumberFormat.format("15812341234"); // formattedNumber = "+8615812341234" + ``` + +## Measurement Conversion + +The **I18NUtil** class provides an API to implement measurement conversion. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------------------------- | +| I18NUtil | unitConvert(fromUnit:UnitInfo,toUnit:UnitInfo,value:number,locale:string,style?:string):string9+ | Converts one measurement unit into another and formats the unit based on the specified locale and style.| + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Convert a measurement unit. + + Call [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) to convert a measurement unit and format the display result. + + ```js + let fromUnit = {unit: "cup", measureSystem: "US"}; + let toUnit = {unit: "liter", measureSystem: "SI"}; + let number = 1000; + let locale = "en-US"; + let style = "long"; + let converttedUnit = I18n.I18NUtil.unitConvert(fromUnit, toUnit, number, locale, style); // converttedUnit = "236.588 liters" + ``` + +## Alphabet Indexing + +[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) provides APIs to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. + +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | ----------------------- | +| | getInstance(locale?:string):IndexUtil8+ | Instantiates an **IndexUtil** object. | +| IndexUtil | getIndexList():Array<string>8+ | Obtains the index list of the current locale. | +| IndexUtil | addLocale(locale:string): void8+ | Adds the index of a new locale to the index list.| +| IndexUtil | getIndex(text:string):string8+ | Obtains the index of a text object. | ### How to Develop -1. Instantiate a **PhoneNumberFormat** object. +1. Import the **i18n** module. - Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. + ```js + import I18n from '@ohos.i18n' + ``` + +2. Instantiates an **IndexUtil** object. + Call **getInstance** to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - ```js - var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); + + ```js + let indexUtil = I18n.getInstance("zh-CN"); ``` -2. Check whether the phone number format is correct. - Call the **isValidNumber** method to check whether the format of the input phone number is correct. - - ```js - var validNumber = phoneNumberFormat.isValidNumber("15812341234"); +3. Obtain the index list. + + Call **getIndexList** to obtain the alphabet index list of the current locale. + + ```js + let indexList = indexUtil.getIndexList(); // indexList = ["...", "A", "B", "C", ..., "X", "Y", "Z", "..."] ``` -3. Format a phone number. - Call the **format** method of **PhoneNumberFormat** to format the input phone number. - - ```js - var formattedNumber = phoneNumberFormat.format("15812341234"); +4. Add an index. + + Call **addLocale** to add the alphabet index of a new locale to the current index list. + + ```js + indexUtil.addLocale("ar") ``` +5. Obtain the index of a string. -## Measurement Conversion + Call **getIndex** to obtain the alphabet index of a string. -The **unitConvert** API is provided to help you implement measurement conversion. + ```js + let text = "access index"; + let index = indexUtil.getIndex(text); // index = "A" + ``` + +## Obtaining Line Breaks of Text +When a text is displayed in more than one line, use [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs to obtain the line break positions of the text. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | - +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| | getLineInstance(locale:string):BreakIterator8+ | Instantiates a **BreakIterator** object. | +| BreakIterator | setLineBreakText(text:string): void8+ | Sets the text to be processed. | +| BreakIterator | getLineBreakText():string8+ | Obtains the text to be processed. | +| BreakIterator | current():number8+ | Obtains the current position of a **BreakIterator** object in the text being processed. | +| BreakIterator | first():number8+ | Sets a **BreakIterator** object to the first breakable point. | +| BreakIterator | last():number8+ | Sets a **BreakIterator** object to the last breakable point. | +| BreakIterator | next(index?:number):number8+ | Moves a **BreakIterator** object to the break point according to **index**. | +| BreakIterator | previous():number8+ | Moves a **BreakIterator** object to the previous break point. | +| BreakIterator | following(offset:number):number8+ | Moves a **BreakIterator** object to the break point following the position specified by **offset**.| +| BreakIterator | isBoundary(offset:number):boolean8+ | Determines whether a position is a break point. | ### How to Develop -1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. +1. Import the **i18n** module. - - ```js - var fromUnit = {unit: "cup", measureSystem: "US"}; - var toUnit = {unit: "liter", measureSystem: "SI"}; - var number = 1000; - var locale = "en-US"; - var style = "long"; - i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ```js + import I18n from '@ohos.i18n' + ``` +2. Instantiate a **BreakIterator** object. -## Alphabet Index + Call **getLineInstance** to instantiate a **BreakIterator** object. -[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. + ```js + let locale = "en-US" + let breakIterator = I18n.getLineInstance(locale); + ``` +3. Set and access the text that requires line breaking. -### Available APIs + Call **setLineBreakText** and **getLineBreakText** to set and access the text that requires line breaking. -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getInstance(locale?: string): IndexUtil8+ | Instantiates an **IndexUtil** object. | -| ohos.i18n | getIndexList(): Array<string>8+ | Obtains the index list of the current locale. | -| ohos.i18n | addLocale(locale: string): void8+ | Adds the index of a new locale to the index list. | -| ohos.i18n | getIndex(text: string): string8+ | Obtains the index of **text**. | + ```js + let text = "Apple is my favorite fruit"; + breakIterator.setLineBreakText(text); + let breakText = breakIterator.getLineBreakText(); // breakText = "Apple is my favorite fruit" + ``` +4. Obtain the current position of the **BreakIterator** object. -### How to Develop + Call **current** to obtain the current position of the **BreakIterator** object in the text being processed. -1. Instantiate an **IndexUtil** object. + ```js + let pos = breakIterator.current(); // pos = 0 + ``` - Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. +5. Set the position of a **BreakIterator** object. + The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. - ```js - var indexUtil = i18n.getInstance("zh-CN"); + ```js + let firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text (firstPos = 0). + let lastPos = breakIterator.last(); // Sets a BreakIterator object to the last break point, that is, the position after the text end (lastPos = 26). + // Move a BreakIterator object forward or backward by a certain number of break points. + // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. + // If the object is moved out of the text length range, **-1** is returned. + let nextPos = breakIterator.next(-2); // nextPos = 12 + let previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, **-1** is returned. Example: previousPos = 9 + // Move a BreakIterator object to the break point following the position specified by **offset**. If the object is moved out of the text length range, **-1** is returned. + let followingPos = breakIterator.following(10); // Example: followingPos = 12 ``` -2. Obtain the index list. +6. Determine whether a position is a break point. - Call the **getIndexList** method to obtain the alphabet index list of the current locale. - - ```js - var indexList = indexUtil.getIndexList(); + Call **isBoundary** to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. + + ```js + let isboundary = breakIterator.isBoundary(5); // isboundary = false ``` -3. Add an index. +## Obtaining the Time Zone - Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - - ```js - indexUtil.addLocale("ar") +[TimeZone](../reference/apis/js-apis-i18n.md#timezone) provides APIs to obtain time zone information, such as the time zone ID, localized representation, and time zone offset. + +### Available APIs + +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| | getTimeZone(zoneID?: string): TimeZone7+ | Obtains a **TimeZone** object. | +| TimeZone | getID(): string7+ | Obtains the time zone ID. | +| TimeZone | getDisplayName(locale?: string, isDST?: boolean): string7+ | Obtains the localized representation of the time zone. | +| TimeZone | getRawOffset(): number7+ | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone. | +| TimeZone | getOffset(date?: number): number7+ | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone at a certain time point. | +| TimeZone | getAvailableIDs(): Array9+ | Obtains the list of time zone IDs supported by the system. | +| TimeZone | getAvailableZoneCityIDs(): Array9+ | Obtains the list of time zone city IDs supported by the system. | +| TimeZone | getCityDisplayName(cityID: string, locale: string): string9+ | Obtains the localized representation of a time zone city in the specified locale. | +| TimeZone | getTimezoneFromCity(cityID: string): TimeZone9+ | Obtains the **TimeZone** object corresponding to the specified time zone ID.| + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` -4. Obtain the index of a string. +2. Instantiate the **TimeZone** object, and obtain the time zone information. - Call the **getIndex** method to obtain the alphabet index of a string. - - ```js - var text = "access index"; - indexUtil.getIndex(text); + Call **getTimeZone** to obtain the **TimeZone** object. + + ```js + let timezone = I18n.getTimeZone(); // If you use the default settings, you'll obtain the TimeZone object corresponding to the system time zone. ``` + Obtain the time zone ID, localized representation, time zone offset, and time zone offset at a certain time point. + + ```js + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "China Standard Time" + let rawOffset = timezone.getRawOffset(); // rawOffset = 28800000 + let offset = timezone.getOffset(new Date().getTime()); // offset = 28800000 + ``` -## Obtaining Line Breaks of Text +3. Obtain the list of time zone IDs supported by the system. + + Call **getAvailableIDs** to obtain the list of time zone IDs supported by the system. + You can use the time zone ID in the time zone ID list as an input parameter of the **getTimeZone** API to create a **TimeZone** object. + + ```js + let timezoneIDs = I18n.TimeZone.getAvailableIDs(); // timezoneIDs = ["America/Adak", ...], which contains 24 time zone IDs in total + let timezone = I18n.getTimeZone(timezoneIDs[0]); + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "Hawaii-Aleutian Standard Time" + ``` + +4. Obtain the list of time zone city IDs supported by the system. + + Call **getAvailableZoneCityIDs** to obtain the list of time zone city IDs supported by the system. + Call **getCityDisplayName** to obtain the localized representation of the time zone city ID. + Call **getTimezoneFromCity** to create a **TimeZone** object based on the time zone city ID. -When a text is displayed in more than one line, [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs are used to obtain the line break positions of the text. + ```js + let zoneCityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); // ["Auckland", "Magadan", ...] + let cityDisplayName = I18n.TimeZone.getCityDisplayName(zoneCityIDs[0], "zh-Hans"); // cityDisplayName = "Auckland (New Zealand)" + let timezone = I18n.TimeZone.getTimezoneFromCity(zoneCityIDs[0]); + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "New Zealand Standard Time" + ``` + +## Obtain the **Transliterator** object. +Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to create a **Transliterator** object and obtain the transliterated string. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getLineInstance(locale: string): BreakIterator8+ | Instantiates a **BreakIterator** object. | -| ohos.i18n | setLineBreakText(text: string): void8+ | Sets the text to be processed. | -| ohos.i18n | getLineBreakText(): string8+ | Obtains the text to be processed. | -| ohos.i18n | current(): number8+ | Obtains the current position of a **BreakIterator** object in the text being processed. | -| ohos.i18n | first(): number8+ | Sets a **BreakIterator** object to the first breakable point. | -| ohos.i18n | last(): number8+ | Sets a **BreakIterator** object to the last breakable point. | -| ohos.i18n | next(index?: number): number8+ | Moves a **BreakIterator** object to the break point according to **index**. | -| ohos.i18n | previous(): number8+ | Moves a **BreakIterator** object to the previous break point. | -| ohos.i18n | following(offset: number): number8+ | Moves a **BreakIterator** object to the break point following the position specified by **offset**. | -| ohos.i18n | isBoundary(offset: number): boolean8+ | Determines whether a position is a break point. | +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| Transliterator | getAvailableIDs():Array9+ | Obtains the transliterator ID list. | +| Transliterator | getInstance(): Transliterator9+ | Creates a **Transliterator** object. | +| Transliterator | transform(text: string): string9+ | Obtains a transliterated string. | +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Obtains the transliterator ID list. + + Call **getAvailableIDs** to obtain the transliterator ID list. + An ID is in the **source-destination** format. For example, **ASCII-Latin** means to convert the transliterator ID from ASCII to Latin. + + ```js + let ids = I18n.Transliterator.getAvailableIDs(); // ids = ["ASCII-Latin", "Accents-Any", ... ], 671 languages in total + ``` + +3. Create a **Transliterator** object, and obtain the transliterated string. + + You can use the ID in the transliterator ID list as an input parameter of the **getInstance** API to create a **Transliterator** object. + Call **transform** to obtain the transliterated string. + + ```js + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); // Any-Latn means to convert any text to Latn text. + let transformText = transliterator.transform ("Hello"); // transformText = "nǐ hǎo" + ``` + +## Obtaining the Character Type + +[Unicode](../reference/apis/js-apis-i18n.md#unicode9) provides APIs to obtain character information, for example, whether a character is a digit or a space. + +### Available APIs + +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| Unicode | isDigit(char: string): boolean9+ | Checks whether the input character is a digit. | +| Unicode | isSpaceChar(char: string): boolean9+ | Checks whether the input character is a space. | +| Unicode | isWhitespace(char: string): boolean9+ | Checks whether the input character is a white space. | +| Unicode | isRTL(char: string): boolean9+ | Checks whether the input character is of the RTL language. | +| Unicode | isIdeograph(char: string): boolean9+ | Checks whether the input character is an ideographic character. | +| Unicode | isLetter(char: string): boolean9+ | Checks whether the input character is a letter. | +| Unicode | isLowerCase(char: string): boolean9+ | Checks whether the input character is a lowercase letter. | +| Unicode | isUpperCase(char: string): boolean9+ | Checks whether the input character is an uppercase letter. | +| Unicode | getType(char: string): string9+ | Obtains the type of a character.| ### How to Develop -1. Instantiate a **BreakIterator** object. +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` - Call the **getLineInstance** method to instantiate a **BreakIterator** object. +2. Check the input character has a certain attribute. + Check whether the input character is a digit. - ```js - var locale = "en-US" - var breakIterator = i18n.getLineInstance(locale); + ```js + let isDigit = I18n.Unicode.isDigit("1"); // isDigit = true + isDigit = I18n.Unicode.isDigit("a"); // isDigit = false ``` -2. Set and access the text that requires line breaking. + Check whether the input character is a space. - Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking. + ```js + let isSpaceChar = I18n.Unicode.isSpaceChar(" "); // isSpaceChar = true + isSpaceChar = I18n.Unicode.isSpaceChar("\n"); // isSpaceChar = false + ``` - - ```js - var text = "Apple is my favorite fruit"; - breakIterator.setLineBreakText(text); - var breakText = breakIterator.getLineBreakText(); + Check whether the input character is a white space. + + ```js + let isWhitespace = I18n.Unicode.isWhitespace(" "); // isWhitespace = true + isWhitespace = I18n.Unicode.isWhitespace("\n"); // isWhitespace = true + ``` + + Check whether the input character is of the RTL language. + + ```js + let isRTL = I18n.Unicode.isRTL(""); // isRTL = true (Arabic characters are written from left to right.) + isRTL = I18n.Unicode.isRTL("a"); // isRTL = false ``` -3. Obtain the current position of the **BreakIterator** object. + Check whether the input character is an ideographic character. - Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. + ```js + let isIdeograph = I18n.Unicode.isIdeograph("Hello"); // isIdeograph = true + isIdeograph = I18n.Unicode.isIdeograph("a"); // isIdeograph = false + ``` + Check whether the input character is a letter. - ```js - var pos = breakIterator.current(); + ```js + let isLetter = I18n.Unicode.isLetter("a"); // isLetter = true + isLetter = I18n.Unicode.isLetter("."); // isLetter = false ``` -4. Set the position of a **BreakIterator** object. + Check whether the input character is a lowercase letter. - The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. + ```js + let isLowerCase = I18n.Unicode.isLowerCase("a"); // isLetter = true + isLowerCase = I18n.Unicode.isLowerCase("A"); // isLetter = false + ``` - - ```js - var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text. - var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end. - // Move a BreakIterator object forward or backward by a certain number of break points. - // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. - // When the object is moved out of the text length range, -1 is returned. - var nextPos = breakIterator.next(-2); - var previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned. - // Move a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned. - var followingPos = breakIterator.following(10); + Check whether the input character is an uppercase letter. + + ```js + let isUpperCase = I18n.Unicode.isUpperCase("a"); // isUpperCase = false + isUpperCase = I18n.Unicode.isUpperCase("A"); // isUpperCase = true + ``` + +3. Obtain the character type. + + Call **getType** to obtain the character type. + + ```js + let type = I18n.Unicode.getType("a"); // type = U_LOWER_CASE_LETTER ``` -5. Determine whether a position is a break point. +## Obtaining the Sequence of Year, Month, and Day in a Date - Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| I18NUtil | getDateOrder(locale: string): string9+ | Checks the sequence of year, month, and day in a date. | + +### How to Develop - ```js - var isboundary = breakIterator.isBoundary(5); +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` - ``` \ No newline at end of file +2. Check the sequence of year, month, and day in a date. + + Call **getDateOrder** to obtain the sequence of year, month, and day in the date of the specified locale. + The API returns a string consisting of three parts, **y**, **L**, and **d**, which indicate the year, month, and day, respectively. The three parts are separated by using a hyphen (-), for example, **y-L-d**. + + ```js + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" indicates that the sequence of year, month, and day in Chinese is year-month-day. + ``` diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index f123a0b29a64a10b683f9fb90d163790e4f0524e..609af84500cecb0ce5bda8409216b6957182885f 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -1,38 +1,42 @@ -# Internationalization Development (Intl) +# intl Development -This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. For more details about APIs and their usage, see [Intl](../reference/apis/js-apis-intl.md). +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. For more details about APIs and their usage, see [intl](../reference/apis/js-apis-intl.md). -> **NOTE** -> -> In the code snippets in this document, **intl** refers to the name of the imported module. +The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. ## Setting Locale Information -Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minimize locale information. - +[Locale](../reference/apis/js-apis-intl.md#locale) provides APIs to maximize or minimize the locale information. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | - +| Locale | constructor()8+ | Instantiates a **Locale** object.| +| Locale | constructor(locale:string,options?:LocaleOptions) | Instantiates a **Locale** object based on the locale parameter and options.| +| Locale | toString():string | Converts locale information into a string.| +| Locale | maximize():Locale | Maximizes locale information.| +| Locale | minimize():Locale | Minimizes locale information.| ### How to Develop -1. Instantiate a **Locale** object. +1. Import the **intl** module. + + Importing an incorrect bundle can lead to unexpected API behavior. + + ```js + import Intl from '@ohos.intl' + ``` + +2. Instantiates a **Locale** object. - Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md#localeoptions) list. + Create a **Locale** object using the **Locale** constructor. This API receives a string representing the locale and an optional [attribute](../reference/apis/js-apis-intl.md#localeoptions) list. (Note that **intl** is the name of the imported module.) A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). - Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese. - Script: optional. It is represented by a four-letter code as defined in ISO-15924. The first letter is in uppercase, and the remaining three letters are in lowercase. For example, **Hant** represents the traditional Chinese, and **Hans** represents the simplified Chinese. - Country or region: optional. It is represented by two-letter code as defined in ISO-3166. Both letters are in uppercase. For example, **CN** represents China, and **US** represents the United States. - - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the Latin numbering system and Chinese calendar system are used. Extensions can also be passed via the second parameter. + - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the latn digital system and chinese calendar system are used. Extensions can also be passed via the second parameter. | Extended Parameter ID| Description| | -------- | -------- | | ca | Calendar algorithm.| @@ -40,305 +44,346 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim | hc | Hour cycle.| | nu | Numbering system.| | kn | Whether numeric collation is used when sorting or comparing strings.| - | kf | Whether upper case or lower case is considered when sorting or comparing strings.| + | kf | Whether capitalization is considered when sorting or comparing strings.| ```js - var locale = "zh-CN"; - var options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; - var localeObj = new intl.Locale(locale, options); + let locale = "zh-CN"; + let options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; + let localeObj = new Intl.Locale(locale, options); ``` -2. Obtain the string representing a **Locale** object. +3. Obtain the string representing a **Locale** object. - Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. - + Call **toString** to obtain the string representing a **Locale** object, including the language, region, and other options. + ```js - var localeStr = localeObj.toString(); + let localeStr = localeObj.toString(); // localeStr = "zh-CN-u-ca-chinese-co-pinyin-kf-false ``` -3. Maximize locale information. +4. Maximize locale information. - Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. - + Call **maximize** to maximize locale information; that is, supplement the missing script and region information. + ```js - var maximizedLocale = localeObj.maximize(); + let maximizedLocale = localeObj.maximize(); + let maximizedLocaleStr = maximizedLocale.toString(); // localeStr = "zh-Hans-CN-u-ca-chinese-co-pinyin-kf-false ``` -4. Minimize locale information. +5. Minimize locale information. - Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. - + Call **minimize** to minimize locale information; that is, delete the unnecessary script and region information. + ```js - var minimizedLocale = localeObj.minimize(); + let minimizedLocale = localeObj.minimize(); + let minimizedLocaleStr = minimizedLocale.toString(); // zh-u-ca-chinese-co-pinyin-kf-false ``` - ## Formatting the Date and Time -Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to format the date and time for a specific locale. - +[DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) provides APIs to format the date and time for the specified locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | - +| DateTimeFormat | constructor()8+ | Creates a **DateTimeFormat** object.| +| DateTimeFormat | constructor(locale:string\|Array<string>,options?:DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes.| +| DateTimeFormat | format(date:Date):string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object.| +| DateTimeFormat | formatRange(startDate:Date,endDate:Date):string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object.| +| DateTimeFormat | resolvedOptions():DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object.| ### How to Develop -1. Instantiate a **DateTimeFormat** object. - - Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var dateTimeFormat = new intl.DateTimeFormat(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). - +2. Instantiate a **DateTimeFormat** object. + + Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. + ```js - var options = {dateStyle: "full", timeStyle: "full"}; - var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options); + let dateTimeFormat = new Intl.DateTimeFormat(); ``` -2. Format the date and time. - - Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. + Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). ```js - var date = new Date(); - var formatResult = dateTimeFormat.format(date); + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); ``` -3. Format a period. +3. Format the date and time. - Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. - + Call **format** to format a **Date** object. A string is returned as the formatting result. + ```js - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); + let date = new Date(2022, 12, 12, 12, 12, 12); + let formatResult = dateTimeFormat.format(date); // formatResult = "January 12, 2023, Thursday, 12:12:12 pm, China Standard Time" ``` -4. Obtain attributes of the **DateTimeFormat** object. +4. Format a period. - Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. - + Call **formatRange** to format a period. This API requires the input of two **Date** objects, which respectively indicate the start date and end date of a period. A string is returned as the formatting result. + ```js - var options = dateTimeFormat.resolvedOptions(); + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formatRangeResult = datefmt.formatRange(startDate, endDate); // formatRangeResult = "17/12/2021-18/12/2021" ``` +5. Access the attributes of the **DateTimeFormat** object. -## Formatting Numbers + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **DateTimeFormat** object. + + ```js + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); + let resolvedOptions = dateTimeFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "calendar": "gregorian", "dateStyle":"full", "timeStyle":"full", "timeZone": "CST"} + ``` -Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale. +## Number Formatting +[NumberFormat](../reference/apis/js-apis-intl.md#numberformat) provides APIs to implement the number formatting specific to a locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | - +| NumberFormat | constructor()8+ | Creates a **NumberFormat** object for the specified locale.| +| NumberFormat | constructor(locale:string\|Array<string>,options?:NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes.| +| NumberFormat | format(number:number):string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object.| +| NumberFormat | resolvedOptions():NumberOptions | Obtains the attributes of the **NumberFormat** object.| ### How to Develop -1. Instantiate a **NumberFormat** object. - - Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var numberFormat = new intl.NumberFormat(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). - +2. Instantiate a **NumberFormat** object. + + Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **NumberFormat** object (**intl** is the name of the imported module). + ```js - var options = {compactDisplay: "short", notation: "compact"}; - var numberFormat = new intl.NumberFormat("zh-CN", options); + let numberFormat = new Intl.NumberFormat(); ``` -2. Format a number. - - Call the **format** method to format a number. A string is returned as the formatting result. + Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). ```js - var number = 1234.5678 - var formatResult = numberFormat.format(number); + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); ``` -3. Obtain attributes of the **NumberFormat** object. +3. Format a number. - Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. - + Call **format** to format a number. A string is returned as the formatting result. + ```js - var options = numberFormat.resolvedOptions(); + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); + let number = 1234.5678 + let formatResult = numberFormat.format(number); // formatResult = "1235" ``` +4. Access the attributes of the **NumberFormat** object. -## Sorting Strings + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **NumberFormat** object. + + ```js + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); + let resolvedOptions = numberFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "compactDisplay": "short", "notation": "compact", "numberingSystem": "Latn"} + ``` -Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. +## String Sorting +Users in different regions have different requirements for string sorting. [Collator](../reference/apis/js-apis-intl.md#collator8) provides APIs to sort character strings specific to a locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | - +| Collator | constructor()8+ | Creates a **Collator** object.| +| Collator | constructor(locale:string\|Array<string>,options?:CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes.| +| Collator | compare(first:string,second:string):number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object.| +| Collator | resolvedOptions():CollatorOptions8+ | Obtains the attributes of the **Collator** object.| ### How to Develop -1. Instantiate a **Collator** object. - - Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var collator = new intl.Collator(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). - +2. Instantiate a **Collator** object. + + Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **Collator** object (**intl** is the name of the imported module). + ```js - var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); + let collator = new Intl.Collator(); ``` -2. Compare two strings. - - Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'. ```js - var str1 = "first string"; - var str2 = "second string"; - var compareResult = collator.compare(str1, str2); + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); ``` -3. Obtain attributes of the **Collator** object. +3. Compare two strings. - Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. - + Call **compare** to compare two input strings. This API returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + ```js - var options = collator.resolvedOptions(); + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); + let str1 = "first string"; + let str2 = "second string"; + let compareResult = collator.compare(str1, str2); // compareResult = -1 + str1 = "first"; + str2 = "First"; + compareResult = collator.compare(str1, str2); // compareResult = -1 ``` +4. Access the attributes of the **Collator** object. -## Determining the Singular-Plural Type + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **Collator** object. + + ```js + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); + let options = collator.resolvedOptions(); // options = {"localeMatcher": "best fit", "locale": "zh-CN", "usage": "sort", "sensitivity": "variant", "ignorePunctuation": "false", "numeric": false, "caseFirst": "false", "collation": "default"} + ``` -Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. +## Determining the Singular-Plural Type +According to grammars in certain languages, the singular or plural form of a noun depends on the number prior to the noun. [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) provides APIs to determine the singular-plural type for a specific locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| PluralRules | constructor()8+ | Creates a **PluralRules** object.| +| PluralRules | constructor(locale:string\|Array<string>,options?:PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes.| +| PluralRules | select(n:number):string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object.| ### How to Develop -1. Instantiate a **PluralRules** object. - - Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var pluralRules = new intl.PluralRules(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). - +2. Instantiate a **PluralRules** object. + + Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **PluralRules** object (**intl** is the name of the imported module). + ```js - var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + let pluralRules = new Intl.PluralRules(); ``` -2. Determine the singular-plural type. - - Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). ```js - var number = 1234.5678 - var categoryResult = plurals.select(number); + let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); ``` +3. Determine the singular-plural type. -## Formatting the Relative Time + Call **select** to determine the singular-plural type for an input number. This API returns a string as the category of the input number, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + + ```js + let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + let number = 1234.5678 + let categoryResult = pluralRules.select(number); // categoryResult = "other" + ``` -Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale. +## Formatting Relative Time +[RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) provides APIs to format the relative time for a specific locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | - +| RelativeTimeFormat | constructor()8+ | Creates a **RelativeTimeFormat** object.| +| RelativeTimeFormat | constructor(locale:string\|Array<string>,options?:RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes.| +| RelativeTimeFormat | format(value:number,unit:string):string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.| +| RelativeTimeFormat | formatToParts(value:number,unit:string):Array<object>8+ | Obtains each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.| +| RelativeTimeFormat | resolvedOptions():RelativeTimeFormatResolvedOptions8+ | Obtains the attributes of the **RelativeTimeFormat** object.| ### How to Develop -1. Instantiate a **RelativeTimeFormat** object. +1. Import the **intl** module. - Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object. + Importing an incorrect bundle can lead to unexpected API behavior. + + ```js + import Intl from '@ohos.intl' + ``` + +2. Instantiate a **RelativeTimeFormat** object. + Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **RelativeTimeFormat** object (**intl** is the name of the imported module). ```js - var relativeTimeFormat = new intl.RelativeTimeFormat(); + let relativeTimeFormat = new Intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). ```js - var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); ``` -2. Format the relative time. +3. Format the relative time. - Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. - + Call **format** to format the relative time. This API receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. A string is returned as the formatting result. + ```js - var number = 2; - var unit = "year" - var formatResult = relativeTimeFormat.format(number, unit); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let number = 2; + let unit = "year" + let formatResult = relativeTimeFormat.format(number, unit); // 2 years later ``` -3. Obtain each part of the relative time format. +4. Obtain each part of the relative time format. - Upon obtaining each part of the relative time format, customize the relative time formatting result. - + On obtaining each part of the relative time format, customize the relative time formatting result. + ```js - var number = 2; - var unit = "year" - var formatResult = relativeTimeFormat.formatToParts(number, unit); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let number = 2; + let unit = "year" + let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}] ``` -4. Obtain attributes of the **RelativeTimeFormat** object. +5. Access the attributes of the **RelativeTimeFormat** object. - Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). - + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **RelativeTimeFormat** object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). + ```js - var options = numberFormat.resolvedOptions(); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"} ``` ## Samples diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index 699eb7cb6cae5f198c1620e22b7c3f0df4a90813..0b5b382d72fec98bfa18c3cfdee7bd61ef713da1 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -3,27 +3,30 @@ ## Introduction **AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. - Before calling the APIs, be familiar with the following terms: - **Audio interruption**: When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. - **Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. - **Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). -- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus preemption occurs. Focus preemption triggers focus transfer, and the **AudioRenderer** instance that originally has the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to set the independent mode. +- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus transfer is triggered by focus preemption. When focus transfer occurs, the **AudioRenderer** instance that is having the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to switch to the independent mode. ## Working Principles The following figure shows the audio renderer state transitions. -Figure 1 Audio renderer state transitions +**Figure 1** Audio renderer state transitions ![audio-renderer-state](figures/audio-renderer-state.png) - **PREPARED**: The audio renderer enters this state by calling **create()**. + - **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. -- **PAUSED**: The audio renderer in the **RUNNING** state can call **pause()** to pause the audio playback. After the audio playback is paused, it can call **start()** to resume the playback. -- **STOPPED**: The audio renderer in the **PAUSED** or **RUNNING** state can call **stop()** to stop the playback. -- **RELEASED**: The audio renderer in the **PREPARED**, **PAUSED**, or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state. + +- **PAUSED**: The audio renderer enters this state by calling **pause()** when it is in the **RUNNING** state. When the audio playback is paused, it can call **start()** to resume the playback. + +- **STOPPED**: The audio renderer enters this state by calling **stop()** when it is in the **PAUSED** or **RUNNING** state. + +- **RELEASED**: The audio renderer enters this state by calling **release()** when it is in the **PREPARED**, **PAUSED**, or **STOPPED** state. In this state, the audio renderer releases all occupied hardware and software resources and will not transit to any other state. ## How to Develop @@ -62,7 +65,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ```js async function startRenderer() { let state = audioRenderer.state; - // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. + // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state when start() is called. if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); @@ -258,8 +261,8 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; await audioRenderer.setInterruptMode(interruptMode); - // Set the volume of the stream to 10. - let volume : number = 10; + // Set the volume of the stream to 0.5. + let volume : number = 0.5; await audioRenderer.setVolume(volume); ``` @@ -303,7 +306,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th case audio.InterruptHint.INTERRUPT_HINT_RESUME: startRenderer(); break; - // Notify the application that the audio stream is interrupted. The application determines whether to continue. (In this example, the application pauses the rendering.) + // Notify the application that the audio stream is interrupted. The application then determines whether to continue. (In this example, the application pauses the rendering.) case audio.InterruptHint.INTERRUPT_HINT_PAUSE: isPlay = false; pauseRenderer(); @@ -312,7 +315,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th } }); - audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be received. + audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be listened for. ``` 10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. @@ -358,7 +361,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th ```js try { - audioRenderer.on('invalidInput', () => { // The string does not match. + audioRenderer.on('invalidInput', () => { // The string is invalid. }) } catch (err) { console.info(`Call on function error, ${err}`); // The application throws exception 401. @@ -373,7 +376,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th 14. (Optional) Refer to the complete example of **on('audioInterrupt')**. - Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRenderer1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. + Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRender1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. ```js async runningAudioRender1(){ @@ -429,7 +432,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th let rlen = 0; rlen += bufferSize; - // 1.7 Render the original audio data in the buffer by using audioRenderer. + // 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(); @@ -505,7 +508,7 @@ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. Th let rlen = 0; rlen += bufferSize; - // 2.7 Render the original audio data in the buffer by using audioRenderer. + // 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(); diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md index 420d09121f86b7a4612c2e7ad6fe5f29831be80b..f4f5ac69bc57146d6ee63dde171da7628e0a108d 100644 --- a/en/application-dev/napi/mindspore-lite-guidelines.md +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -15,7 +15,6 @@ Before getting started, you need to understand the following basic concepts: **Float16 inference**: a mode in which Float16 is used for inference. Float16, also called half-precision, uses 16 bits to represent a number. - ## Available APIs APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. ### Context APIs @@ -54,6 +53,33 @@ The following figure shows the development process for MindSpore Lite model infe **Figure 1** Development process for MindSpore Lite model inference ![how-to-use-mindspore-lite](figures/01.png) +Before moving to the main process, you need to reference related header files and compile functions to generate random input. + +Example code: + +```c +#include +#include +#include "mindspore/model.h" + +// Generate random input. +int GenerateInputDataWithRandom(OH_AI_TensorHandleArray inputs) { + for (size_t i = 0; i < inputs.handle_num; ++i) { + float *input_data = (float *)OH_AI_TensorGetMutableData(inputs.handle_list[i]); + if (input_data == NULL) { + printf("MSTensorGetMutableData failed.\n"); + return OH_AI_STATUS_LITE_ERROR; + } + int64_t num = OH_AI_TensorGetElementNum(inputs.handle_list[i]); + const int divisor = 10; + for (size_t j = 0; j < num; j++) { + input_data[j] = (float)(rand() % divisor) / divisor; // 0--0.9f + } + } + return OH_AI_STATUS_SUCCESS; +} +``` + The development process consists of the following main steps: 1. Prepare the required model. @@ -61,7 +87,7 @@ The development process consists of the following main steps: The required model can be downloaded directly or obtained using the model conversion tool. - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. - - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/benchmark_tool.html) to convert it to the `.ms` format. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/zh-CN/r1.5/use/downloads.html#id1) to convert it to the `.ms` format. 2. Create a context, and set parameters such as the number of runtime threads and device type. @@ -101,8 +127,8 @@ The development process consists of the following main steps: return OH_AI_STATUS_LITE_ERROR; } - // Load and build the model. The model type is OH_AI_ModelTypeMindIR. - int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_ModelTypeMindIR, context); + // Load and build the model. The model type is OH_AI_MODELTYPE_MINDIR. + int ret = OH_AI_ModelBuildFromFile(model, argv[1], OH_AI_MODELTYPE_MINDIR, context); if (ret != OH_AI_STATUS_SUCCESS) { printf("OH_AI_ModelBuildFromFile failed, ret: %d.\n", ret); OH_AI_ModelDestroy(&model); @@ -193,7 +219,7 @@ The development process consists of the following main steps: dl ) ``` - - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.cmake"`. + - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/ohos-sdk/linux/native/build/cmake/ohos.toolchain.camke"`. - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. @@ -213,4 +239,4 @@ The development process consists of the following main steps: Tensor name: Softmax-65, tensor size is 4004 ,elements num: 1001. output data is: 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 - ``` + ``` \ No newline at end of file diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index 188b4f1336e2c56562f594e42dc26cabf8a8fc55..5113c413d523b9d58363b78ac94ba42cc1954e9d 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -1,12 +1,14 @@ # Using Native APIs in Application Projects -OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. Currently, the **ace_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository. +OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see **libnapi.ndk.json** in the ace_napi repository. ## How to Develop -The IDE 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 `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. +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. ## Development Guidelines @@ -17,7 +19,7 @@ You can `import` the native .so that contains the JS processing logic. For examp ### .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'`. +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'**. ### JS Objects and Threads @@ -28,7 +30,7 @@ The Ark engine prevents NAPIs from being called to operate JS objects in non-JS ### Importing Header Files -Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, when only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. +Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, if only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. ### napi_create_async_work @@ -50,11 +52,11 @@ napi_status napi_create_async_work(napi_env env, -## Example 1: Encapsulating Synchronous and Asynchronous APIs for the Storage Module +## Encapsulating Synchronous and Asynchronous APIs for the Storage Module ### Overview -This example shows how to encapsulate the synchronous and asynchronous APIs of the storage module. The storage module implements the functions of storing, obtaining, deleting, and clearing data. +This example shows how to encapsulate the synchronous and asynchronous APIs of the **Storage** module. The **Storage** module implements the functions of storing, obtaining, deleting, and clearing data. ### API Declaration @@ -79,11 +81,11 @@ export default storage; ### Implementation -You can obtain the complete code from `sample/native_module_storage/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. +You can obtain the complete code from sample/native_module_storage/ in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. -#### Registering the Module +**1. Register the module.** -Register four synchronous APIs (`getSync`, `setSync`, `removeSync`, and`clearSync`) and four asynchronous APIs (`get`, `set`, `remove`, and `clear`). +Register four synchronous APIs (**getSync**, **setSync**, **removeSync**, and **clearSync**) and four asynchronous APIs (**get**, **set**, **remove**, and **clear**). ```c++ /*********************************************** @@ -122,9 +124,9 @@ extern "C" __attribute__((constructor)) void StorageRegister() } ``` -#### Implementing getSync +**2. Implement getSync.** -The **getSync** function registered for the storage module is **JSStorageGetSync**. Obtain data from `gKeyValueStorage`, create a string object, and return it. +The **getSync** function registered for the **Storage** module is **JSStorageGetSync**. Obtain data from **gKeyValueStorage**, create a string object, and return the object created. ```c static napi_value JSStorageGetSync(napi_env env, napi_callback_info info) @@ -168,9 +170,9 @@ static napi_value JSStorageGetSync(napi_env env, napi_callback_info info) } ``` -#### Implementing get +**3. Implement get().** -The `get` function registered for the storage module is `JSStorageGet`. +The **get** function registered for the **Storage** module is **JSStorageGet**. ```c static napi_value JSStorageGet(napi_env env, napi_callback_info info) @@ -268,7 +270,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info) } ``` -### JS Sample Code +**JS Sample Code** ```js import storage from 'libstorage.so'; @@ -292,11 +294,11 @@ export default { -## Example 2: Binding Native and JS Objects for the NetServer Module +## Binding Native and JS Objects for the NetServer Module ### Overview -This example shows how to implement the `on/off/once` method and bind C++ and JS objects using the **wrap** API. The NetServer module implements the network service. +This example shows how to implement the **on**, **off**, and **once** methods and bind C++ and JS objects using **wrap()**. The **NetServer** module implements the network service. ### API Declaration @@ -312,9 +314,9 @@ export class NetServer { ### Implementation -You can obtain the complete code from `sample/native_module_netserver/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. +You can obtain the complete code from **sample/native_module_netserver/** in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. -#### Registering the Module +**1. Register the module.** ```c static napi_value NetServer::Export(napi_env env, napi_value exports) @@ -338,7 +340,7 @@ static napi_value NetServer::Export(napi_env env, napi_value exports) } ``` -#### Binding C++ and JS Objects in a Constructor +**2. Bind C++ and JS objects in a constructor.** ```c napi_value NetServer::JS_Constructor(napi_env env, napi_callback_info cbinfo) @@ -365,7 +367,7 @@ napi_value NetServer::JS_Constructor(napi_env env, napi_callback_info cbinfo) } ``` -#### Obtaining the C++ Object from the JS Object +**3. Obtain a C++ object from a JS object.** ```c napi_value NetServer::JS_Start(napi_env env, napi_callback_info cbinfo) @@ -398,7 +400,7 @@ napi_value NetServer::JS_Start(napi_env env, napi_callback_info cbinfo) } ``` -After `netServer->Start` is executed, call back the `start` event registered by `on`. +After **netServer->Start** is executed, call back the **start** event registered by **on()**. ```c int NetServer::Start(int port) @@ -435,7 +437,7 @@ int NetServer::Start(int port) } ``` -#### Registering Events (on) +**4. Call on() to register an event observer.** ```c napi_value NetServer::JS_On(napi_env env, napi_callback_info cbinfo) @@ -475,7 +477,7 @@ napi_value NetServer::JS_On(napi_env env, napi_callback_info cbinfo) } ``` -### JS Sample Code +**JS Sample Code** ```javascript import { NetServer } from 'libnetserver.so'; @@ -491,7 +493,7 @@ export default { -## Example 3: Calling Back a JS API in a Non-JS Thread +## Calling Back a JS API in a Non-JS Thread ### Overview @@ -499,11 +501,11 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp ### Implementation -You can obtain the complete code from `sample/native_module_callback/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. +You can obtain the complete code from **sample/native_module_callback/** in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository. -#### Registering the Module +**1. Register the module.** -Register the `test` API to pass in a parameter. +Register the **test** API to pass in a parameter. ```c++ /*********************************************** @@ -536,7 +538,7 @@ extern "C" __attribute__((constructor)) void CallbackTestRegister() } ``` -#### Obtaining the Loop in env and Throwing the Task to the JS Thread +**2. Obtain the loop in env and throw the task to a JS thread.** ```c++ #include @@ -627,7 +629,7 @@ static napi_value JSTest(napi_env env, napi_callback_info info) } ``` -### JS Sample Code +**JS Sample Code** ```js import callback from 'libcallback.so'; diff --git a/en/application-dev/notification/Readme-EN.md b/en/application-dev/notification/Readme-EN.md index dccfc8dbc4c59611db4aa53ff8a5a295cbba4d46..bf85581053f30d6aa56e0218c51339ef6ee3f268 100644 --- a/en/application-dev/notification/Readme-EN.md +++ b/en/application-dev/notification/Readme-EN.md @@ -1,9 +1,10 @@ -# Common Event and Notification +# Notification + +- [Notification Overview](notification-overview.md) +- [Notification Subscription (Open Only to System Applications)](notification-subscription.md) +- [Enabling Notification](notification-enable.md) +- Publishing a Notification + - [Publishing a Basic Notification](text-notification.md) + - [Publishing a Progress Notification](progress-bar-notification.md) + - [Adding a WantAgent Object to a Notification](notification-with-wantagent.md) -- [Common Event and Notification Overview](notification-brief.md) -- [Common Event Development](common-event.md) -- [Notification Development](notification-guidelines.md) -- Agent-Powered Scheduled Reminder - - [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md) - - [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md) -- [Debugging Assistant Usage](assistant-guidelines.md) diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md deleted file mode 100644 index 5d83cf443c0f629fcb471a6c12ccd3069ac2e593..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/assistant-guidelines.md +++ /dev/null @@ -1,134 +0,0 @@ -# Debugging Assistant Usage - -The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell. - -## cem Debugging Assistant - -### publish - -* Function - - Publishes a common event. - -* Usage - - `cem publish []` - - The table below describes the available options. - - | Option | Description | - | ------------ | ------------------------------------------ | - | -e/--event | Indicates the name of the common event to publish. Mandatory. | - | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. | - | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | - | -c/--code | Indicates the result code of the common event. Optional. | - | -d/--data | Indicates the data carried in the common event. Optional. | - | -h/--help | Indicates the help Information | - -* Example - - `cem publish --event "testevent"` - - Publish a common event named **testevent**. - - ![cem-publish-event](figures/cem-publish-event.png) - - - - `cem publish -e "testevent" -s -o -c 100 -d "this is data" ` - - Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**. - - ![cem-publish-all](figures/cem-publish-all.png) - -### dump - -* Function - - Displays information about common events. - -* Usage - - `cem dump []` - - The table below describes the available options. - - | Option | Description | - | ---------- | -------------------------------------------- | - | -a/--all | Displays information about all common events that have been sent since system startup. | - | -e/--event | Displays information about a specific event. | - | -h/--help | Displays the help information. | - -* Example - -​ `cem dump -e "testevent"` - -​ Display information about the common event testevent. - -​ ![cem-dump-e](figures/cem-dump-e.png) - -### help - -* Function - - Displays the help information. - -* Usage - - `cem help` - -* Example - - ![cem-help](figures/cem-help.png) - - - -## anm Debugging Assistant - -### dump - -* Function - - Displays information about notifications. - -* Usage - - `anm dump []` - - The table below describes the available options. - - | Option | Description | - | ---------------- | ---------------------------------------- | - | -A/--active | Displays information about all active notifications. | - | -R/--recent | Displays information about the recent notifications. | - | -D/--distributed | Displays information about distributed notifications from other devices. | - | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. | - | -h/--help | Displays the help information. | - -* Example - - `anm dump -A` - - Display information about all active notifications. - - ![anm-dump-A](figures/anm-dump-A.png) - - - - `anm dump --setRecentCount 10` - - Set the number of the cached recent notifications to be displayed to **10**. - -### help - -* Function - - Displays the help information. - -* Usage - - `anm help` - -* Example - - ![anm-help](figures/anm-help.png) diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md deleted file mode 100644 index 71ffeb0b07acfb088988163a68f72882d267f49b..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md +++ /dev/null @@ -1,167 +0,0 @@ -# Agent-Powered Scheduled Reminder Development - -## When to Use - -You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - - -## Available APIs - -**reminderAgent** encapsulates the APIs for publishing and canceling reminders. - -For details about the APIs, see [reminderAgent](../reference/apis/js-apis-reminderAgent.md). - -**Table 1** Major APIs in reminderAgent - -| Name| Description| -| -------- | -------- | -| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | -| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| -| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application.| -| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application.| -| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder.| -| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type.| - -## How to Develop - -> **NOTE** -> -> 1. To publish a reminder through the reminder agent, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. -> -> 2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). - -1. Define a reminder agent. - - Sample code for defining a reminder agent for a countdown timer: - ```js - import reminderAgent from '@ohos.reminderAgent'; - import notification from '@ohos.notification'; - export default { - // ArkTS project: - let timer : reminderAgent.ReminderRequestTimer = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10, - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - } - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - } - ``` - - Sample code for defining a reminder agent for a calendar event: - - ```js - // ArkTS project: - let calendar : reminderAgent.ReminderRequestCalendar = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, - dateTime: { - year: 2050, - month: 7, - day: 30, - hour: 11, - minute: 14, - second: 30 - }, - repeatMonths: [1], - repeatDays: [1], - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - ``` - - Sample code for defining a reminder agent for an alarm: - - ```js - // ArkTS project: - let alarm : reminderAgent.ReminderRequestAlarm = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, - hour: 11, - minute: 14, - daysOfWeek: [0], - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION - } - ``` - -2. Publish a countdown reminder. - ```js - startTimer() { - reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ - this.printInfo(JSON.stringify(err)); - this.printInfo("reminderId:" + reminderId); - }); - } - ``` - - HML page code: - ```html -
- -
- ``` diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-overview.md b/en/application-dev/notification/background-agent-scheduled-reminder-overview.md deleted file mode 100644 index a9eccc77a9fecd9d1044eead091bfe9ffb097310..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/background-agent-scheduled-reminder-overview.md +++ /dev/null @@ -1,4 +0,0 @@ -# Agent-Powered Scheduled Reminder Overview - -Your application can call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md deleted file mode 100644 index dfb611ea572b80486756faaa4b004513cd6858a7..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/common-event.md +++ /dev/null @@ -1,172 +0,0 @@ -# Common Event Development -## Introduction -OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. - -Common events are classified into system common events and custom common events. - -+ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation. - -+ Custom common event: customized by applications to implement cross-application event communication. - -Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. - -## Common Event Subscription Development - -### When to Use -You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support). - -### Available APIs -| API | Description| -| ---------------------------------------------------------------------------------------------- | ----------- | -| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| -| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | -| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| - -### How to Develop -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). - -```js -// Used to save the created subscriber object for subsequent subscription and unsubscription. -private subscriber = null - -// Subscriber information -var subscribeInfo = { - events: ["event"], -} -``` - -3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. - -```js -// Callback for subscriber creation. -commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { - if (err.code) { - console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]CreateSubscriber") - this.subscriber = subscriber - this.result = "Create subscriber succeed" - } -}) -``` - -4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). - -```js -// Callback for common event subscription. -if (this.subscriber != null) { - commonEvent.subscribe(this.subscriber, (err, data) => { - if (err.code) { - console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data)) - this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code - } - }) - this.result = "Subscribe succeed" -} else { - prompt.showToast({ message: "Need create subscriber" }) -} -``` - -## Common Event Publishing Development - -### When to Use -You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. - -### Available APIs -| API | Description| -| ---------------------------------- | ------ | -| publish(event: string, callback: AsyncCallback) | Publishes a common event.| -| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| - -### How to Develop -#### Development for Publishing a Common Event -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Pass in the common event name and callback, and publish the event. - -```js -// Publish a common event. -commonEvent.publish("event", (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish1") - } -}) -``` - -#### Development for Publishing a Common Event with Given Attributes -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent' -``` - -2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). - -```js -// Attributes of a common event. -var options = { - code: 1, // Result code of the common event - data: "initial data";// Result data of the common event -} -``` - -3. Pass in the common event name, attributes of the common event, and callback, and publish the event. - -```js -// Publish a common event. -commonEvent.publish("event", options, (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish2") - } -}) -``` - -## Common Event Unsubscription Development - -### When to Use -You can use the **unsubscribe** API to unsubscribe from a common event. - -### Available APIs -| API | Description| -| ---------------------------------- | ------ | -| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| - -### How to Develop -1. Import the **commonEvent** module. - -```js -import commonEvent from '@ohos.commonEvent'; -``` - -2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#common-event-subscription-development). -3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. - -```js -if (this.subscriber != null) { - commonEvent.unsubscribe(this.subscriber, (err) => { - if (err.code) { - console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err)) - } else { - console.log("[CommonEvent]Unsubscribe") - this.subscriber = null - this.result = "Unsubscribe succeed" - } - }) -} -``` diff --git a/en/application-dev/notification/figures/anm-help.png b/en/application-dev/notification/figures/anm-help.png deleted file mode 100644 index d80ac8e76a70c2be383f0a05a12e3e707dcf242b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/anm-help.png and /dev/null differ diff --git a/en/application-dev/notification/figures/ans.png b/en/application-dev/notification/figures/ans.png deleted file mode 100644 index 8be552d2acedbef962326365fb2d19ded3838c14..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/ans.png and /dev/null differ diff --git a/en/application-dev/notification/figures/cem-help.png b/en/application-dev/notification/figures/cem-help.png deleted file mode 100644 index 8ca4bc0605f9c1f75a8cb45f8ab77c9c5d6f04e4..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/cem-help.png and /dev/null differ diff --git a/en/application-dev/notification/figures/ces.png b/en/application-dev/notification/figures/ces.png deleted file mode 100644 index b1aa5438a19ac79899e0f45791f3e1a79e4242dc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/ces.png and /dev/null differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001416585590.png b/en/application-dev/notification/figures/en-us_image_0000001416585590.png new file mode 100644 index 0000000000000000000000000000000000000000..9da6812580fd6c7d785391c652104ef0698ce2bc Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416585590.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001416745530.png b/en/application-dev/notification/figures/en-us_image_0000001416745530.png new file mode 100644 index 0000000000000000000000000000000000000000..7a6fd0d9304abef2eb240a3c78a93b73bb9237af Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416745530.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062434.png b/en/application-dev/notification/figures/en-us_image_0000001417062434.png new file mode 100644 index 0000000000000000000000000000000000000000..07db3298f0db1c3357624b44d271dc1e6f97ea9e Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062434.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062446.png b/en/application-dev/notification/figures/en-us_image_0000001417062446.png new file mode 100644 index 0000000000000000000000000000000000000000..c197fd6293f41890b2bfcf17a28a1477e8aa6d96 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062446.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462297.png b/en/application-dev/notification/figures/en-us_image_0000001466462297.png new file mode 100644 index 0000000000000000000000000000000000000000..a07d9e818677e9364ad3239e61ce198471b68603 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462297.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462305.png b/en/application-dev/notification/figures/en-us_image_0000001466462305.png new file mode 100644 index 0000000000000000000000000000000000000000..740f4b79a9ee234008cad6cf3616a8f213569476 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462305.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582017.png b/en/application-dev/notification/figures/en-us_image_0000001466582017.png new file mode 100644 index 0000000000000000000000000000000000000000..1652d9111be2a27863fe2322c4feb577bab22ae9 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582017.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582045.png b/en/application-dev/notification/figures/en-us_image_0000001466582045.png new file mode 100644 index 0000000000000000000000000000000000000000..4040452a87bc69ae8fa0eb9b55ca77ac32bdb2d8 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582045.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782025.png b/en/application-dev/notification/figures/en-us_image_0000001466782025.png new file mode 100644 index 0000000000000000000000000000000000000000..d8e45c1746ab419a8056f9493c8796cfb734d2d0 Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782025.png differ diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782033.png b/en/application-dev/notification/figures/en-us_image_0000001466782033.png new file mode 100644 index 0000000000000000000000000000000000000000..218e5fcef6d163113c9037028215297ef626fcfa Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782033.png differ diff --git a/en/application-dev/notification/figures/notification-with-wantagent.png b/en/application-dev/notification/figures/notification-with-wantagent.png new file mode 100644 index 0000000000000000000000000000000000000000..234ef895c918404598cf7640f9d072de2bb2d0d0 Binary files /dev/null and b/en/application-dev/notification/figures/notification-with-wantagent.png differ diff --git a/en/application-dev/notification/figures/notification.png b/en/application-dev/notification/figures/notification.png deleted file mode 100644 index 18dcb99b0c531a19698f749105d88db91043837a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/notification/figures/notification.png and /dev/null differ diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md deleted file mode 100644 index 75237412fdf29d88843a9f23fa653f64f2de7c86..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/notification-brief.md +++ /dev/null @@ -1,20 +0,0 @@ -# Common Event and Notification Overview - -The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more. - -Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. - -![ces](figures/ces.png) - -- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events. -- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications. - -The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: - -- Display received SMS messages and instant messages. -- Display push messages of applications, such as advertisements, version updates, and news notifications. -- Display ongoing events, such as music playback, navigation information, and download progress. - -Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions. - -![ans](figures/ans.png) diff --git a/en/application-dev/notification/notification-enable.md b/en/application-dev/notification/notification-enable.md new file mode 100644 index 0000000000000000000000000000000000000000..12aa4f41eb1570d707b4c65310cefe6aa45e1b17 --- /dev/null +++ b/en/application-dev/notification/notification-enable.md @@ -0,0 +1,49 @@ +# Enabling Notification + + +To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time. + + **Figure 1** Dialog box prompting the user to enable notification + +![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png) + + +- Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled. + +- The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) is called later. The user can manually enable notification as follows. + + | 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. | + | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | + | ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) | + + +## Available APIs + +For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification). + +**Table 1** Notification APIs + +| Name | Description | +| -------- | -------- | +| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback<boolean>): void | Checks whether notification is enabled.
**NOTE**
This is a system API and cannot be called by third-party applications. | +| setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback<void>): void | Sets whether to enable notification. Notification can be enabled or disabled in **Notifications** of the target application under **Settings** > **Apps & services** > **Apps**.
**NOTE**
This is a system API and cannot be called by third-party applications.| +| requestEnableNotification(callback: AsyncCallback<void>): void | Requests notification to be enabled. When called for the first time, this API displays a dialog box prompting the user to enable notification. | + + +## How to Develop + +1. Import the **NotificationManager** module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +2. Call the API to request notification to be enabled. + + ```ts + notificationManager.requestEnableNotification().then(() => { + console.info(`[ANS] requestEnableNotification success`); + }).catch((err) => { + console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`); + }); + ``` diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md deleted file mode 100644 index fb73f274202aafd9ff852201ca2fb8c5116aba50..0000000000000000000000000000000000000000 --- a/en/application-dev/notification/notification-guidelines.md +++ /dev/null @@ -1,258 +0,0 @@ - - -# Notification Development - -## When to Use - -OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI. - -Below are some typical use cases for notifications: - -- Display received SMS messages and instant messages. -- Display push messages of applications, such as advertisements and version updates. -- Display ongoing events, such as navigation information and download progress. - - - -## Notification Service Process - -The notification service process involves the ANS subsystem, notification sender, and notification subscriber. - -A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber. - -System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database. - -![1648113187545](figures/notification.png) - - - -## Available APIs - -Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md). - -**Table 1** APIs for notification enabling - -| API | Description | -| ------------------------------------------------------------ | ---------------- | -| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.| -| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. | - -If the notification function of an application is disabled, it cannot send notifications. - - - -**Table 2** APIs for notification subscription - -| API | Description | -| ------------------------------------------------------------ | ---------------- | -| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.| -| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. | -| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. | - -The subscription APIs support subscription to all notifications and notifications from specific applications. - - - -**Table 3** Notification subscription callbacks - -| API | Description | -| ------------------------------------------------ | ---------------- | -| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | -| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | -| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.| -| onConnect?:() => void; | Callback for subscription. | -| onDisconnect?:() => void; | Callback for unsubscription. | - - - -**Table 4** APIs for notification sending - -| API | Description | -| ------------------------------------------------------------ | ------------------------ | -| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. | -| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. | -| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. | -| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.| - -The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. - - - -## Development Guidelines - -The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications. - -### Modules to Import - -```js -import Notification from '@ohos.notification'; -``` - - - -### Subscribing to Notifications - -The notification recipient preferentially initiates a notification subscription request to the notification subsystem. - -```js -var subscriber = { - onConsume: function (data) { - let req = data.request; - console.info('===>onConsume callback req.id: ' + req.id); - }, - onCancel: function (data) { - let req = data.request; - console.info('===>onCancel callback req.id: : ' + req.id); - }, - onUpdate: function (data) { - console.info('===>onUpdate in test===>'); - }, - onConnect: function () { - console.info('===>onConnect in test===>'); - }, - onDisconnect: function () { - console.info('===>onDisConnect in test===>'); - }, - onDestroy: function () { - console.info('===>onDestroy in test===>'); - }, - }; - - Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. - if (err.code) { - console.error('===>failed to subscribe because ' + JSON.stringify(err)); - return; - } - console.info('===>subscribeTest success : ' + JSON.stringify(data)); - }); -``` - - - -### Publishing Notifications - -##### Enabling Notification - -Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature. - -```js -Notification.requestEnableNotification().then((data) => { - console.info('===>requestEnableNotification success'); -}).catch((err) => { - console.error('===>requestEnableNotification failed because ' + JSON.stringify(err)); -}); -``` - - - -##### Publishing Notifications - -To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published. - -Normal text notification: - -```js -// Create a NotificationRequest object. -var notificationRequest = { - id: 1, - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "test_title", - text: "test_text", - additionalText: "test_additionalText" - } - } -} - -// Publish the notification. -Notification.publish(notificationRequest).then((data) => { - console.info('===>publish promise success req.id : ' + notificationRequest.id); -}).catch((err) => { - console.error('===>publish promise failed because ' + JSON.stringify(err)); -}); -``` - - - -Notification containing **WantAgent**: - -For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md). - -- Create a **WantAgent** object. - -```js -import wantAgent from '@ohos.wantAgent'; - -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - bundleName: 'ohos.samples.eTSNotification', - abilityName: 'ohos.samples.eTSNotification.MainAbility', - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -// WantAgent object -var WantAgent; - -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("===>getWantAgentCallback===>"); - if (err.code == 0) { - WantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} - -// Obtain the WantAgent object. -wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) -``` - -- Publish the notification. - -```js -// Create a NotificationRequest object. -var notificationRequest = { - content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, - normal: { - title: "AceApplication_Title", - text: "AceApplication_Text", - additionalText: "AceApplication_AdditionalText" - }, - }, - id: 1, - label: 'TEST', - wantAgent: WantAgent, - slotType: Notification.SlotType.OTHER_TYPES, - deliveryTime: new Date().getTime() -} - -// Publish the notification. -Notification.publish(notificationRequest).then((data) => { - console.info('===>publish promise success req.id : ' + notificationRequest.id); -}).catch((err) => { - console.error('===>publish promise failed because ' + JSON.stringify(err)); -}); -``` - - - -- Cancel the notification. - -An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself. - -```js -// cancel callback -function cancelCallback(err) { - console.info("===>cancelCallback===>"); -} - -Notification.cancel(1, "label", cancelCallback) -``` diff --git a/en/application-dev/notification/notification-overview.md b/en/application-dev/notification/notification-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6bef8be8fd446e62b3e3da04582b467c9ddc5961 --- /dev/null +++ b/en/application-dev/notification/notification-overview.md @@ -0,0 +1,27 @@ +# Notification Overview + + +## Introduction + +All system applications and services can publish notifications through the notification APIs. Users can view the notifications in the notification panel or click a notification to open the publishing application. + +Below are some typical use cases for notifications: + +- Display received SMS messages and instant messages. + +- Display push messages, such as advertisements and version updates. + +- Display ongoing events, such as the download progress. + +The Advanced Notification Service (ANS) in OpenHarmony is used to manage notifications of various types, such as basic notifications, progress notifications, and reminders published through the background agent. + + +## Notification Service Process + +The notification service process involves the notification subsystem, notification sender, and notification subscriber. + +A notification is generated by the notification sender and sent to the notification subsystem through [inter-process communication (IPC)](../connectivity/ipc-rpc-overview.md). The notification subsystem then distributes the notification to the notification subscriber. + +System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database. + +![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png) diff --git a/en/application-dev/notification/notification-subscription.md b/en/application-dev/notification/notification-subscription.md new file mode 100644 index 0000000000000000000000000000000000000000..a633a2bb955bcf877fbe4befb8b40ad103d7e7e6 --- /dev/null +++ b/en/application-dev/notification/notification-subscription.md @@ -0,0 +1,82 @@ +# Notification Subscription (Open Only to System Applications) + + +To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application. + + +You can use the **NotificationSubscriber** object to provide callbacks for subscription events, such as subscription success, notification reception, notification cancellation, and subscription cancellation. + + +## Available APIs + +The major APIs for notification subscription are described as follows. For details about the APIs, see [@ohos.notificationSubscribe](../reference/apis/js-apis-notificationSubscribe.md). + +**Table 1** Major APIs for notification subscription + +| Name | Description| +| -------- | -------- | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to notifications from a specific application.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to notifications from all applications. | + +**Table 2** Callbacks for notification subscription + +| Name | Description| +| -------- | -------- | +| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | +| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | +| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates. | +| onConnect?:() => void; | Callback for subscription. | +| onDisconnect?:() => void; | Callback for unsubscription. | +| onDestroy?:() => void | Callback for disconnecting from the notification subsystem. | +| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void | Callback for the Do Not Disturb (DNT) time changes.| +| onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) => void | Callback for notification switch changes. | + + +## How to Develop + +1. Request the **ohos.permission.NOTIFICATION_CONTROLLER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. Import the **notificationSubscribe** module. + + ```ts + import notificationSubscribe from '@ohos.notificationSubscribe'; + ``` + +3. Create a **subscriber** object. + + ```ts + let subscriber = { + onConsume: function (data) { + let req = data.request; + console.info('[ANS] onConsume callback req.id: ' + req.id); + }, + onCancel: function (data) { + let req = data.request; + console.info('[ANS] onCancel callback req.id: : ' + req.id); + }, + onUpdate: function (data) { + console.info('[ANS] onUpdate in test'); + }, + onConnect: function () { + console.info('[ANS] onConnect in test'); + }, + onDisconnect: function () { + console.info('[ANS] onDisConnect in test'); + }, + onDestroy: function () { + console.info('[ANS] onDestroy in test'); + }, + }; + ``` + +4. Initiate notification subscription. + + ```ts + notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. + if (err) { + console.error(`[ANS] failed to subscribe, error[${err}]`); + return; + } + console.info(`[ANS] subscribeTest success : + ${data}`); + }); + ``` diff --git a/en/application-dev/notification/notification-with-wantagent.md b/en/application-dev/notification/notification-with-wantagent.md new file mode 100644 index 0000000000000000000000000000000000000000..d8f0321d28738749d6ed6073e49f26181c22e706 --- /dev/null +++ b/en/application-dev/notification/notification-with-wantagent.md @@ -0,0 +1,121 @@ +# Adding a WantAgent Object to a Notification + +A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsulates an intention to start a specified ability, release a common event, and more. In OpenHarmony, a **WantAgent** object can be passed in a notification from the publisher to the subscriber, so as to trigger the intention specified. For example, you may want the user to start a specific ability by touching the notification published by your application. In this case, you can add a **WantAgent** object that encapsulates such an action to the notification. After receiving the **WantAgent** object, the system triggers it once the user touches the notification from the notification panel, starting the specified ability. + +Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered. + + **Figure 1** Publishing a notification with a WantAgent object +![notification-with-wantagent](figures/notification-with-wantagent.png) + + +## Available APIs + +For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). + +| Name| Description| +| -------- | -------- | +| getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void | Creates a **WantAgent** object.| +| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void | Triggers a **WantAgent** object.| +| cancel(agent: WantAgent, callback: AsyncCallback<void>): void | Cancels a **WantAgent** object.| +| getWant(agent: WantAgent, callback: AsyncCallback<Want>): void | Obtains a **WantAgent** object.| +| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void | Checks whether two **WantAgent** objects are equal. | + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the modules. + + ```typescript + import notificationManager from '@ohos.notificationManager'; + import wantAgent from '@ohos.app.ability.wantAgent'; + ``` + +3. Create a **WantAgentInfo** object. + + Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component. + + ```typescript + let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations. + + // Set the action type through operationType of WantAgentInfo. + let wantAgentInfo = { + wants: [ + { + deviceId: '', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: '', + entities: [], + uri: '', + parameters: {} + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] + }; + ``` + + Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md). + + ```typescript + let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations. + + // Set the action type through operationType of WantAgentInfo. + let wantAgentInfo = { + wants: [ + { + action: 'event_name', // Set the action name. + parameters: {}, + } + ], + operationType: wantAgent.OperationType.SEND_COMMON_EVENT, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], + } + ``` + +4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object. + + ```typescript + // Create a WantAgent object. + wantAgent.getWantAgent(wantAgentInfo, (err, data) => { + if (err) { + console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err)); + return; + } + console.info('[WantAgent]getWantAgent success'); + wantAgentObj = data; + }); + ``` + +5. Create a **NotificationRequest** object and publish a notification that carries the **WantAgent** object. + + ```typescript + // Create a NotificationRequest object. + let notificationRequest = { + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: 'Test_Title', + text: 'Test_Text', + additionalText: 'Test_AdditionalText', + }, + }, + id: 1, + label: 'TEST', + wantAgent: wantAgentObj, + } + + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + +6. When the user touches the notification from the notification panel, the system automatically triggers the action specified in the **WantAgent** object. diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..de430008e3048532e9afea94d83a62dd2f8342c1 --- /dev/null +++ b/en/application-dev/notification/progress-bar-notification.md @@ -0,0 +1,69 @@ +# Publishing a Progress Notification + + +The progress notification is a commonly used notification type, mainly used to display the progress of an ongoing operation, such as file downloading. When publishing a progress notification through the notification subsystem, you can use the readily available template by specifying the related attributes, such as the template name and template data. + +In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data. + + +## Available APIs + +| Name| Description| +| -------- | -------- | +| isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.
Only the progress-type template is supported.| + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +3. Check whether a specific template is supported. In this example, the template of the **downloadTemplate** type is checked. + + ```ts + notificationManager.isSupportTemplate('downloadTemplate').then((data) => { + console.info(`[ANS] isSupportTemplate success`); + let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite. + // ... + }).catch((err) => { + console.error(`[ANS] isSupportTemplate failed, error[${err}]`); + }); + ``` + + > **NOTE** + > + > Proceed with the step below only when the specified template is supported. +4. Create a **NotificationRequest** object and publish a progress notification. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText' + } + }, + // Create a progress template. The name field has a fixed value of downloadTemplate. + template: { + name: 'downloadTemplate', + data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success `); + }); + ``` diff --git a/en/application-dev/notification/text-notification.md b/en/application-dev/notification/text-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..ddbc5478cee37208da33d2acecb71417deaccdc2 --- /dev/null +++ b/en/application-dev/notification/text-notification.md @@ -0,0 +1,160 @@ +# Publishing a Basic Notification + + +You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached. + + + **Table 1** Basic notification content types + +| Type| Description| +| -------- | -------- | +| NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification.| +| NOTIFICATION_CONTENT_LONG_TEXT | Long text notification.| +| NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| +| NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.| + + +Notifications are displayed in the notification panel, which is the only system subscriber to notifications. Below you can see two examples of the basic notification. + +**Figure 1** Examples of the basic notification +![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png) + + +## Available APIs + +The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-notificationManager.md#notificationrequest) parameter in the APIs. + +| Name| Description| +| -------- | -------- | +| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. | +| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a notification. | +| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.| + + +## How to Develop + +1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user. + +2. Import the module. + + ```ts + import notificationManager from '@ohos.notificationManager'; + ``` + +3. Create a **NotificationRequest** object and publish a progress notification. + - A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification + normal: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + } + } + } + + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the normal text notification. + ![en-us_image_0000001466782033](figures/en-us_image_0000001466782033.png) + - In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification + longText: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + longText: 'test_longText', + briefText: 'test_briefText', + expandedTitle: 'test_expandedTitle', + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the long-text notification. + ![en-us_image_0000001416745530](figures/en-us_image_0000001416745530.png) + - In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively. + + ```ts + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification + multiLine: { + title: 'test_title', + text: 'test_text', + briefText: 'test_briefText', + longTitle: 'test_longTitle', + lines: ['line_01', 'line_02', 'line_03', 'line_04'], + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success`); + }); + ``` + + Below is an example of the multi-line notification. + ![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png) + - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB. + + ```ts + let notificationPicture: PixelMap = undefined; // Obtain the pixel map information. + let notificationRequest = { + id: 1, + content: { + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, + picture: { + title: 'test_title', + text: 'test_text', + additionalText: 'test_additionalText', + briefText: 'test_briefText', + expandedTitle: 'test_expandedTitle', + picture: notificationPicture + } + } + } + + // Publish the notification. + notificationManager.publish(notificationRequest, (err) => { + if (err) { + console.error(`[ANS] failed to publish, error[${err}]`); + return; + } + console.info(`[ANS] publish success `); + }); + ``` + + Below is an example of the picture-attached notification. + ![en-us_image_0000001466582045](figures/en-us_image_0000001466582045.png) diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 9b89cfd83f8a3af29bda3fe76016d269561282cb..439bbdcb9d9455a36c75ceb8ba39e728d1aecebd 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -5,11 +5,30 @@ - [Getting Started with ArkTS in FA Model](start-with-ets-fa.md) - [Getting Started with JavaScript in FA Model](start-with-js-fa.md) - Development Fundamentals - - [Application Package Structure Configuration File (FA Model)](package-structure.md) - - [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - - [SysCap](syscap.md) + - Application Package Fundamentals + - [Application Package Overview](application-package-overview.md) + - Application Package Structure + - [Application Package Structure in Stage Model](application-package-structure-stage.md) + - [Application Package Structure in FA Model](application-package-structure-fa.md) + - [HAR File Structure](har-structure.md) + - Multi-HAP Mechanism + - [Multi-HAP Design Objectives](multi-hap-objective.md) + - [Multi-HAP Build View](multi-hap-build-view.md) + - [Multi-HAP Development, Debugging, Release, and Deployment Process](multi-hap-release-deployment.md) + - [Multi-HAP Usage Rules](multi-hap-rules.md) + - [Multi-HAP Operation Mechanism and Data Communication Modes](multi-hap-principles.md) + - [Application Installation and Uninstallation Process](application-package-install-uninstall.md) + - Application Configuration Files in Stage Model + - [Application Configuration File Overview (Stage Model)](application-configuration-file-overview-stage.md) + - [app.json5 Configuration File](app-configuration-file.md) + - [module.json5 Configuration File](module-configuration-file.md) + - Application Configuration Files in FA Model + - [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md) + - [Internal Structure of the app Tag](app-structure.md) + - [Internal Structure of deviceConfig Tag](deviceconfig-structure.md) + - [Internal Structure of the module Tag](module-structure.md) - [Resource Categories and Access](resource-categories-and-access.md) - - Learning ArkTS +- Learning ArkTS - [Getting Started with ArkTS](arkts-get-started.md) - ArkTS Syntax (Declarative UI) - [Basic UI Description](arkts-basic-ui-description.md) diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md new file mode 100644 index 0000000000000000000000000000000000000000..3fff90e0682c4f79e63fa0ee8306a5f8aa7e9385 --- /dev/null +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -0,0 +1,56 @@ +# app.json5 Configuration File + + +This document gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains. + +```json +{ + "app": { + "bundleName": "com.application.myapplication", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "description": "$string:description_application", + "distributedNotificationEnabled": true, + "minAPIVersion": 9, + "targetAPIVersion": 9, + "apiReleaseType": "Release", + "debug": false, + "entityType": "media", + "car": { + "minAPIVersion": 8, + } + }, +} +``` + + +As shown above, the **app.json5** file contains several tags. + + + **Table 1** Tags in the app.json5 file + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:
- Consists of letters, digits, underscores (_), and periods (.).
- Starts with a letter.
- Contains 7 to 127 bytes.
You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| +| debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.
- **true**: The application can be debugged.
- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| +| icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index. | String| No| +| label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index. | String| No| +| description | Description of the application. The value is a string with a maximum of 255 bytes or a resource index to the description. | String| Yes (initial value: left empty)| +| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| versionCode | Version number of the application. The value is a 32-bit non-negative integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number| No| +| versionName | Version number of the application displayed to users.
The value consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:
Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.
The value contains a maximum of 127 bytes.| String| No| +| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario.| Number| Yes (initial value: value of **versionCode**)| +| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| +| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| +| apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.
- **Canary**: indicates a restricted release.
- **Beta**: indicates a publicly released beta version.
- **Release**: indicates a publicly released official version.
The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| +| distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.
- **true**: Distributed notification is enabled.
- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)| +| entityType | Type of the application. The options are as follows:
- game
- media
- communication
- news
- travel
- utility
- shopping
- education
- kids
- business
- photography
- unspecified| String| Yes (initial value: **"unspecified"**)| +| multiProjects | Whether the application supports joint development of multiple projects.
- **true**: The application supports joint development of multiple projects.
- **false**: The application does not support joint development of multiple projects.| Boolean| Yes (initial value: **false**)| +| tablet | Tablet-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| tv | TV-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| wearable | Wearable-specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on wearables, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| car | Head unit–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on head units, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| +| default | Default device–specific configuration, which includes **minAPIVersion** and **distributedNotificationEnabled** attributes.
When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| diff --git a/en/application-dev/quick-start/app-structure.md b/en/application-dev/quick-start/app-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..62b23fad4d660b1d3e516a696b0f7ce95bbde053 --- /dev/null +++ b/en/application-dev/quick-start/app-structure.md @@ -0,0 +1,49 @@ +# Internal Structure of the app Tag + + +The **app** tag contains application-wide configuration. The internal structure is as follows: + +### Internal Structure of the app Tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| bundleName | Bundle name, which uniquely identifies an application. The bundle name must start with a letter and can contain only letters, digits, underscores (_), and periods (.). The bundle name is a string with 7 to 127 bytes of a reverse domain name, for example, **"com.example.myapplication"**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String| No| +| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +|version | Version of the application.| Object| No| +| 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)| + +#### Internal Structure of the version Atttribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:
For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.
*A* indicates the major version number.
*B* indicates the minor version number.
*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
*A* indicates the major version number.
*B* indicates the minor version number.
*C* indicates the feature version number.
*D* indicates the patch version number.| Number| No| +| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:
API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No| +| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)| + +#### Internal Structure of the apiVersion Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| compatible | Minimum API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| +| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| +| releaseType | SDK status when the application is running.
**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.
**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| + +### Example of the **app** Tag + +```json +"app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 8, + "name": "8.0.1" + }, + "apiVersion": { + "compatible": 8, + "target": 9, + "releaseType": "Beta1" + } + } +``` diff --git a/en/application-dev/quick-start/application-configuration-file-overview-fa.md b/en/application-dev/quick-start/application-configuration-file-overview-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..73bc7ebb53a70742bf5d2f0e581ddcae1db673bc --- /dev/null +++ b/en/application-dev/quick-start/application-configuration-file-overview-fa.md @@ -0,0 +1,118 @@ +# Application Configuration File Overview (FA Model) + + +Each application project must have configuration files in its code directory. These configuration files provide basic application information for OpenHarmony build tools, the operating system, and application markets. + + +The application configuration file must contain the following information: + + +- Basic information of the application, including the bundle name, vendor, and version number. Such information must be set under the **app** tag. + +- Component information of the application, including all abilities, device types, component types, and syntax types in use. + +- Device-specific information of the application. Such information affects the functioning of the application on the device. + + +When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file. + + +## Configuration File Internal Structure + +The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| [app](app-structure.md) | Application-wide configuration. Different HAP files of an application must use the same **app** configuration. | Object| No| +| [deviceConfig](deviceconfig-structure.md) | Device-specific configuration. | Object| No| +| [module](module-structure.md) | HAP configuration. It is valid only for the current HAP file.| Object| No| + +Example of the **config.json** file: + + +```json +{ + "app": { + "vendor": "example", + "bundleName": "com.example.demo", + "version": { + "code": 1000000, + "name": "1.0.0" + } + }, + "deviceConfig": { + }, + "module": { + "mainAbility": ".MainAbility_entry", + "deviceType": [ + "tablet" + ], + "commonEvents": [ + { + "name": ".MainAbility", + "permission": "ohos.permission.GET_BUNDLE_INFO", + "data": [ + "com.example.demo", + "100" + ], + "events": [ + "install", + "update" + ] + } + ], + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "MainAbility_entry", + "name": ".MainAbility_entry", + "srcLanguage": "ets", + "icon": "$media:icon", + // $string:MainAbility_entry_desc is a resource index. + "description": "$string:MainAbility_entry_desc", + "formsEnabled": false, + // $string:MainAbility_entry_label is a resource index. + "label": "$string:MainAbility_entry_label", + "type": "page", + "launchType": "standard" + } + ], + "distro": { + "moduleType": "entry", + "installationFree": false, + "deliveryWithInstall": true, + "moduleName": "myapplication" + }, + "package": "com.example.myapplication", + "srcPath": "", + "name": ".myapplication", + "js": [ + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/index" + ], + "name": ".MainAbility_entry", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} +``` diff --git a/en/application-dev/quick-start/application-configuration-file-overview-stage.md b/en/application-dev/quick-start/application-configuration-file-overview-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..ff66e3d405738a44f0c645593ffb0dbfb5beca97 --- /dev/null +++ b/en/application-dev/quick-start/application-configuration-file-overview-stage.md @@ -0,0 +1,25 @@ +# Application Configuration File Overview (Stage Model) + + +Each application project must have configuration files in its code directory. These configuration files provide basic application information for build tools, operating systems, and application markets. + + +In the code directory of an application project developed in stage model, there are two types of configuration files: one **app.json5** file and one or more **module.json5** files. + + +The [app.json5](app-configuration-file.md) file contains the following contents: + + +- Application-wide configuration, including the bundle name, developer, and version number. + +- Device-specific configuration. + + +The [module.json5](module-configuration-file.md) file contains the following contents: + + +- Basic module configuration, such as the name, type, description, and supported device types of the module. + +- Information about the [application components](../application-models/stage-model-development-overview.md), including the descriptions of the UIAbility and ExtensionAbility components. + +- Information about the permissions required during application running. diff --git a/en/application-dev/quick-start/application-package-install-uninstall.md b/en/application-dev/quick-start/application-package-install-uninstall.md new file mode 100644 index 0000000000000000000000000000000000000000..3ccafd9ad3da5f98b9fbd229ff7025863ca105d8 --- /dev/null +++ b/en/application-dev/quick-start/application-package-install-uninstall.md @@ -0,0 +1,8 @@ +# Application Installation and Uninstallation Process + + +The OpenHarmony bundle manager service module provides APIs for installing, updating, and uninstalling applications. You can call these APIs when needed. After you release your application to the application market, users can install and uninstall it on their device. + + + **Figure 1** Process of installing and uninstalling an application +![hap-intall-uninstall](figures/hap-intall-uninstall.png) diff --git a/en/application-dev/quick-start/application-package-overview.md b/en/application-dev/quick-start/application-package-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..c9c16ad5ec6a70b48180fc277d46c54664ca2182 --- /dev/null +++ b/en/application-dev/quick-start/application-package-overview.md @@ -0,0 +1,18 @@ +# Application Package Overview + + +A user application, also known as an application or app, runs on the operating system of devices and provides particular services for users. The software package corresponding to an application is called an application package. + + +OpenHarmony provides an efficient management mechanism for application packages. By harnessing this mechanism, you can easily develop, install, query, update, and uninstall application packages. +- To accelerate application deployment, you can use the integrated development tool provided by OpenHarmony to integrate executable code, resources, and third-party libraries into an OpenHarmony application package. + +- To distribute your application package by device type, you can specify the device types for distribution in the application package configuration file provided by OpenHarmony. + +- An application may provide a wide range of features. It is a good practice to divide and manage application features by module. OpenHarmony provides a multi-package management mechanism on an application-by-application basis. You can aggregate different application features into different packages to facilitate subsequent maintenance and expansion. + +- To allow an application to run across various chip platforms, such as x86, Arm, and other 32-bit or 64-bit platforms, OpenHarmony abstracts away the differences between chip platforms for application packages. + +- With a myriad of query APIs in OpenHarmony, you can quickly check the information about applications, including the application versions, names, components, and permissions. + +- To facilitate resource search and use, the bundle management service in OpenHarmony archives resources by type (media, native, string, internationalization, and more) in different directories and integrates resource index files. diff --git a/en/application-dev/quick-start/application-package-structure-fa.md b/en/application-dev/quick-start/application-package-structure-fa.md new file mode 100644 index 0000000000000000000000000000000000000000..6909481445ecb1219c30ed3ae425d6b475662805 --- /dev/null +++ b/en/application-dev/quick-start/application-package-structure-fa.md @@ -0,0 +1,24 @@ +# Application Package Structure in FA Model + + +To develop an application based on the [FA model](application-configuration-file-overview-fa.md), it is essential to understand the application package structure in this model. + + +The difference between the application package structures in the FA model and stage model lies in where the internal files of a HAP file are stored. In the FA model, all the resource files, library files, and code files are stored in the **assets** folder, where the files are further organized. + + +- **config.json** is an application configuration file, where the template code is automatically created by DevEco Studio. You can modify the configuration as required. For details about the fields in this file, see [Internal Structure of the app Tag](app-structure.md). + +- The **assets** folder is a collection of all the resource files, library files, and code files in a HAP file. It can be further organized into the **entry** folder and the **js** folder. The **entry** folder stores the **resources** folder and the **resources.index** file. + +- The **resources** folder stores resource files (such as strings and images) of the application. + +- The **resources.index** file provides a resource index table, which is generated by DevEco Studio invoking the specific SDK tool. + +- The **js** folder stores code files created after compilation. + +- The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. + +**Figure 1** Application package structure in FA model + +![app-pack-fa](figures/app-pack-fa.png) \ No newline at end of file diff --git a/en/application-dev/quick-start/application-package-structure-stage.md b/en/application-dev/quick-start/application-package-structure-stage.md new file mode 100644 index 0000000000000000000000000000000000000000..b9bd91d798c6a57c06c74cebb38bf558c8fa011d --- /dev/null +++ b/en/application-dev/quick-start/application-package-structure-stage.md @@ -0,0 +1,32 @@ +# Application Package Structure in Stage Model + + +To develop an application based on the [stage model](application-configuration-file-overview-stage.md), it is essential to understand the structure of the application package created after the application is built and packaged. + + +- In development, an application contains one or more modules. You can [create modules](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) in the application project in [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/). As a basic functional unit of an OpenHarmony application/service, a module contains source code, resource files, third-party libraries, and application/service configuration files, and can be built and run independently. Modules can be classified as Ability or Library. A module of the Ability type is built into a Harmony Ability Package (HAP) file in .hap format, and a module of the Library type is built into a [Harmony Ability Resources (HAR) file](har-structure.md) in .tgz format. + A module can contain one or more [UIAbility](../application-models/uiability-overview.md) components, as shown in the figure below. + + **Figure 1** Relationship between modules and UIAbility components + + ![ability-and-module](figures/ability-and-module.png) + + Unless otherwise specified, the modules described in this document refer to the modules of the Ability type. + +- As aforementioned, you can build an application into one or more HAP files. The HAP file is the basic unit for installing an application. It provides code, resources, third-party libraries, and a configuration file. HAP files can be classified as Entry or Feature. + - HAP of the entry type: main module of the application, whose **type** field is set to **"entry"** in the [module.json5](module-configuration-file.md) file. In an application, each type of device supports only one HAP of the entry type, which is typically used to implement the application's entry screen, entry icon, or headline feature. + - HAP of the feature type: dynamic feature module of the application, whose **type** field is set to **"feature"** in the [module.json5](module-configuration-file.md) file. Each application can contain zero, one, or more HAP files of the feature type, which are used to implement the application features. You can configure this type of HAP file to be downloaded and installed independently as required or to be downloaded and installed together with the HAP file of the entry type. For details, see **deliveryWithInstall** in [module.json5 Configuration File](module-configuration-file.md). + +- All the HAP files in an application are integrated into a bundle, and the bundle name is the unique identifier of the application. For details, see **bundleName** tag in [app.json5 Configuration File](app-configuration-file.md). Note that to release an application to the application market, all HAP files (that is, the bundle) contained in the application must be packed into an Application Package (App Pack) in .app format, which also contains the **pack.info** file that describes the attributes of the App Pack. The App Pack is distributed and installed on the cloud and on the device on a HAP-by-HAP basis. + +- The HAP file includes folders such as **ets**, **libs**, and **resources** and files such as **resources.index**, **module.json**, and **pack.info**. + - The **ets** folder stores bytecode files generated after application code build. + - The **libs** folder stores library files, which are .so binary files that contain third-party code on which the OpenHarmony application depends. + - The **resources** folder stores resource files (such as strings and images) of the application. + - The **resources.index** file provides a resource index table, which is generated when the application project is built in DevEco Studio. + - The **module.json** file is the configuration file indispensable in a HAP file. It consists of **module.json5** and **app.json5** in the project configuration. While DevEco Studio provides default configuration, you must modify the configuration as needed. For details about the configuration fields, see [Application Configuration Files in Stage Model](application-configuration-file-overview-stage.md). + - The **pack.info** file describes the HAP attributes in the bundle, for example, **bundleName** and **versionCode** in **app** and **name**, **type**, and **abilities** in **module**. The file is automatically generated when DevEco Studio generates the bundle. + + **Figure 2** Application package structure in stage model + + ![app-pack-stage](figures/app-pack-stage.png) \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-rendering-control.md b/en/application-dev/quick-start/arkts-rendering-control.md index dff2cda50c02afabc15d0f5c8bb576218cab316e..d0ff5a8c183d8efba03b12f7343f001a3ba31fe5 100644 --- a/en/application-dev/quick-start/arkts-rendering-control.md +++ b/en/application-dev/quick-start/arkts-rendering-control.md @@ -34,7 +34,7 @@ Column() { You can use **ForEach** to obtain data from arrays and create components for each data item. -``` +```ts ForEach( arr: any[], itemGenerator: (item: any, index?: number) => void, @@ -275,7 +275,7 @@ struct MyComponent { > > ```ts > LazyForEach(dataSource, -> item => Text(`${item.i}. item.data.label`)), +> item => Text(`${item.i}. item.data.label`), > item => item.data.id.toString()) > ``` 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 145827cd820399e5078b7e395b3c23b3719e1a03..8e1bfd1a19ae568b5db641fb83b1b37e49eeb9c5 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 @@ -60,26 +60,15 @@ struct ComponentA { this.label = (this.languageCode === 'en') ? 'Number' : 'Count' }) } - .margin({ bottom: 50 }) + .margin({ top: 50, bottom: 50 }) Row() { Button (`Change @StorageLink decorated variable: ${this.varA}`).height(40).fontSize(14) .onClick(() => { this.varA++ }) - }.margin({ bottom: 50 }) - - Row() { - Button (`Change @StorageProp decorated variable: ${this.languageCode}`).height(40).fontSize(14) - .onClick(() => { - if (this.languageCode === 'zh') { - this.languageCode = 'en' - } else { - this.languageCode = 'zh' - } - }) } - } + }.width('100%') } } ``` @@ -110,27 +99,26 @@ One-way data binding can be established between a component and the **LocalStora > **NOTE** > -> If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead. +> If a **LocalStorage** instance does not have an initial value assigned when being created, it can use the initial value defined by **@LocalStorageLink** or **@LocalStorageProp** in the component. ### Example 1: Creating a LocalStorage Instance in an Ability The **LocalStorage** is loaded through the **loadContent** API. For details, see [loadContent](../reference/apis/js-apis-window.md#loadcontent9-1). ```ts -// MainAbility.ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { storage: LocalStorage onCreate() { this.storage = new LocalStorage() this.storage.setOrCreate('storageSimpleProp', 121) - console.info('[Demo MainAbility onCreate]') + console.info('[Demo EntryAbility onCreate]') } onDestroy() { - console.info('[Demo MainAbility onDestroy]') + console.info('[Demo EntryAbility onDestroy]') } onWindowStageCreate(windowStage) { @@ -139,15 +127,15 @@ export default class MainAbility extends Ability { } onWindowStageDestroy() { - console.info('[Demo] MainAbility onWindowStageDestroy') + console.info('[Demo] EntryAbility onWindowStageDestroy') } onForeground() { - console.info('[Demo] MainAbility onForeground') + console.info('[Demo] EntryAbility onForeground') } onBackground() { - console.info('[Demo] MainAbility onBackground') + console.info('[Demo] EntryAbility onBackground') } } ``` diff --git a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md index d3f1002dca22fe4522134d662d4c640742d86952..2eae06eca22030673ef35bcf756279444fcd9c60 100644 --- a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md +++ b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md @@ -15,8 +15,8 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c | @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other.| | @Observed | Class | This decorator is used to indicate that the data changes in the class will be managed by the UI page. | | @ObjectLink | Objects of **@Observed** decorated classes| When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering.| -| @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.| | @Provide | Primitive data types, classes, and arrays | As the data provider, **@Provide** can update the data of child nodes and trigger page re-rendering.| +| @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.| ## State Management with Application-level Variables @@ -25,5 +25,8 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c - **@StorageLink**: works in a way similar to that of **@Consume**. The difference is that the target object is obtained from the **AppStorage** based on the given name. **@StorageLink** establishes two-way binding between the decorated UI component and **AppStorage** to synchronize data. - **@StorageProp**: synchronizes UI component attributes with the **AppStorage** unidirectionally. That is, the value change in the **AppStorage** will trigger an update of the corresponding UI component, but the change of the UI component will not cause an update of the attribute value in the **AppStorage**. - Service logic implementation API: adds, reads, modifies, or deletes the state data of applications. The changes made by this API will be synchronized to the UI component for UI update. +- **LocalStorage**: provides ability-specific storage. +- **@LocalStorageLink**: establishes two-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. +- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. - **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key. - **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started. 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 accda367a04ab0c77bdce7557bf47cc73f48c8a3..19326001c088a85dee94f3beaff4676db604c4f3 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 @@ -82,18 +82,22 @@ struct MyComponent { ## @Prop -**@Prop** and **@State** have the same semantics but different initialization modes. Variables decorated by **@Prop** must be initialized using the **@State** decorated variable provided by their parent components. The **@Prop** decorated variable can be modified in the component, but the modification is not updated to the parent component; that is, **@Prop** uses one-way data binding. +**@Prop** and **@State** have the same semantics but different initialization modes. A **@Prop** decorated variable in a component must be initialized using the **@State** decorated variable in its parent component. The **@Prop** decorated variable can be modified in the component, but the modification is not updated to the parent component; the modification to the **@State** decorated variable is synchronized to the **@Prop** decorated variable. That is, **@Prop** establishes one-way data binding. The **@Prop** decorated state variable has the following features: - Support for simple types: The number, string, and boolean types are supported. - Private: Data is accessed only within the component. - Support for multiple instances: A component can have multiple attributes decorated by **@Prop**. -- Support for initialization with a value passed to the @Prop decorated variable: When a new instance of the component is created, all **@Prop** decorated variables must be initialized. Initialization inside the component is not supported. +- Support for initialization with a value passed to the @Prop decorated variable: When a new instance of the component is created, all **@Prop** variables must be initialized. Initialization inside the component is not supported. + +> **NOTE** +> +> A **@Prop** decorated variable cannot be initialized inside the component. **Example** -In the preceding example, when the user presses **+1** or **-1**, the status of the parent component changes and the **build** method is executed again. In this case, a new **CountDownComponent** instance is created. The **countDownStartValue** attribute of the parent component is used to initialize the **@Prop** decorated variable of the child component. When the **count - costOfOneAttempt** button of the child component is touched, the value of the **@Prop** decorated variable **count** is changed. As a result, the **CountDownComponent** is rendered again. However, the change of the **count** value does not affect the **countDownStartValue** value of the parent component. +In the following example, when the user presses **+1** or **-1**, the status of the parent component changes and the **build** method is executed again. In this case, a new **CountDownComponent** instance is created. The **countDownStartValue** attribute of the parent component is used to initialize the **@Prop** decorated variable of the child component. When the **count - costOfOneAttempt** button of the child component is touched, the value of the **@Prop** decorated variable **count** is changed. As a result, the **CountDownComponent** is rendered again. However, the change of the **count** value does not affect the **countDownStartValue** value of the parent component. ```ts // xxx.ets @@ -152,13 +156,13 @@ Two-way binding can be established between the **@Link** decorated variable and - Support for multiple types: The **@Link** decorated variables support the data types the same as the **@State** decorated variables; that is, the value can be of the following types: class, number, string, boolean, or arrays of these types. - Private: Data is accessed only within the component. -- Single data source: The variable of the parent component used for initializing the **@Link** decorated variable must be a **@State** decorated variable. +- Single data source: The variable used to initialize the **@Link** decorated variable in a component must be a state variable defined in the parent component. - **Two-way binding**: When a child component changes the **@Link** decorated variable, the **@State** decorated variable of its parent component is also changed. - Support for initialization with the variable reference passed to the @Link decorated variable: When creating an instance of the component, you must use the naming parameter to initialize all **@Link** decorated variables. **@Link** decorated variables can be initialized by using the reference of the **@State** or **@Link** decorated variable. Wherein, the **@State** decorated variables can be referenced using the **'$'** operator. > **NOTE** > -> **@Link** decorated variables cannot be initialized within the component. +> A **@Link** decorated variable cannot be initialized inside the component. **Simple Type Example** @@ -391,13 +395,13 @@ struct ViewB { ``` -## @Consume and @Provide +## @Provide and @Consume As the data provider, **@Provide** can update the data of child nodes and trigger page rendering. After **@Consume** detects that the **@Provide** decorated variable is updated, it will initiate re-rendering of the current custom component. > **NOTE** > -> To avoid infinite loops caused by circular reference, exercise caution when using **@Provide** and **@Consume**. +> When using **@Provide** and **@Consume**, avoid circular reference that may lead to infinite loops. ### @Provide diff --git a/en/application-dev/quick-start/deviceconfig-structure.md b/en/application-dev/quick-start/deviceconfig-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..7386e27ea69a33efc2e7bca6dfcb2413e3479799 --- /dev/null +++ b/en/application-dev/quick-start/deviceconfig-structure.md @@ -0,0 +1,72 @@ +# Internal Structure of deviceConfig Tag + + +The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. + +### Table 1 Internal Structure of the deviceConfig Tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| default | Application configuration specific to the OpenHarmony device that provides full access to system capabilities.| Object| Yes (initial value: left empty)| +| tablet | Application configuration specific to tablets.| Object| Yes (initial value: left empty)| +| tv | Application configuration specific to smart TVs.| Object| Yes (initial value: left empty)| +| car | Application configuration specific to head units.| Object| Yes (initial value: left empty)| +| wearable | Application configuration specific to wearables.| Object| Yes (initial value: left empty)| + + +Table 2 describes the internal structure of the **deviceConfig** attributes. + +#### Table 2 Internal Structure of the deviceConfig Attributes + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. The value can contain a maximum of 31 characters.| String| Yes (initial value: left empty)| +| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application will start during the OS startup and keep alive. If the application process exits, the OS will restart it.| Boolean| Yes (initial value: **false**)| +| supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.| Boolean| Yes (initial value: **false**)| +| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| +| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| + +#### Table 3 Internal Structure of the network Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.
**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)| +| securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)| + +#### Table 4 Internal Structure of the securityConfig Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| + +#### Table 5 Internal Structure of the domainSettings Attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)| +| domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)| + +### Example of the deviceConfig Tag + +```json +"deviceConfig": { + "default": { + "process": "com.example.test.example", + "supportBackup": false, + "network": { + "cleartextTraffic": true, + "securityConfig": { + "domainSettings": { + "cleartextPermitted": true, + "domains": [ + { + "subdomains": true, + "name": "example.ohos.com" + } + ] + } + } + } + } +} +``` diff --git a/en/application-dev/quick-start/figures/02.png b/en/application-dev/quick-start/figures/02.png index 19dd76ca232282b19883dde63075c5d155e7db70..eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb 100644 Binary files a/en/application-dev/quick-start/figures/02.png and b/en/application-dev/quick-start/figures/02.png differ diff --git a/en/application-dev/quick-start/figures/04.png b/en/application-dev/quick-start/figures/04.png index cf23d17c7ee8552e30a5b234c97862b51981dcf8..1190d1e5aa631b12171632d258e4c4fae32e9bba 100644 Binary files a/en/application-dev/quick-start/figures/04.png and b/en/application-dev/quick-start/figures/04.png differ diff --git a/en/application-dev/quick-start/figures/07.png b/en/application-dev/quick-start/figures/07.png index 0f34d01d824ae1780c73cade9a39fff5f4b9b84e..17f2b060d300667ff250935b6a37485843e854ce 100644 Binary files a/en/application-dev/quick-start/figures/07.png and b/en/application-dev/quick-start/figures/07.png differ diff --git a/en/application-dev/quick-start/figures/ability-and-module.png b/en/application-dev/quick-start/figures/ability-and-module.png new file mode 100644 index 0000000000000000000000000000000000000000..8910b0f30e8fc6808498155263939dbcb1a21336 Binary files /dev/null and b/en/application-dev/quick-start/figures/ability-and-module.png differ diff --git a/en/application-dev/quick-start/figures/app-pack-fa.png b/en/application-dev/quick-start/figures/app-pack-fa.png new file mode 100644 index 0000000000000000000000000000000000000000..51c78e2625228cfbce44d694a0eefae2b0f22782 Binary files /dev/null and b/en/application-dev/quick-start/figures/app-pack-fa.png differ diff --git a/en/application-dev/quick-start/figures/app-pack-stage.png b/en/application-dev/quick-start/figures/app-pack-stage.png new file mode 100644 index 0000000000000000000000000000000000000000..355681fd15a3d8365ab690002fdb9f88b35e2360 Binary files /dev/null and b/en/application-dev/quick-start/figures/app-pack-stage.png differ diff --git a/en/application-dev/quick-start/figures/appstorage.gif b/en/application-dev/quick-start/figures/appstorage.gif index c500542314c4d9182155122729e6b7b15e3abc16..cb1489a13820351450099a973f09a26ec6963c71 100644 Binary files a/en/application-dev/quick-start/figures/appstorage.gif and b/en/application-dev/quick-start/figures/appstorage.gif differ diff --git a/en/application-dev/quick-start/figures/arkts-get-started.png b/en/application-dev/quick-start/figures/arkts-get-started.png index 8858c1d09bc4624ad9ace341b8d4aff2f2c4f2fa..0a83234882aecf0c1cfe390d1b9d49bccdbd0362 100644 Binary files a/en/application-dev/quick-start/figures/arkts-get-started.png and b/en/application-dev/quick-start/figures/arkts-get-started.png differ diff --git a/en/application-dev/quick-start/figures/hap-intall-uninstall.png b/en/application-dev/quick-start/figures/hap-intall-uninstall.png new file mode 100644 index 0000000000000000000000000000000000000000..de04aa18f5053de48dd0b595c8265c781e36fee5 Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-intall-uninstall.png differ diff --git a/en/application-dev/quick-start/figures/hap-multi-view.png b/en/application-dev/quick-start/figures/hap-multi-view.png new file mode 100644 index 0000000000000000000000000000000000000000..be727ebd53ebffbd29e52b78a750462489008892 Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-multi-view.png differ diff --git a/en/application-dev/quick-start/figures/hap-release.png b/en/application-dev/quick-start/figures/hap-release.png new file mode 100644 index 0000000000000000000000000000000000000000..527cefcf7e466e105f74065c3d8b59b18802d94b Binary files /dev/null and b/en/application-dev/quick-start/figures/hap-release.png differ diff --git a/en/application-dev/quick-start/har-structure.md b/en/application-dev/quick-start/har-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..1d479b504a48752fdcb4ff033e81103efa134da2 --- /dev/null +++ b/en/application-dev/quick-start/har-structure.md @@ -0,0 +1,10 @@ +# HAR File Structure + + +The OpenHarmony Archive (HAR) file enables code to be shared among multiple modules or projects. Unlike a Harmony Ability Package (HAP) file, a HAR file cannot be independently installed on a device. Instead, it can only be referenced as the dependency of an application module. + + +A HAR file is the build product of a [module](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3) of the Library type in a DevEco Studio project. + + +As a static shared package in OpenHarmony, the [HAR file](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-npm-package-0000001222578434) can contain the source code, C++ libraries, resource files, and the **module.json** file (in stage model) or **config.json** file (in FA model). diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md new file mode 100644 index 0000000000000000000000000000000000000000..f06e9f911b9d1cb949097e23d24163f7afaa09c2 --- /dev/null +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -0,0 +1,637 @@ +# module.json5 Configuration File + + +This document gives an overview of the **module.json5** configuration file. To start with, let's go through an example of what this file contains. + +```json +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "virtualMachine": "ark", + "metadata": [ + { + "name": "string", + "value": "string", + "resource": "$profile:distrofilter_config" + } + ], + "abilities": [ + { + "name": "EntryAbility", + "srcEntrance": "./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, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "FormAbility" + ], + "when": "inuse" + } + } + ] + } +} +``` + + +As shown above, the **module.json5** file contains several tags. + + + **Table 1** Tags in the module.json5 file + +| 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| +| 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)| +| 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 contains a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| [deviceTypes](#devicetypes) | Type of the device on which the module can run.| String array| No (can be left empty)| +| 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 JS component defined by the module syntax. This tag is deprecated since API version 9.
- **"hml"**: The JS component is developed using HML, CSS, or JS.
- **"ets"**: The JS component is developed using ArkTS. | String| Yes (initial value: **"hml"**)| +| [pages](#pages)| Profile that represents information about each page in the JS component. 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)| +| [extensionAbilities](#extensionabilities) | ExtensionAbility configuration of the module, which is valid only for the current ExtensionAbility component.| Object| Yes (initial value: left empty)| +| [requestPermissions](#requestpermissions) | A set of permissions that the application needs to request from the system for running correctly.| Object| Yes (initial value: left empty)| +| [testRunner](#testrunner) | Test runner configuration of the module.| Object| Yes (initial value: left empty)| + + +## deviceTypes + + **Table 2** deviceTypes + +| Device Type| Value| Description| +| -------- | -------- | -------- | +| Tablet| tablet | - | +| Smart TV| tv | - | +| Smart watch| wearable | Watch that provides call features.| +| Head unit| car | - | +| Default device| default | OpenHarmony device that provides full access to system capabilities.| + +Example of the **deviceTypes** structure: + + +```json +{ + "module": { + "name": "myHapName", + "type": "feature", + "deviceTypes" : [ + "tablet" + ] + } +} +``` + + +## pages + +The **pages** tag is a profile that represents information about specified pages. + + +```json +{ + "module": { + // ... + "pages": "$profile:main_pages", // Configured through the resource file in the profile + } +} +``` + +Define the **main_pages.json** file under **resources/base/profile** in the development view. The base name of the file (**main_pages** in this example) can be customized, but must be consistent with the information specified by the **pages** tag. The file lists the page information of the current application. + + +```json +{ + "src": [ + "pages/index/mainPage", + "pages/second/payment", + "pages/third/shopping_cart", + "pages/four/owner" + ] +} +``` + + +## metadata + +The **metadata** tag represents the custom metadata of the HAP file. The tag value is an array and contains three subtags: **name**, **value**, and **resource**. + + **Table 3** metadata + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| resource | Custom data format. The value is a resource index. It contains a maximum of 255 bytes. | String| Yes (initial value: left empty)| + + +```json +{ + "module": { + "metadata": [{ + "name": "module_metadata", + "value": "a test demo for module metadata", + "resource": "$profile:shortcuts_config", + }], + + "abilities": [{ + "metadata": [{ + "name": "ability_metadata", + "value": "a test demo for ability", + "resource": "$profile:config_file" + }, + { + "name": "ability_metadata_2", + "value": "a string test", + "resource": "$profile:config_file" + }], + }], + + "extensionAbilities": [{ + "metadata": [{ + "name": "extensionAbility_metadata", + "value": "a test for extensionAbility", + "resource": "$profile:config_file" + }, + { + "name": "extensionAbility_metadata_2", + "value": "a string test", + "resource": "$profile:config_file" + }], + }] + } +} +``` + + +## 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. + + **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"**)| +| 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** of the current module, this attribute is mandatory. | String| Yes (initial value: left empty) | +| 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**)| +| 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 **action.system.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)| +| 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**)| +| orientation | Orientation of the UIAbility component when it is started. The options are as follows:
- **unspecified**: automatically determined by the system.
- **landscape**: landscape mode.
- **portrait**: portrait mode.
- **landscape_inverted**: inverted landscape mode.
- **portrait_inverted**: inverted portrait mode.
- **auto_rotation**: determined by the sensor.
- **auto_rotation_landscape**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes.
- **auto_rotation_portrait**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes.
- **auto_rotation_restricted**: determined by the sensor when the sensor switch is enabled.
- **auto_rotation_landscape_restricted**: determined by the sensor in the horizontal direction, including landscape and inverted landscape modes, when the sensor switch is enabled.
- **auto_rotation_portrait_restricted**: determined by the sensor in the vertical direction, including portrait and inverted portrait modes, when the sensor switch is enabled.
- **locked**: auto rotation disabled.| String| Yes (initial value: **"unspecified"**)| +| supportWindowMode | Window mode supported by the UIAbility component. The options are as follows:
- **fullscreen**: full-screen mode.
- **split**: split-screen mode.
- **floating**: floating window mode.| String array| Yes (initial value:
["fullscreen", "split", "floating"])| +| 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)| +| 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**)| + +Example of the **abilities** structure: + + +```json +{ + "abilities": [{ + "name": "EntryAbility", + "srcEntrance": "./ets/entryability/EntryAbility.ts", + "launchType":"standard", + "description": "$string:description_main_ability", + "icon": "$media:icon", + "label": "Login", + "permissions": [], + "metadata": [], + "visible": true, + "continuable": true, + "skills": [{ + "actions": ["action.system.home"], + "entities": ["entity.system.home"], + "uris": [] + }], + "backgroundModes": [ + "dataTransfer", + "audioPlayback", + "audioRecording", + "location", + "bluetoothInteraction", + "multiDeviceConnection", + "wifiInteraction", + "voip", + "taskKeeping" + ], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true, + "orientation": " ", + "supportWindowMode": ["fullscreen", "split", "floating"], + "maxWindowRatio": 3.5, + "minWindowRatio": 0.5, + "maxWindowWidth": 2560, + "minWindowWidth": 1400, + "maxWindowHeight": 300, + "minWindowHeight": 200, + "excludeFromMissions": false + }] +} +``` + + +## skills + +The **skills** tag represents the feature set of [wants](../application-models/want-overview.md) that can be received by the UIAbility or ExtensionAbility component. + + **Table 5** skills + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| actions | [Actions](../application-models/actions-entities.md) of wants that can be received, which can be predefined or customized.| String array| Yes (initial value: left empty)| +| entities | [Entities](../application-models/actions-entities.md) of wants that can be received.| String array| Yes (initial value: left empty)| +|uris | URIs that match the wants.| Object array| Yes (initial value: left empty)| + + **Table 6** uris + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| scheme | Scheme of the URI, such as HTTP, HTTPS, file, and FTP.| String| Yes when only **type** is set in **uris** (initial value: left empty) | +| host | Host address of the URI. This attribute is valid only when **schema** is set. Common methods:
- domain name, for example, **example.com**.
- IP address, for example, **10.10.10.1**.| String| Yes (initial value: left empty)| +| port | Port number of the URI. For example, the default HTTP port number is 80, the default HTTPS port number is 443, and the default FTP port number is 21. This attribute is valid only when both **scheme** and **host** are set.| String| Yes (initial value: left empty)| +| path \| pathStartWith \| pathRegex | Path of the URI. **path**, **pathStartWith**, and **pathRegex** represent different matching modes between the paths in the URI and the want. Set any one of them as needed. **path** indicates full matching, **pathStartWith** indicates prefix matching, and **pathRegex** indicates regular expression matching. This attribute is valid only when both **scheme** and **host** are set.| String| Yes (initial value: left empty)| +| type | Data type that matches the want. The value compiles with the [Multipurpose Internet Mail Extensions (MIME)](https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com %E3%80%82) type specification. This attribute can be configured together with **scheme** or be configured separately. | String| Yes (initial value: left empty)| + +Example of the **skills** structure: + + +```json +{ + "abilities": [ + { + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme":"http", + "host":"example.com", + "port":"80", + "path":"path", + "type": "text/*" + } + ] + } + ] + } + ] +} +``` + + +## extensionAbilities + +The **extensionAbilities** tag represents the configuration of extensionAbilities, which is valid only for the current extensionAbility. + + **Table 7** extensionAbilities + +| 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| +| 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 the index to an icon resource file. 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 the index to a string resource.
**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| +| 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 **action.system.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 ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| + +Example of the **extensionAbilities** structure: + + +```json +{ + "extensionAbilities": [ + { + "name": "FormName", + "srcEntrance": "./form/MyForm.ts", + "icon": "$media:icon", + "label" : "$string:extension_name", + "description": "$string:form_description", + "type": "form", + "permissions": ["ohos.abilitydemo.permission.PROVIDER"], + "readPermission": "", + "writePermission": "", + "visible": true, + "uri":"scheme://authority/path/query", + "skills": [{ + "actions": [], + "entities": [], + "uris": [] + }], + "metadata": [ + { + "name": "ohos.extension.form", + "resource": "$profile:form_config", + } + ] + } + ] +} +``` + + +## requestPermissions + +The **requestPermissions** tage represents a set of permissions that the application needs to request from the system for running correctly. + + **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| +| 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: + + +```json +{ + "module" : { + "requestPermissions": [ + { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "EntryFormAbility" + ], + "when": "inuse" + } + } + ] + } +} +``` + + +## shortcuts + +The **shortcuts** tag provides the shortcut information of an application. The value is an array of up to four shortcuts. It consists of four sub-attributes: **shortcutId**, **label**, **icon**, and **wants**. + +The **shortcut** information is identified in **metadata**, where: + +- **name** indicates the name of the shortcut, identified by **ohos.ability.shortcuts**. + +- **resource** indicates where the resources of the shortcut are stored. + +| Attribute| Description| Data Type | Default Value| +| -------- | -------- | -------- | -------- | +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No| +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label, with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| icon | Icon of the shortcut. The value is an icon resource index. | String| Yes (initial value: left empty)| +| [wants](../application-models/want-overview.md) | Wants to which the shortcut points. Each want consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut. The value is a string.
**abilityName**: target component name of the shortcut. The value is a string.| Object| Yes (initial value: left empty)| + + +1. Configure the **shortcuts_config.json** file in **/resource/base/profile/**. + + ```json + { + "shortcuts": [ + { + "shortcutId": "id_test1", + "label": "$string:shortcut", + "icon": "$media:aa_icon", + "wants": [ + { + "bundleName": "com.ohos.hello", + "abilityName": "EntryAbility" + } + ] + } + ] + } + ``` + +2. In the **abilities** tag of the **module.json5** file, configure the **metadata** tag for the UIAbility component to which a shortcut needs to be added so that the shortcut configuration file takes effect for the UIAbility. + + ```json + { + "module": { + // ... + "abilities": [ + { + "name": "EntryAbility", + "srcEntrance": "./ets/entryability/EntryAbility.ts", + // ... + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "metadata": [ + { + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + } + ] + } + ] + } + } + ``` + + +## distroFilter + +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. + + **Table 9** distroFilter + +| 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 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](https://developer.harmonyos.com/en/docs/documentation/doc-guides/basic-resource-file-categories-0000001052066099) 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 + +| 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 + +| 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 + +| 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 + +| 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 | Code of the country or region to which the application is to be distributed.| String array| No| + +Configure the **distro_filter_config.json** file (this file name is customizable) in **resources/base/profile** under the development view. + + +```json +{ + "distroFilter": { + "apiVersion": { + "policy": "include", + "value": [ + 3, + 4 + ] + }, + "screenShape": { + "policy": "include", + "value": [ + "circle", + "rect" + ] + }, + "screenWindow": { + "policy": "include", + "value": [ + "454*454", + "466*466" + ] + }, + "screenDensity": { + "policy": "exclude", + "value": [ + "ldpi", + "xldpi" + ] + }, + "countryCode": {// Distribution to the Chinese mainland and Hong Kong, China is supported. + "policy": "include", + "value": [ + "CN", + "HK" + ] + } + } +} +``` + +Configure **metadata** in the **module** tag in the **module.json5** file. + + +```json +{ + "module": { + // ... + "metadata": [ + { + "name": "ohos.module.distro", + "resource": "$profile:distro_filter_config", + } + ] + } +} +``` + + +## testRunner + +The **testRunner** tag represents the supported test runner. + + **Table 15** testRunner + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the test runner object. The value is a string with a maximum of 255 bytes.| String| No| +| srcPath | Code path of the test runner. The value is a string with a maximum of 255 bytes. | String| No| + +Example of the / structure: + + +```json +{ + "module": { + // ... + "testRunner": { + "name": "myTestRunnerName", + "srcPath": "etc/test/TestRunner.ts" + } + } +} +``` diff --git a/en/application-dev/quick-start/module-structure.md b/en/application-dev/quick-start/module-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..a8df69c1846a1ff6f7647aff4490da5d4990d431 --- /dev/null +++ b/en/application-dev/quick-start/module-structure.md @@ -0,0 +1,640 @@ +# Internal Structure of the module Tag + + +The **module** tag contains the HAP configuration. + +### Table 1 Internal Structure of the module Tag + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| mainAbility | Ability whose icon is displayed in the Service Center. When the resident process is started, the **mainAbility** is started.| String| Yes (initial value: left empty)| +| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. | String| No| +| name | Class name of the HAP file. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. The prefix must be the same as the **package** value specified for this module. Alternatively, the value can start with a period (.) followed by the class name.| String| Yes (initial value: left empty)| +| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description.| String| Yes (initial value: left empty)| +| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty)| +|deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No| +|distro | Distribution description of the HAP file.| Object| No| +|metaData | Metadata of the HAP file.| Object| Yes (initial value: left empty)| +| abilities | All abilities in the current module. The value is an array of objects, each of which represents an ability.| Object array| Yes (initial value: left empty)| +| js | A set of JS modules developed using ArkUI. The value is an array of objects, each of which represents a JS module.| Object array| Yes (initial value: left empty)| +| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)| +| reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| +| colorMode | Color mode of the application. The options are as follows:
- **dark**: Resources applicable for the dark mode are used.
- **light**: Resources applicable for the light mode are used.
- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| +| distroFilter | Distribution rules of the application. This attribute 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 three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. | Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| +|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the subscribed common events. When a subscribed event is sent, the static subscriber is started. Unlike the common dynamic subscriber, the static subscriber does not need to actively call the common event subscription API in the service code, and may not be started when the common event is released. In constrast, the dynamic subscriber actively calls the common event subscription API and therefore requires the application to stay active.| Object array| Yes (initial value: left empty)| +| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)| +|testRunner | Test runner configuration.| Object| Yes (initial value: left empty)| + +Example of the **module** tag structure: + +```json +{ + "module": { + "mainAbility": ".MainAbility", + "deviceType": [ + "default", + "tablet" + ], + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "MainAbility", + "name": ".MainAbility", + "srcLanguage": "ets", + "icon": "$media:icon", + "description": "$string:MainAbility_desc", + "formsEnabled": false, + "label": "$string:MainAbility_label", + "type": "page", + "launchType": "standard" + } + ], + "distro": { + "moduleType": "entry", + "installationFree": false, + "deliveryWithInstall": true, + "moduleName": "entry" + }, + "package": "com.example.entry", + "srcPath": "", + "name": ".entry", + "js": [ + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/Index" + ], + "name": ".MainAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} +``` + +#### Table 2 Internal structure of the distro attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| moduleName | Name of the HAP file. The maximum length is 31 bytes.| String| No| +| moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No| +| installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| +| deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| + + +Example of the **distro** attribute structure: + +```json +"distro": { + "moduleName": "ohos_entry", + "moduleType": "entry", + "installationFree": true, + "deliveryWithInstall": true +} +``` + +#### Table 3 Internal structure of the metadata attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| parameters | Metadata of the parameters to be passed for calling the ability. The metadata of each parameter consists of the **description**, **name**, and **type** sub-attributes.| Object array| Yes (initial value: left empty)| +| results | Metadata of the ability return value. The metadata of each return value consists of the **description**, **name**, and **type** sub-attributes.| Object array| Yes (initial value: left empty)| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**.| Object array| Yes (initial value: left empty)| + +#### Table 4 Internal structure of the parameters attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| description | Description of the parameter. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 bytes.| String| No| +| type | Type of the parameter passed for calling the ability, for example, **Integer**.| String| No| + +#### Table 5 Internal structure of the results attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| name | Name of the return value. The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| type | Type of the return value, for example, **Integer**.| String| No| + +#### Table 6 Internal structure of the customizeData attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Key of the data element. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| value | Value of the data element. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| extra | Custom format of the data element. The value is a resource index that identifies the data.| String| Yes (initial value: left empty)| + + +Example of the metadata attribute: + +```json +"metaData": { + "parameters" : [{ + "name" : "a test for metadata parameter", + "type" : "Float", + // "$string:parameters_description" is a file resource index. + "description" : "$string:parameters_description" + }], + "results" : [{ + "name" : "a test for metadata result", + "type" : "Float", + "description" : "$string:results_description" + }], + "customizeData" : [{ + "name" : "a customizeData", + "value" : "string", + "extra" : "$string:customizeData_description" + }] +} +``` + +#### Table 7 Values of the deviceType attribute + +| Device Type| Value| Description| +| -------- | -------- | -------- | +| Tablet| tablet | - | +| Smart TV| tv | - | +| Smart watch| wearable | Watch that provides call features.| +| Head unit| car | - | +| Default device| default | OpenHarmony device that provides full access to system capabilities.| + +#### Table 8 Internal structure of the abilities attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)| +| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created by default, and its configuration will be saved to the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 bytes.| String| No| +| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)| +| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String| Yes (initial value: left empty)| +| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)| +| launchType | Launch type of the ability. The value can be **standard** or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)| +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)| +| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the reverse domain name notation. It contains a maximum of 255 bytes.| String array| Yes (initial value: left empty)| +|skills | Types of the **want** that can be accepted by the ability.| Object array| Yes (initial value: left empty)| +| deviceCapability | Device capabilities required to run the ability. The value is an array of up to 512 elements, each of which contains a maximum of 64 bytes.| String array| Yes (initial value: left empty)| +| metaData | Metadata.| Object| Yes (initial value: left empty)| +| type | Ability type. The options are as follows:
**page**: FA developed using the Page template to provide the capability of interacting with users.
**service**: PA developed using the Service template to provide the capability of running tasks in the background.
**data**: PA developed using the Data template to provide unified data access for external systems.
**CA**: ability that can be started by other applications as a window.| String| No| +| orientation | Display orientations of the ability. This attribute applies only to the ability using the Page template. The options are as follows:
**unspecified**: indicates that the system automatically determines the display orientation of the ability.
**landscape**: indicates the landscape orientation.
**portrait**: indicates the portrait orientation.
**followRecent**: indicates that the orientation follows the most recent application in the stack.| String| Yes (initial value: **"unspecified"**)| +| backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This field applies only to the ability using the Service template. The options are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices.
**audioPlayback**: audio playback service.
**audioRecording**: audio recording service.
**pictureInPicture**: picture in picture (PiP) and small-window video playback services.
**voip**: voice/video call and VoIP services.
**location**: location and navigation services.
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services.
**wifiInteraction**: WLAN scanning, connection, and transmission services.
**screenFetch**: screen recording and screenshot services.
**multiDeviceConnection**: multi-device interconnection service.| String array| Yes (initial value: left empty)| +| grantPermission | Whether permissions can be granted for any data in the ability.| Boolean| Yes (initial value: left empty)| +| readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: left empty)| +| writePermission | Permission required for writing data to the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. The options are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user selectes a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty)| +| mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack.| String| Yes (initial value: bundle name of the application)| +| targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias.| String| Yes (initial value: left empty, indicating that the current ability is not an alias)| +| formsEnabled | Whether the ability can provide widgets. This attribute applies only to the ability using the Page template.
**true**: This ability can provide widgets.
**false**: This ability cannot provide widgets.| Boolean| Yes (initial value: **false**)| +| forms | Information about the widgets used by the ability. This attribute is valid only when **formsEnabled** is set to **true**.| Object array| Yes (initial value: left empty)| +| srcLanguage | Programming language of the ability, which you can specify when creating the project.| String| Yes (initial value: **"js"**)| +| srcPath | JS code path corresponding to the ability. The value can contain maximum of 127 bytes.| String| No| +| uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider.| Object| Yes (initial value: left empty)| +| startWindowIcon | Index to the icon file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$media:icon**.| String| Yes (initial value: left empty)| +| startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String| Yes (initial value: left empty)| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean| Yes (initial value: **false**)| + +#### Table 9 Internal structure of the uriPermission attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| path | Path. The value can contain maximum of 255 bytes.| String| No| +| mode | Matching mode.| String| Yes (initial value: **default**)| + + +Example of the **abilities** attribute structure: + +```json +"abilities": [ + { + "name": ".MainAbility", + "description": "test main ability", + // $media:ic_launcher is a media resource. + "icon": "$media:ic_launcher", + // $string:example is a string resource. + "label": "$string:example", + "launchType": "standard", + "orientation": "unspecified", + "permissions": [], + "visible": true, + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ], + "configChanges": [ + "locale", + "layout", + "fontSize", + "orientation" + ], + "type": "page", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true + }, + { + "name": ".PlayService", + "description": "example play ability", + "icon": "$media:ic_launcher", + "label": "$string:example", + "launchType": "standard", + "orientation": "unspecified", + "visible": false, + "skills": [ + { + "actions": [ + "action.play.music", + "action.stop.music" + ], + "entities": [ + "entity.audio" + ] + } + ], + "type": "service", + "backgroundModes": [ + "audioPlayback" + ] + }, + { + "name": ".UserADataAbility", + "type": "data", + "uri": "dataability://com.example.world.test.UserADataAbility", + "visible": true + } +] +``` + +#### Table 10 Internal structure of the skills attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| +| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| +| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both.
The URI is specified by separate attributes of each part: <scheme>://<host>:<port>[<path>\|<pathStartWith>\|<pathRegex>].
**scheme** is mandatory when the specification is of the URI type and is optional when the specification is of data type only.| Object array| Yes (initial value: left empty)| + +#### Table 11 Internal structure of the uris attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| scheme | Scheme of the URI.| String| No| +| host | Host value of the URI.| String| Yes (initial value: left empty)| +| port | Port number of the URI.| String| Yes (initial value: left empty)| +| pathStartWith | **pathStartWith** value of the URI.| String| Yes (initial value: left empty)| +| path | **path** value of the URI.| String| Yes (initial value: left empty)| +| pathRegx | **pathRegx** value of the URI.| String| Yes (initial value: left empty)| +| type | **type** value of the URI. The value is a MIME type. Typical values include **"audio/aac"** and **"text/css"**.| String| Yes (initial value: left empty)| + + +Example of the **skills** attribute structure: + +```json +"skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme": "http", + "host": "www.example.com", + "port": "8080", + "path": "query/student/name", + "type": "text/*" + } + ] + } +] +``` + +#### Table 12 reqPermissions attributes + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the permission to request.| String| No| +| reason | Reason for requesting the permission. Multi-language adaptation is required.| String| No if the permission to request is **user_grant**, yes in other cases (initial value: left empty)
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. | +| usedScene | Scene under which the permission is used. It consists of the **abilities** and **when** sub-attributes.
- **ability**: ability name. Multiple ability names can be configured.
- **when**: time for using the permission. The options are **inuse** and **always**.| Object| Yes (initial value: left empty)
**when**: initial value (**inuse**) allowed| + +#### Table 13 Internal structure of the usedScene attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| ability | Names of abilities that require the permission.| String array| Yes (initial value: all ability names)| +| when | Time when the permission is used.
**inuse**: The permission is required when the ability is in use.
**always**: The permission is required at all times.| Value| Yes (initial value: left empty)| + +#### Table 14 Internal structure of the js attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the JS component. The default value is **default**.| String| No| +| pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JS FA.| String array| No| +| window | Window-related configurations.| Object| Yes (initial value: see Table 15)| +| type | Type of the JS component. The options are as follows:
**normal**: indicates an application instance.
**form**: indicates a widget instance.| String| Yes (initial value: **"normal"**)| +|mode | Development mode of the JS component.| Object| Yes (initial value: left empty)| + +#### Table 15 Internal structure of the window attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number| Yes (initial value: 720px)| +| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| + +#### Table 16 Internal structure of the mode attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| type | Type of the JS component. The value can be **pageAbility** or **form**.| String| Yes (initial value: **pageAbility**)| +| syntax | Syntax type of the JS component. The value can be **"hml"** or **"ets"**.| String| Yes (initial value: **"hml"**)| + + +Example of the **js** attribute structure: + +```json +"js": [ + { + "name": "default", + "pages": [ + "pages/index/index", + "pages/detail/detail" + ], + "window": { + "designWidth": 720, + "autoDesignWidth": false + }, + "type": "form" + } +] +``` + +#### Table 17 Internal structure of the shortcuts attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes.| String| No| +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the label. The value is a string with a maximum of 63 bytes.| String| Yes (initial value: left empty)| +| icon | Icon of the shortcut. The value is a resource index to the description.| String| Yes (initial value: left empty)| +| intents | Wants to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes.| Object array| Yes (initial value: left empty)| + +#### Table 18 Internal structure of the intents attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| targetClass | Target class of the shortcut.| String| Yes (initial value: left empty)| +| targetBundle | Application bundle name for the target ability of the shortcut.| String| Yes (initial value: left empty)| + + +Example of the **shortcuts** attribute structure: + +```json +"shortcuts": [ + { + "shortcutId": "id", + // $string:shortcut is a string resource index. + "label": "$string:shortcut", + "intents": [ + { + "targetBundle": "com.example.world.test", + "targetClass": "com.example.world.test.entry.MainAbility" + } + ] + } +] +``` + +#### Table 19 Internal structure of the forms attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes.| String| No| +| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean| No| +| type | Type of the widget. The options are as follows:
**JS**: indicates a JavaScript-programmed widget.| String| No| +| colorMode | Color mode of the widget. The options are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| +| supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 1**: indicates a grid with two rows and one column.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No| +| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String| No| +| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
**false**: The widget cannot be updated periodically.| Boolean| No| +| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.| String| Yes (initial value: **"0:0"**)| +| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this attribute does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.| Number| Yes (initial value: **0**)| +| formConfigAbility | Name of the ability used to adjust the widget.| String| Yes (initial value: left empty)| +| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String| No| +| metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute.| Object| Yes (initial value: left empty)| +| customizeData | Custom information of the widget.| Object array| Yes (initial value: left empty)| + +#### Table 20 Internal structure of the customizeData attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| extra | Format of the current custom data. The value is the resource value of **extra**.| String| Yes (initial value: left empty)| + + +Example of the **forms** attribute structure: + +```json +"forms": [ + { + "name": "Form_Js", + "description": "It's Js Form", + "type": "JS", + "jsComponentName": "card", + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "11:00", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2", + "2*4", + "4*4" + ] + }, + { + "name": "Form_Js", + "description": "It's JS Form", + "type": "Js", + "colorMode": "auto", + "isDefault": false, + "updateEnabled": true, + "scheduledUpdateTime": "21:05", + "updateDuration": 1, + "defaultDimension": "1*2", + "supportDimensions": [ + "1*2" + ], + "landscapeLayouts": [ + "$layout:ability_form" + ], + "portraitLayouts": [ + "$layout:ability_form" + ], + "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "com.example.weather.testWidget" + } + ] + } + } +] +``` + +#### Table 21 Internal structure of the distroFilter attribute + +| 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).| Object array| Yes (initial value: left empty)| +| countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported.| Object array| Yes (initial value: left empty)| + +#### Table 22 Internal structure of the apiVersion attribute + +| 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 23 Internal structure of the screenShape attribute + +| 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. | Array| No| + +#### Table 24 Internal structure of the screenWindow attribute + +| 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"**. | Array| No| + +#### Table 25 Internal structure of the screenDensity attribute + +| 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 dots per inch (DPI). The 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].| Array| No| + +#### Table 26 Internal structure of the countryCode attribute + +| 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 | Country code of the area to which the application is to be distributed. The value is a string array, of which each substring indicates a country or region. The substring consists of two uppercase letters.| String array| No| + + +Example of the **distroFilter** attribute structure: + +```json +"distroFilter": { + "apiVersion": { + "policy": "include", + "value": [4,5] + }, + "screenShape": { + "policy": "include", + "value": ["circle","rect"] + }, + "screenWindow": { + "policy": "include", + "value": ["454*454","466*466"] + }, + "screenDensity":{ + "policy": "exclude", + "value": ["ldpi","xldpi"] + }, + "countryCode": { + "policy":"include", + "value":["CN","HK"] + } +} +``` + +#### Table 27 Internal structure of the commonEvents attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the static common event. The value can contain a maximum of 127 bytes.| String| No| +| permission | Permission required to implement static common events. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| data | Additional data array to be carried by the current static common event.| String array| Yes (initial value: left empty)| +| type | Type array of the current static common event.| String array| Yes (initial value: left empty)| +| events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No| + + +Example of the **commonEvents** attribute structure: + +```json +"commonEvents": [ + { + "name": ".MainAbility", + "permission": "ohos.permission.GET_BUNDLE_INFO", + "data": [ + "com.example.demo", + "100" + ], + "events": [ + "install", + "update" + ] + } +] +``` + +#### Table 28 Internal structure of the testRunner attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of the test runner object. The value can contain a maximum of 255 bytes.| String| No| +| srcPath | Code path of the test runner. The maximum length of this tag is 255 bytes.| String| No| + +```json +"testRunner": { + "name": "myTestRunnerName", + "srcPath": "etc/test/TestRunner.ts" +} +``` + + +**definePermission** applies only to system applications and does not take effect for third-party applications. + +#### Table 29 Internal structure of the definePermissions attribute + +| Name| Description| Data Type| Initial Value Allowed| +| -------- | -------- | -------- | -------- | +| name | Name of a permission. The value can contain a maximum of 255 bytes.| String| No| +| grantMode | Permission grant mode. The options are as follows:
- **system_grant**: The permission is automatically granted by the system after the application is installed.
- **user_grant**: The permission is dynamically requested when needed and must be granted by the user.| String| Yes (initial value: **"system_grant"**)| +| availableLevel | Permission type. The options are as follows:
- **system_core**: system core permission.
- **system_basic**: basic system permission.
- **normal**: normal permission, which can be requsted by all applications.| String| Yes (initial value: **"normal"**)| +| provisionEnable | Whether the permission can be requested in provision mode, including high-level permissions. The value **true** means that the permission can be requested in provision mode.| Boolean| Yes (initial value: **true**)| +| distributedSceneEnabled | Whether the permission can be used in distributed scenarios.| Boolean| Yes (initial value: **false**)| +| label | Brief description of the permission. The value is a resource index to the description.| String| Yes (initial value: left empty)| +| description | Detailed description of the permission. The value is a string with a maximum of 255 bytes or a string resource index.| String| Yes (initial value: left empty)| diff --git a/en/application-dev/quick-start/multi-hap-build-view.md b/en/application-dev/quick-start/multi-hap-build-view.md new file mode 100644 index 0000000000000000000000000000000000000000..3266828fdbda2b969668410a98ce4b64cce54411 --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-build-view.md @@ -0,0 +1,28 @@ +# Multi-HAP Build View + + +DevEco Studio allows you to develop and build multiple HAP files in one application project, as shown below. + + + **Figure 1** Multi-HAP build view +![hap-multi-view](figures/hap-multi-view.png) + + +1. Development view in DevEco Studio + - AppScope folder + - [app.json5](app-configuration-file.md): application-wide configuration, such as the application bundle name, version number, application icon, application name, and dependent SDK version number. + - **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. + - **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. + +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. + - All HAP files are finally built into an Application Package (App Pack) in .app format for release to the application market. diff --git a/en/application-dev/quick-start/multi-hap-objective.md b/en/application-dev/quick-start/multi-hap-objective.md new file mode 100644 index 0000000000000000000000000000000000000000..ad43c84fd7799be1e3277400c6c5dfb1926d5b7c --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-objective.md @@ -0,0 +1,10 @@ +# Multi-HAP Design Objectives + + +- Modular management: A well-designed application is generally managed in a modular manner, where modules are loosely coupled. In light of this, the multi-HAP mechanism is designed, allowing you to divide services into multiple modules and store each module in an independent HAP file. For example, If you are developing a payment application and its home screen consists of multiple modules, such as the scan, pay, messaging, and finance modules, you can implement the logic of the home screen for managing other modules in the entry-type HAP file, and implement specific modules in feature-type HAP files. The feature-type HAP files are independent. You can develop and test each of them separately, and then integrate them with the entry-type HAP file. + +- Flexible deployment: You can combine multiple HAP files and deploy them on different devices. Assume that an application contains one entry-type HAP file (**Entry.hap**) and two feature-type HAP files (**Feature1.hap** and **Feature2.hap**). The **Entry.hap** file can be deployed on device A and device B, the **Feature1.hap** file can be deployed only on device A, and the **Feature2.hap** can be deployed only on device B. In this way, you can easily combine the **Entry.hap** and **Feature1.hap** files and deploy them on device A, and combine the **Entry.hap** and **Feature2.hap** files and deploy them on device B. + +- On-demand loading: You can load modules only when they are needed, reducing the package size. Specifically, you can configure some HAP files of an application to be loaded on demand. For example, if some features are not used during application startup, you can configure them to be loaded only when they are needed, rather than being loaded at startup. This can reduce the size of the application package to some extent. + +- Easier resource sharing: The resources (including public resource files and public pages) and shared objects (.so library files) required by multiple HAP files can be stored in an independent HAP file. In this way, other HAP files can obtain the resources and files by accessing the HAP, which reduces the size of the application package to some extent. diff --git a/en/application-dev/quick-start/multi-hap-principles.md b/en/application-dev/quick-start/multi-hap-principles.md new file mode 100644 index 0000000000000000000000000000000000000000..9268c0ddafacf26962d8a3d46d9f2adf98e6aac4 --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-principles.md @@ -0,0 +1,21 @@ +# Multi-HAP Operation Mechanism and Data Communication Modes + + +The multi-HAP mechanism is used to facilitate modular management for developers. There is no one-to-one mapping between the HAP and the running process of the application. The detailed running mechanism is as follows: + + +- By default, all UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in the same independent process, and other ExtensionAbility components of the same type run in separate processes. + +- The HAP file supports the process configuration through the **process** tag in the **module.json5** (stage model) or **config.json** (FA model) file. This feature is supported only by system applications. If **process** is configured for an HAP file, all components of the HAP file run in an independent process. Multiple HAP files can be configured with the same process, in which case the HAP files run in the same process. For details about the process configuration, see [module.json5 Configuration File](module-configuration-file.md). + +- When an application is running, the resources and code of the corresponding HAP file are loaded only when the UIAbility component in the same process is started. + + +Based on the preceding mechanism, the multi-HAP data communication modes are as follows: + + +- For details about data communication in the same process, see [Thread Model (Stage Model)](../application-models/thread-model-stage.md). + +- For details about cross-process data communication, see [Process Model (Stage Model)](../application-models/process-model-stage.md). + +- If multiple HAPs run in the same process, the communication mode between the components of multiple HAP files is the same as that between the components of the same HAP file. diff --git a/en/application-dev/quick-start/multi-hap-release-deployment.md b/en/application-dev/quick-start/multi-hap-release-deployment.md new file mode 100644 index 0000000000000000000000000000000000000000..785f476bf2fa508470d433477f4e1139e76589fd --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-release-deployment.md @@ -0,0 +1,51 @@ +# Multi-HAP Development, Debugging, Release, and Deployment Process + +Below is the process of developing, debugging, releasing, and deploying multiple HAP files. + +**Figure 1** Process of developing, debugging, releasing, and deploying multiple HAP files +![hap-release](figures/hap-release.png) + +## Development +You can use [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio) to create multiple modules based on service requirements and develop services in independent modules. + +## Debugging +You can use DevEco Studio to build code into one or more HAP files. Then, you can debug the HAP files. +* 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 + + 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 + // The execution result is as follows: + install bundle successfully. + // Uninstall + hdc_std uninstall com.example.myapplication + // The execution result is as follows: + uninstall bundle successfully. + ``` + +* Using Bundle Manager (bm) 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: + ``` + // 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: + install bundle successfully. + // Uninstall + bm uninstall -n com.example.myapplication + // The execution result is as follows: + uninstall bundle successfully. + ``` +## 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. + +## Deployment +The application market on the cloud distributes the applications to application market clients. These applications can contain one or more HAP files. After the user selects an application to download, the application market downloads all the HAP files contained in this application. + +## Installation on a Device +After the download is complete, the application market client calls the installation API of the bundle manager service in the system to install the downloaded HAP files. The bundle manager service deploys HAP files by application in the specified directory to complete the application installation. diff --git a/en/application-dev/quick-start/multi-hap-rules.md b/en/application-dev/quick-start/multi-hap-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..34b7824cb62b7e1ca73232faa9f58685df2077ac --- /dev/null +++ b/en/application-dev/quick-start/multi-hap-rules.md @@ -0,0 +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. + +- 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. + +- 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. + +- 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. diff --git a/en/application-dev/quick-start/package-structure.md b/en/application-dev/quick-start/package-structure.md deleted file mode 100644 index 6c1ecfe7be836e8b17dcb7d6d1045354d5aa386d..0000000000000000000000000000000000000000 --- a/en/application-dev/quick-start/package-structure.md +++ /dev/null @@ -1,797 +0,0 @@ - - -# Application Package Structure Configuration File - -When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file. - -## Internal Structure of the config.json File - -The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. For details, see Table 1. - -Table 1 Internal structure of the config.json file - -| Tag | Description | Data Type| Initial Value Allowed| -| ------------ | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of the application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#internal-structure-of-the-deviceconfig-tag).| Object | No | -| module | Configuration of a HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | - -Example of the **config.json** file: - -```json -{ - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5, - "releaseType": "Beta1" - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication.entrymodule", - "name": ".MyApplication", - "deviceType": [ - "default" - ], - "distro": { - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.entrymodule.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "$string:app_name", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } -} -``` - -### Internal Structure of the app Tag - -The **app** tag contains the global configuration information of the application. For details about the internal structure, see Table 2. - -Table 2 Internal structure of the app tag - -| Attribute | Description | Data Type| Initial Value Allowed | -| ----------------- | ------------------------------------------------------------ | -------- | --------------------------- | -| bundleName | Bundle name, which uniquely identifies an application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | -| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | -| version | Version of the application. For details, see Table 3. | Object | No | -| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty) | -| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8.| Boolean | Yes (initial value: **false**)| -| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8. | Boolean | Yes (initial value: **true**) | -| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | - -Table 3 Internal structure of version - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------ | ------------------------------------------------------------ | -------- | -------------------------- | -| name | Application version number visible to users. The value can be customized and cannot exceed 127 bytes. The customization rules are as follows:
API 5 and earlier versions: A three-segment version number is recommended, for example, A.B.C (also compatible with A.B). In the version number, A, B, and C are integers ranging from 0 to 999. Other formats are not supported.
A indicates the major version number.
B indicates the minor version number.
C indicates the patch version number.
API 6 and later versions: A four-segment version number is recommended, for example, A.B.C.D. In the version number, A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
A indicates the major version number.
B indicates the minor version number.
C indicates the feature version number.
D indicates the patch version number.| Number | No | -| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The value rules are as follows:
API 5 and earlier versions: It is a non-negative integer less than 32 bits in binary mode, converted from the value of version.name as follows: The conversion rules are as follows:
Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001.
API 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer ranging from 2 to 31. Note that the value must be updated each time the application version is updated. The value for a later version must be greater than that for an earlier version.| Number | No | -| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| - -Table 4 Internal structure of apiVersion - -| Attribute | Description | Data Type| Initial Value Allowed| -| ----------- | ----------------------------------------------------------- | -------- | ---------- | -| compatible | Minimum API version required for running the application. The value ranges from 0 to 2147483647. | Integer | Yes | -| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Integer | Yes | -| releaseType | Type of the target API version required for running the application. | String | Yes | - -Example of the app tag structure: - -```json -"app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5, - "releaseType": "Beta1" - } -} -``` - -### Internal Structure of the deviceConfig Tag - -The **deviceConfig** tag contains the application configuration information on the device, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. For details about the internal structure, see Table 5. - -Table 5 Internal structure of the deviceConfig tag - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ----------------------------------------- | -------- | ------------------ | -| default | Application configuration applied to all types of devices. For details, see Table 6.| Object | No | -| tablet | Application configuration specific to tablets. For details, see Table 6. | Object | Yes (initial value: left empty)| -| tv | Application configuration specific to smart TVs. For details, see Table 6. | Object | Yes (initial value: left empty)| -| car | Application configuration specific to head units. For details, see Table 6. | Object | Yes (initial value: left empty)| -| wearable | Application configuration specific to wearables. For details, see Table 6.| Object | Yes (initial value: left empty)| - -For details about the internal structures of device attributes, see Table 6. - -Table 6 Internal structure of device attributes - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------ | ------------------------------------------------------------ | -------- | ----------------------- | -| process | Process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters.| String | Yes | -| keepAlive | Whether the application is always kept alive. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | -| supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**)| -| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **true**) | -| directLaunch | Whether the application can be started when the device is locked. The value **true** means that the application can be started when the device is locked. Devices running OpenHarmony do not support this attribute.| Boolean | Yes (initial value: **false**)| -| ark | Maple configuration. For details, see Table 7. | Object | Yes (initial value: left empty) | -| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. For details, see Table 9.| Object | Yes (initial value: left empty) | - -Table 7 Internal structure of the ark attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | -------------------------------- | -------- | ------------------------------ | -| reqVersion | Maple version required for the application. For details, see Table 8.| Object | No | -| flag | Type of the Maple application. | String | No (available options: **m**, **mo**, **z**).| - -Table 8 Internal structure of the reqVersion attribute - -| Attribute | Description | Data Type| Initial Value Allowed| -| ---------- | --------------------------------------------------------- | -------- | ---------- | -| compatible | Minimum Maple version required for the application. The value is a 32-bit unsigned integer.| Integer | No | -| target | Type of the Maple application. The value is a 32-bit unsigned integer. | Integer | No | - -Table 9 Internal structure of the network attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------------- | ------------------------------------------------------------ | -------- | ----------------------- | -| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.
**true**: The application is allowed to use plaintext traffic.
**false**: The application is not allowed to use plaintext traffic.| Boolean | Yes (initial value: **false**)| -| securityConfig | Network security configuration of the application. For details, see Table 10. | Object | Yes (initial value: left empty) | - -Table 10 Internal structure of the securityConfig attribute - -| Attribute | Sub-attribute | Description | Data Type| Initial Value Allowed | -| -------------- | ------------------ | ------------------------------------------------------------ | -------- | ---------------- | -| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| -| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | -| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | - -Example of the deviceConfig tag structure: - -```json -"deviceConfig": { - "default": { - "process": "com.example.test.example", - "supportBackup": false, - "network": { - "cleartextTraffic": true, - "securityConfig": { - "domainSettings": { - "cleartextPermitted": true, - "domains": [ - { - "subdomains": true, - "name": "example.ohos.com" - } - ] - } - } - } - } -} -``` - -### Internal Structure of the module Tag - -The **module** tag contains the configuration information of the HAP file. For details about the internal structure, see Table 11. - -Table 11 Internal structure of the module tag - -| Attribute | Description | Data Type | Initial Value Allowed | -| ----------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | -| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | No | -| name | Class name of the HAP file. The value is in the reverse domain name notation, with the prefix same as the package name specified by **package** at the same level. It can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | -| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | -| deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No | -| distro | Distribution description of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 12.| Object | No | -| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | -| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | -| js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | -| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | -| reqPermissions | Permissions that the application requests from the system when it is running. For details, see Table 21. | Object array | Yes (initial value: left empty) | -| colorMode | Color mode of the application. Available values are as follows:
**"dark"**: Resources applicable for the dark mode are selected.
**"light"**: Resources applicable for the light mode are selected.
**"auto"**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **auto**) | -| distroFilter | Distribution rules of the application.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29.| Object | Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| -| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | -| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | -| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | -| testRunner | Test runner configuration. For details, see Table 36. | Object | Yes (initial value: left empty) | -| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The caller of the application must have these permissions to properly call the app. For details, see Table 37.| Object | Yes (initial value: left empty) | - -Example of the **module** tag structure: - -```json -"module": { - "mainAbility": "MainAbility", - "package": "com.example.myapplication.entry", - "name": ".MyOHOSAbilityPackage", - "description": "$string:description_application", - "supportModes": [ - "drive" - ], - "deviceType": [ - "car" - ], - "distro": { - "moduleName": "ohos_entry", - "moduleType": "entry" - }, - "abilities": [ - ... - ], - "shortcuts": [ - ... - ], - "js": [ - ... - ], - "reqPermissions": [ - ... - ], - "colorMode": "light" -} -``` - -Table 12 Internal structure of the distro attribute - -| Attribute | Description | Data Type| Initial Value Allowed| -| ---------------- | ------------------------------------------------------------ | -------- | ---------- | -| moduleName | Name of the HAP file. The maximum length is 31 characters. | String | No | -| moduleType | Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**.| String | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
- When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
- When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| deliveryWithInstall | Whether the HAP file is installed with application.
**true**: The HAP file is installed together with the application.
**false**: The HAP file is not installed together with the application.| Boolean| No| - -Example of the **distro** attribute structure: - -```json -"distro": { - "moduleName": "ohos_entry", - "moduleType": "entry", - "installationFree": true, - "deliveryWithInstall": true -} -``` - -Table 13 Internal structure of the metaData attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | ------------------------------------------------------------ | -------- | -------------------- | -| parameters | Metadata of the parameters to be passed for calling the ability. The metadata of each parameter consists of the **description**, **name**, and **type** sub-attributes. For details, see Table 14.| Object array| Yes (initial value: left empty) | -| results | Metadata of the ability return value. The metadata of each return value consists of the **description**, **name**, and **type** sub-attributes. For details, see Table 15.| Object array| Yes (initial value: left empty)| -| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**. For details, see Table 16.| Object array| Yes (initial value: left empty)| - -Table 14 Internal structure of the parameters attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ----------- | ------------------------------------------------------------ | -------- | ------------------ | -| description | Description of the parameter passed for calling the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| -| name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the parameter passed for calling the ability, for example, **Integer**. | String | No | - -Table 15 Internal structure of the results attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ----------- | ------------------------------------------------------------ | -------- | -------------------- | -| description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| -| name | Name of the return value. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the return value, for example, **Integer**. | String | No | - -Table 16 Internal structure of the customizeData attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ---------------------------------------------------------- | -------- | -------------------- | -| name | Key of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Custom format of the data item. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| - -Example of the **metaData** attribute structure: - -```json -"metaData": { - "parameters" : [{ - "name" : "string", - "type" : "Float", - "description" : "$string:parameters_description" - }], - "results" : [{ - "name" : "string", - "type" : "Float", - "description" : "$string:results_description" - }], - "customizeData" : [{ - "name" : "string", - "value" : "string", - "extra" : "$string:customizeData_description" - }] -} -``` - -Table 17 Internal structure of the abilities attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | -| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | -| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 characters. | String | No | -| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | -| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. | String | Yes (initial value: left empty) | -| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty) | -| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 characters. | String | Yes (No for abilities using the Data template) | -| launchType | Launch type of the ability. Available values are as follows:
**"standard"**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**"singleton"**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **"singleton"**) | -| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean | Yes (initial value: **false**) | -| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | -| skills | Types of the **want** that can be accepted by the ability. | Object array | Yes (initial value: left empty) | -| deviceCapability | Device capabilities required to run the ability.| String array| Yes (initial value: left empty) | -| metaData | Metadata. For details, see Table 13. | Object | Yes (initial value: left empty) | -| type | Ability type. Available values are as follows:
**"page"**: FA developed using the Page template to provide the capability of interacting with users.
**"service"**: PA developed using the Service template to provide the capability of running tasks in the background.
**"data"**: PA developed using the Data template to provide unified data access for external systems.
**"CA"**: ability that can be started by other applications as a window. | String | No | -| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
**"unspecified"**: indicates that the system automatically determines the display orientation of the ability.
**"landscape"**: indicates the landscape orientation.
**"portrait"**: indicates the portrait orientation.
**"followRecent"**: indicates that the orientation follows the most recent application in the stack. | String | Yes (initial value: **"unspecified"**) | -| backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This attribute applies only to the ability using the Service template. Available values are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**pictureInPicture**: picture in picture (PiP) and small-window video playback services
**voip**: voice/video call and VoIP services
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services
**wifiInteraction**: WLAN scanning, connection, and transmission services
**screenFetch**: screen recording and screenshot services
**multiDeviceConnection**: multi-device interconnection service| String array| Yes (initial value: left empty) | -| grantPermission | Whether permissions can be granted for any data in the ability. | Boolean | Yes (initial value: left empty) | -| readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| writePermission | Permission required for writing data to the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. Available values are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user has selected a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty) | -| mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: bundle name of the application) | -| targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty, indicating that the current ability is not an alias)| -| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | -| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | -| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean| Yes (initial value: **false**) | -| forms | Information about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | -| srcLanguage | Programming language used to develop the ability. The value can be **"js"** or **"ets"**. | String | Yes | -| srcPath | Path of the JS component code corresponding to the ability. | String | Yes (initial value: left empty) | -| uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$media:icon**.| String | Yes (initial value: left empty)| -| startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String | Yes (initial value: left empty)| -| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| - -Table 18 Internal structure of the uriPermission attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ----------------------- | -------- | ------------------------- | -| path | Path identified by **uriPermission**.| String | No | -| mode | Mode matching the **uriPermission**.| String | Yes (initial value: *default***)| - -Example of the **abilities** attribute structure: - -```json -"abilities": [ - { - "name": ".MainAbility", - "description": "test main ability", - "icon": "$media:ic_launcher", - "label": "$media:example", - "launchType": "standard", - "orientation": "unspecified", - "permissions": [], - "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ] - } - ], - "configChanges": [ - "locale", - "layout", - "fontSize", - "orientation" - ], - "type": "page", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red", - "removeMissionAfterTerminate": true - }, - { - "name": ".PlayService", - "description": "example play ability", - "icon": "$media:ic_launcher", - "label": "$media:example", - "launchType": "standard", - "orientation": "unspecified", - "visible": false, - "skills": [ - { - "actions": [ - "action.play.music", - "action.stop.music" - ], - "entities": [ - "entity.audio" - ] - } - ], - "type": "service", - "backgroundModes": [ - "audioPlayback" - ] - }, - { - "name": ".UserADataAbility", - "type": "data", - "uri": "dataability://com.example.world.test.UserADataAbility", - "visible": true - } -] -``` - -Table 19 Internal structure of the skills attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | ------------------------------------------------------------ | ---------- | -------------------- | -| actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| -| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| -| uris | URIs of the **want** that can be accepted by the ability. For details, see Table 20.| Object array | Yes (initial value: left empty)| - -Table 20 Internal structure of the uris attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | -------------------------- | -------- | -------------------- | -| scheme | Scheme of the URI. | String | No | -| host | Host value of the URI. | String | Yes (initial value: left empty)| -| port | Port number of the URI. | String | Yes (initial value: left empty)| -| pathStartWith | **pathStartWith** value of the URI.| String | Yes (initial value: left empty)| -| path | **path** value of the URI. | String | Yes (initial value: left empty)| -| pathRegx | **pathRegx** value of the URI. | String | Yes (initial value: left empty)| -| type | **type** value of the URI. | String | Yes (initial value: left empty)| - -Example of the **skills** attribute structure: - -```json -"skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ - { - "scheme": "http", - "host": "www.example.com", - "port": "8080", - "path": "query/student/name", - "type": "text/*" - } - ] - } -] -``` - -Table 21 reqPermissions - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| name | Name of the permission to request.| String| No| -| reason | Reason for requesting the permission. The value cannot exceed 256 bytes. Multi-language adaptation is required.| String| No if the requested permission is **user_grant** (if it is left empty, application release will be rejected)| -| usedScene | Application scenario and timing for using the permission. This attribute consists of the **ability** and **when** sub-attributes. **ability**: ability name. Multiple ability names can be configured. **when**: time for using the permission. The options are **inuse** and **always**.| Object| **ability**: mandatory for the **user_grant** permission and can be left empty in other cases
**when**: initial value allowed (initial value: **inuse**)| -For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). - -Table 22 Internal structure of the js attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | ------------------------ | -| name | Name of the JS component. The default value is **default**. | String | No | -| pages | Route information about all pages in the JS component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | -| window | Window-related configurations. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 23.| Object | Yes | -| type | Type of the JS component. Available values are as follows:
**"normal"**: indicates that the JavaScript component is an application instance.
**"form"**: indicates that the JavaScript component is a widget instance. | String | Yes (initial value: **"normal"**) | -| mode | Development mode of the JS component. For details, see Table 24. | Object | Yes (initial value: left empty) | - -Table 23 Internal structure of the window attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | -------- | ----------------------- | -| designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | -| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean | Yes (initial value: **false**)| - -Table 24 Internal structure of the mode attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | -------------------- | ----------------------------------- | --------------------------- | -| type | Type of the JS component. The value can be **"pageAbility"** or **"form"**. | String | Yes (initial value: **"pageAbility"**) | -| syntax | Syntax type of the JS component. The value can be **"hml"** or **"ets"**. | String | Yes (initial value: **"hml"**) | - -Example of the **js** attribute structure: - -```json -"js": [ - { - "name": "default", - "pages": [ - "pages/index/index", - "pages/detail/detail" - ], - "window": { - "designWidth": 720, - "autoDesignWidth": false - }, - "type": "form" - } -] -``` - -Table 25 Internal structure of the shortcuts attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| -| icon | Icon of the shortcut. The value is a resource index to the description. | String | Yes (initial value: left empty)| -| intents | Intents to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes. For details, see Table 26.| Object array| Yes (initial value: left empty)| - -Table 26 Internal structure of the intents attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------ | --------------------------------------- | -------- | -------------------- | -| targetClass | Target class of the shortcut. | String | Yes (initial value: left empty)| -| targetBundle | Application bundle name for the target ability of the shortcut.| String | Yes (initial value: left empty)| - -Example of the **shortcuts** attribute structure: - -```json -"shortcuts": [ - { - "shortcutId": "id", - "label": "$string:shortcut", - "intents": [ - { - "targetBundle": "com.example.world.test", - "targetClass": "com.example.world.test.entry.MainAbility" - } - ] - } -] -``` - -Table 27 Internal structure of the forms attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | -| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | -| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | -| colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| -| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 1: indicates a grid with two rows and one column.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | -| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | -| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | -| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | -| formConfigAbility | Name of the facility or activity used to adjust the ability. | String | Yes (initial value: left empty) | -| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | -| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | -| metaData | Metadata of the widget. The value contains value of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | -| customizeData | Custom information of the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | - -Table 28 Internal structure of the customizeData attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | --------------------------------------------------- | -------- | -------------------- | -| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Current format of the custom data. The value indicates the resource.| String | Yes (initial value: left empty)| - -Example of the **forms** attribute structure: - -```json -"forms": [ - { - "name": "Form_Js", - "description": "It's Js Form", - "type": "JS", - "jsComponentName": "card", - "colorMode": "auto", - "isDefault": true, - "updateEnabled": true, - "scheduledUpdateTime": "11:00", - "updateDuration": 1, - "defaultDimension": "2*2", - "supportDimensions": [ - "2*2", - "2*4", - "4*4" - ] - }, - { - "name": "Form_Js", - "description": "It's JS Form", - "type": "Js", - "colorMode": "auto", - "isDefault": false, - "updateEnabled": true, - "scheduledUpdateTime": "21:05", - "updateDuration": 1, - "defaultDimension": "1*2", - "supportDimensions": [ - "1*2" - ], - "landscapeLayouts": [ - "$layout:ability_form" - ], - "portraitLayouts": [ - "$layout:ability_form" - ], - "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", - "metaData": { - "customizeData": [ - { - "name": "originWidgetName", - "value": "com.example.weather.testWidget" - } - ] - } - } -] -``` - -Table 29 Internal structure of the distroFilter attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | ------------------------------------------------------------ | -------- | -------------------- | -| apiVersion | Supported API versions. For details, see Table 30. | Object | Yes (initial value: left empty)| -| screenShape | Supported screen shapes. For details, see Table 31. | 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. For details, see Table 32.| Object array| Yes (initial value: left empty)| -| screenDensity | Pixel density of the screen, in dots per inch (dpi). For details, see Table 33. | Object array| Yes (initial value: left empty)| -| countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| Yes (initial value: left empty)| - -Table 30 Internal structure of the apiVersion attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. Example: If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| - -Table 31 Internal structure of the screenShape attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAPs can be provided for a smart watch with a circular face and that with a rectangular face.| Array | Yes (initial value: left empty)| - -Table 32 Internal structure of the screenWindow attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Width and height of the screen. The value of a single string is in the format of Width x Height in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| - -Table 33 Internal structure of the screenDensity attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Available values are as follows:
**sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].
**xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].
**xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].
**xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640].| Array | Yes (initial value: left empty)| - -Table 34 Internal structure of the countryCode attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | ------------------------------------------------------------ | ---------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Country code of the area to which the application is to be distributed. The value is a string array, of which each substring indicates a country or region. The substring consists of two uppercase letters.| String array| Yes (initial value: left empty)| - -Example of the **distroFilter** attribute structure: - -```json -"distroFilter": { - "apiVersion": { - "policy": "include", - "value": [4,5] - }, - "screenShape": { - "policy": "include", - "value": ["circle","rect"] - }, - "screenWindow": { - "policy": "include", - "value": ["454*454","466*466"] - }, - "screenDensity":{ - "policy": "exclude", - "value": ["ldpi","xldpi"] - }, - "countryCode": { - "policy":"include", - "value":["CN","HK"] - } -} -``` - -Table 35 Internal structure of the commonEvents attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | ---------- | ------------------ | -| name | Name of a static broadcast. | String | No | -| permission | Permission needed to implement the static common event. | String array| Yes (initial value: left empty)| -| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| -| type | Type array of the current static common event. | String array| Yes (initial value: left empty)| -| events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No | - -Example of the **commonEvents** attribute structure: - -```json -"commonEvents": [ - { - "name":"MainAbility", - "permission": "string", - "data":[ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - } -] -``` - -Table 36 Internal structure of the testRunner attribute - -| Attribute| Description | Data Type| Initial Value Allowed| -| -------- | -------------------- | -------- | ---------- | -| name | Name of the test runner object.| String | No | -| srcPath | Path of the test runner code.| String | No | - -```json -"testRunner": { - "name": "myTestRUnnerName", - "srcPath": "etc/test/TestRunner.ts" -} -``` - -Table 37 Internal structure of the definePermissions attribute -**definePermission** applies only to system applications and does not take effect for third-party applications. - -| Attribute | Description | Data Type| Initial Value Allowed| -| ----------------------- | ------------------------------------------------------------ | -------- | ---------- | -| name | Permission name. | String | No | -| grantMode | Permission grant mode.
Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user. | String | Yes (initial value: **"system_grant"**) | -| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | -| provisionEnable | Whether the permission can be requested in provision mode. | Boolean | Yes (initial value: **true**) | -| distributedSceneEnabled | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | -| label | Brief description of the permission. The value is a resource index. | String | Yes | -| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes | 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 b79359a99ee1f7ecf434a7858a7ee1999b9af5d5..56e8209a5c19e353a21b80ff8b34dd51885db310 100644 --- a/en/application-dev/quick-start/resource-categories-and-access.md +++ b/en/application-dev/quick-start/resource-categories-and-access.md @@ -83,6 +83,7 @@ You can create resource group subdirectories (including element, media, and prof | ------- | ---------------------------------------- | ---------------------------------------- | | 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**. | | 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** diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index 03845296847a43338cca31673b76e46b8c496bbf..ff66e3d405738a44f0c645593ffb0dbfb5beca97 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -1,843 +1,25 @@ +# Application Configuration File Overview (Stage Model) -# Application Package Structure Configuration File +Each application project must have configuration files in its code directory. These configuration files provide basic application information for build tools, operating systems, and application markets. -When developing an application in the Feature Ability (FA) model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json5** and **app.json** files. -## Configuration File Internal Structure +In the code directory of an application project developed in stage model, there are two types of configuration files: one **app.json5** file and one or more **module.json5** files. -The configuration files each consist of two mandatory tags, namely, **app** and **module**. For details, see Table 1. -Table 1 Configuration file internal structure +The [app.json5](app-configuration-file.md) file contains the following contents: -| Tag| Description | Data Type| Initial Value Allowed| -| -------- | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of the application. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| module | Configuration of the HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | -### Internal Structure of the app Tag +- Application-wide configuration, including the bundle name, developer, and version number. -Code snippet in the **app.json** file: +- Device-specific configuration. -```json -{ - "app": { - "bundleName": "com.application.music", - "vendor": "application", - "versionCode": 1, - "versionName": "1.0", - "minCompatibleVersionCode": 1, - "minAPIVersion": 7, - "targetAPIVersion": 8, - "apiReleaseType": "Release", - "debug": false, - "icon": "$media:app_icon", - "label": "$string:app_name", - "description": "$string:description_application", - "distributedNotificationEnabled": true, - "entityType": "game", - "car": { - "apiCompatibleVersion": 8 - } - } -} -``` -This tag is an application-level attribute that applies to all the HAP files and components in the application. For the internal structure of the tag, see Table 2. +The [module.json5](module-configuration-file.md) file contains the following contents: -Table 2 Internal structure of the app tag -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | Bundle name that uniquely identifies the application. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
For an application compiled with the system source code, its bundle name must be in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony. | String | No | -| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | -| icon | Icon of the application. The value is the index to the resource file. | String | No | -| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | -| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | -| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | -| minCompatibleVersionCode | Earliest version that the application is compatible with. It is used to determine cross-device compatibility. | Number | Yes (initial value: value of **versionCode**)| -| minAPIVersion | Minimum API version required for running the application. | Integer | Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| -| targetAPIVersion | Target API version required for running the application. | Integer | Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| -| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | -| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | -| entityType | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: **"unspecified"**) | -| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8. | Boolean | Yes (initial value: **false**) | -| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | -| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | -| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | -| accessible | Whether the installation directory of the application is accessible. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the installation directory can be accessed by third-party applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| multiProjects | Whether multiple projects are supported.| Boolean| Yes (initial value: **false**)| -| deviceType | Supported device types, such as **tablet**, **tv**, **wearable**, and **car**. The following attributes may be included: **minAPIVersion**, **distributedNotificationEnabled**, **keepAlive**, and **removable**.| Object | Yes (initial value: settings under **"app"**)| +- Basic module configuration, such as the name, type, description, and supported device types of the module. -### Internal Structure of the module Tag +- Information about the [application components](../application-models/stage-model-development-overview.md), including the descriptions of the UIAbility and ExtensionAbility components. -Code snippet in the **module.json5** file: - -```json -{ - "module": { - "name": "myHapName", - "type": "entry|feature|har", - "srcEntrance" : "./MyAbilityStage.js", - "description" : "$string:description_application", - "mainElement": "MainAbility", - "deviceTypes": [ - "tablet", - "tv", - "wearable", - "car", - "router" - ], - "deliveryWithInstall": true, - "installationFree": false, - "virtualMachine": "ark | default", - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file1" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file2" - } - ], - "abilities": [ - { - "name": "MainAbility", - "srcEntrance" : "./login/MyMainAbility.ts", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "HiMusic", - "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ ] - } - ], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red" - }, - { - "name": "sampleAbility", - "srcEntrance" : "./login/sampleAbility.ts", - "description": "$string:description_sample_ability", - "icon": "$media:icon", - "label": "HiMusic", - "visible": true, - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red" - } - ], - "requestPermissions": [ - { - "name": "ohos.abilitydemo.permission.PROVIDER", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "FormAbility" - ], - "when": "inuse" - } - } - ] - } -} -``` - -This tag stores the HAP configuration, which only applies to the current HAP file. - -Table 3 Internal structure of the module tag - -| Attribute | Description | Data Type | Initial Value Allowed | -| -------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | Name of the current module. After the module is packed into a HAP file, this attribute indicates the name of the HAP file. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String | No | -| type | Type of the HAP file. There are three types: **entry**, **feature**, and **har**.| String | No | -| srcEntrance | Path of the entry JS code corresponding to the HAP file. The value is a string with a maximum of 127 bytes.| String | Yes | -| description | Description of the HAP file. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| process | Process of the HAP file. The value is a string with a maximum of 31 bytes. If a process is configured under **hap**, all abilities of the application run in this process. This attribute applies only to system applications.| String | Yes (initial value: value of **bundleName** under the **app** tag) | -| mainElement | Entrance ability name or extension name of the HAP file. Only the ability or extension whose value is **mainElement** can be displayed in the Service Center. This attribute cannot be left at the initial value for an OpenHarmony atomic service.| String | Yes for an OpenHarmony application | -| deviceTypes | Types of the devices on which the HAP file can run. Table 4 lists the device types predefined by the system.
Unlike **syscap**, which is based on the device capability (such as Bluetooth and Wi-Fi), **deviceTypes** is based on the device type.| String array| No (can be left empty) | -| deliveryWithInstall | Whether the current HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| Boolean | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.

When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap** must be **true**.
When **entry.hap** is set to **false**, **feature.hap** fields related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
If the target VM type is Ark, the value is **ark**. Otherwise, the value is **default**. This attribute is automatically inserted when the IDE builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | -| uiSyntax(deprecated) | Syntax type of the JS component. This attribute is deprecated since API version 9.
**"hml"**: indicates that the JS component is developed using HML, CSS, or JS.
**"ets"**: indicates that the JS component is developed using the eTS declarative syntax.| String | Yes (initial value: **"hml"**) | -| pages | Profile resource used to list information about each page in the JS component. For details about how to use **pages**, see the **pages** example.| Object | No in the ability scenario | -| metadata | Custom metadata of the HAP file. The configuration is valid only for the current module, ability, or extensionAbility. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | -| abilities | Ability configuration, which is valid only for the current ability. For details, see [Internal Structure of the abilities Attribute](#internal-structure-of-the-abilities-attribute).| Object | Yes (initial value: left empty) | -| extensionAbilities | Extension ability configuration, which is valid only for the current Extension ability. For details, see [Internal structure of the extensionAbility attribute](#internal-structure-of-the-extensionability-attribute).| Object | Yes (initial value: left empty) | -| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The callers must acquire these permissions before calling the application. For details, see [Internal structure of the definePermissions attribute](#internal-structure-of-the-definepermissions-attribute).| Object | Yes (initial value: left empty)| -| requestPermissions | A set of permissions that the application needs to request from the system when the application is running. For details, see [Internal structure of the requestPermissions attribute](#internal-structure-of-the-requestpermissions-attribute). | Object | Yes (initial value: left empty) | -| testRunner | Test runner configuration. For details, see [Internal structure of the testRunner attribute](#internal-structure-of-the-testrunner-attribute).| Object | Yes (initial value: left empty) | - -Table 4 System-defined deviceTypes values - -| Value | Device Type | -| -------- | -------------------------------------------------------- | -| tablet | Tablet, speaker with a screen | -| tv | Smart TV | -| wearable | Smart watch, kids' watch, especially a watch that provides call features| -| car | Head unit | -| router | Router | - -Example of the **deviceTypes** attribute structure: - -```json -{ - "module": { - "name": "myHapName", - "type": "har", - "deviceTypes" : [ - "wearable" - ] - } -} -``` - -Example of the **pages** attribute structure: - -```json -{ - "module": { - "name": "myHapName", - "type": "har", - "deviceTypes" : [ - "wearable" - ], - "pages": "$profile:pages_config" - } -} -``` - -Example of the **pages_config** configuration file: - -```json -{ - "src": [ - "pages/index/index", - "pages/second/second", - "pages/third/third", - "pages/four/four" - ] -} -``` - - - -#### Internal Structure of the metadata Attribute - -The **metadata** attribute provides the configuration about the module, ability, and extensionAbility. The value is of the array type. The configuration is valid only for the current module, ability, or extensionAbility. - -Table 5 Internal structure of the metadata attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------------- | -| name | Name of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | -| resource | Custom data format. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty) | - -Example of the **metadata** attribute structure: - -```json -{ - "module": { - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - } - ] - } -} -``` - -#### Internal Structure of the abilities Attribute - -The **abilities** attribute describes the ability configuration information. The value is of the array type. - -Table 6 Internal structure of the abilities attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| name | Logical name of the ability, which must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String | No | -| srcEntrance | JS code path corresponding to the ability. The value is a string with a maximum of 127 bytes.| String | No | -| launchType | Ability startup mode. Available values are as follows:
**"standard"**: indicates common multi-instance.
**"singleton"**: indicates a singleton.
**"specified"**: indicates one or more specified instances, depending on the internal service of the ability. | String | Yes (initial value: **singleton**) | -| description | Ability description. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the ability. The value is the index to the resource file. | String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| -| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | -| metadata | Metadata of the ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | -| visible | Whether the ability can be invoked by other applications. The value **true** means that the ability can be invoked by other applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| continuable | Whether the ability can be migrated. The value **true** means that the ability can be migrated, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | -| backgroundModes | Continuous task modes of the ability.
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 (multi-screen cloning)
**voip**: voice/video call and VoIP services
**taskKeeping**: computing service
| String | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example: **$media:icon**.| String | No| -| startWindowBackground | Index to the background color resource file of the ability startup page. Example: **$color:red**.| String | No| -| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| -| orientation | Display orientation of the ability when it is started. Available values are as follows:
**"unspecified"**: The device orientation is auto-set by the system.
**"landscape"**: The device is in landscape orientation.
**"portrait"**: The device is in portrait orientation.
**"landscape_inverted"**: The device is in inverted landscape orientation.
**"portrait_inverted"**: The device is in inverted portrait orientation.
**"auto_rotation"**: The device orientation is determined by the sensor.
**auto_rotation_landscape**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape.
**auto_rotation_portrait**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait.
**auto_rotation_restricted**: The device orientation is determined by the sensor when the sensor switch is enabled.
**auto_rotation_landscape_restricted**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape, when the sensor switch is enabled.
**auto_rotation_portrait_restricted**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait, when the sensor switch is enabled.
**locked**: Auto rotate is disabled.| String | Yes (initial value: **"unspecified"**)| -|supportWindowMode|Window display mode of the ability. Available values are as follows:
**fullscreen**: full-screen mode.
**split**: split-screen mode.
**floating**: floating window mode.|Array | Yes (initial value:
["fullscreen", "split", "floating"])| -|priority|Priority of the ability. This attribute applies only to system applications and does not take effect for third-party applications. During implicit query, an ability with a higher the priority is closer to the top of the returned list. The value is an integer ranging from 0 to 10. A larger value indicates a higher priority.|Number| Yes (initial value: **0**)| -|maxWindowRatio|Maximum aspect ratio of the ability.| Number |Yes (initial value: maximum aspect ratio of the platform)| -|minWindowRatio|Minimum aspect ratio of the ability.| Number |Yes (initial value: minimum aspect ratio supported by the platform)| -|maxWindowWidth|Maximum window width of the ability, in vp.| Number |Yes (initial value: maximum window width supported by the platform)| -|minWindowWidth|Minimum window width of the ability, in vp.| Number |Yes (initial value: minimum window width supported by the platform)| -|maxWindowHeight|Maximum window height of the ability, in vp.| Number |Yes (initial value: maximum window height supported by the platform)| -|minWindowHeight|Minimum window height of the ability, in vp.| Number |Yes (initial value: minimum window height supported by the platform)| -| excludeFromMissions | Whether the ability is excluded from the recent tasks list. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** indicates that the task is excluded from the recent tasks list, and **false** indicates that the task is displayed in the recent tasks list.| Boolean | Yes (initial value: **false**)| - -Example of the **abilities** attribute structure: - -```json -{ - "abilities": [{ - "name": "MainAbility", - "srcEntrance": "./ets/login/MyLoginAbility.ts", - "launchType":"standard", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "Login", - "permissions": [], - "metadata": [], - "visible": true, - "continuable": true, - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red", - "removeMissionAfterTerminate": true, - "orientation": " ", - "supportWindowMode": ["fullscreen", "split", "floating"], - "maxWindowRatio": 3.5, - "minWindowRatio": 0.5, - "maxWindowWidth": 2560, - "minWindowWidth": 1400, - "maxWindowHeight": 300, - "minWindowHeight": 200, - "excludeFromMissions": false - }] -} -``` - -#### Internal Structure of the skills Attribute - -This attribute identifies a want feature that can be received by the ability or extension. - -Table 7 Internal structure of the skills attribute - -| Attribute| Description | Data Type | Initial Value Allowed | -| -------- | ------------------------------------------------------------ | ---------- | -------------------- | -| actions | A set of want action values that can be received. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| entities | Categories of abilities that can receive the want. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details, see Table 8.| Object array | Yes (initial value: left empty)| - -Table 8 Internal structure of the uris attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------- | -------- | -------------------- | -| scheme | Scheme of the URI.| String | No | -| host | Host value of the URI. | String | Yes (initial value: left empty)| -| port | Port number of the URI. | String | Yes (initial value: left empty)| -| path | **path** value of the URI. | String | Yes (initial value: left empty)| -| type | **type** value of the URI. | String | Yes (initial value: left empty)| - -Example of the **skills** attribute structure: - -```json -{ - "abilities": [ - { - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ], - "extensionAbilities": [ - { - "skills": [ - { - "actions": [ - ], - "entities": [ - ], - "uris": [ - { - "scheme":"uri2", - "host":"host2", - "port":"port2", - "pathStartWith":"path2", - "pathRegex":"/query/.*", - "path":"path", - "type": "text/*" - } - ] - } - ] - } - ] -} -``` - -#### Internal Structure of the extensionAbility Attribute - -The **extensionAbility** attribute describes the configuration information of the current Extension ability. - -Table 9 Internal structure of the extensionAbility attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ----------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Logical name of the current Extension ability. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String | No | -| srcEntrance | JS code path corresponding to the Extension ability. The value is a string with a maximum of 127 bytes.| String | No | -| description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the Extension ability. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | -| label | Name of the Extension ability displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | -| type | Type of the Extension ability. The value can be **"form"**, **"workScheduler"**, **"inputMethod"**, **"service"**, **"accessibility"**, **"dataShare"**, **"fileShare"**, **"staticSubscriber"**, **"wallpaper"**, **"backup"**, **"window"**, **"enterpriseAdmin"**, **"thumbnail"**, or **"preview"**.| String | No | -| permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value 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 ability. The value is an array containing a maximum of 255 characters and is in the format of a reverse domain name. This attribute is mandatory when **type** is set to **extensionAbility** of the dataShare type.| String | Yes (initial value: left empty) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | -| metadata | Metadata of the Extension ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | -| visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| Boolean | Yes (initial value: **false**)| - -Example of the **extensionAbility** attribute structure: - -```json -{ - "extensionAbilities": [ - { - "name": "FormName", - "srcEntrance": "./form/MyForm.ts", - "icon": "$media:icon", - "label" : "$string:extension_name", - "description": "$string:form_description", - "type": "form", - "permissions": ["ohos.abilitydemo.permission.PROVIDER"], - "readPermission": "", - "writePermission": "", - "visible": true, - "uri":"scheme://authority/path/query" - "skills": [{ - "actions": [], - "entities": [], - "uris": [] - }], - "metadata": [ - { - "name": "ohos.extability.form", - "resource": "$profile:form_config", - } - ] - } - ] -} - -``` - -#### Internal Structure of the definePermissions Attribute - -The **definePermissions** attribute indicates the permissions defined for the HAP file. - -Table 10 Internal structure of the definePermissions attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------ | -| name | Permission name. | String | No | -| grantMode | Permission grant mode. Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user.| String | Yes (initial value: **"system_grant"**)| -| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | -| provisionEnable | Whether to enable provision mode for requesting permissions, including higher-level permissions. The value **true** indicates that provision mode is enabled.| Boolean | Yes (initial value: **true**) | -| distributedSceneEnable | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | -| label | Brief description of the permission. The value is a resource index. | String | Yes (initial value: left empty) | -| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes (initial value: left empty) | - -#### Internal Structure of the requestPermissions Attribute - -This attribute identifies a set of permissions that the application needs to request from the system when the application is running. - -Table 11 Internal structure of the requestPermissions attribute - -| Attribute | Description | Type | Value Range | Default Value | Restrictions | -| --------- | ------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ | -| name | Permission name. This attribute is mandatory. | String | Custom | N/A | Parsing will fail if this attribute is not set. | -| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. | String | Resource reference of the string type in `$string: ***` format | Empty | If the permission to request is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| -| usedScene | Application scenario and timing for using the permission. This attribute is mandatory when the permission to request is **user_grant**. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured.| **abilities**: string array; **when**: string| **abilities**: array of ability names; **when**: **inuse** and **always**| **abilities**: left empty; **when**: left empty| If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional. | - -Example of the **requestPermissions** attribute structure: - -```json -{ - "name": "ohos.abilitydemo.permission.PROVIDER", - "reason": "$string:reason", - "usedScene": { - "abilities": [ - "AudioAbility", - "VideoAbility", - ], - "when": "inuse" - } -} -``` -For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). - -#### Internal Structure of the form Attribute - -The **forms** attribute indicates the service widget configuration. The service widget is an application brief view that can be displayed on the home screen and periodically updated. You can include the **forms** attribute in any of the following modes: - -1. Set **type** to **form** in **extensions**. - -2. Specify the **form** information in **metadata**, where: - - **name** indicates the name of the service widget, for example, **ohos.extability.form**. - - **resource** indicates where the resources of the service widget are stored. - -Table 12 Internal structure of the forms attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ------------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | -| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| src | UI code of a JS service widget. It is recommended that you use the adaptive layout to display a service widget of different specifications. If the layout of a service widget of different specifications differs greatly, you are advised to use different service widgets.| String | Yes (initial value: left empty) | -| window | Adaptive capability of a JS service widget. For details, see Table 12. | Object | Yes (initial value: left empty) | -| isDefault | Whether the widget is a default one. Each ability has only one default widget. **true**: The service widget is the default one. **false**: The service widget is not the default one.| Boolean | No | -| colorMode | Color mode of the widget. The value can be **auto**, **dark**, or **light**.| String | Yes (initial value: **auto**) | -| supportDimensions | Dimensions supported by the service widget. The value can be **1 * 2**, **2 * 1**, **2 * 2**, **2 * 4**, or **4 * 4**, where the number before the asterisk (*) indicates the number of rows, and the number after the asterisk (*) indicates the number of columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | -| updateEnabled | Whether the widget can be updated periodically. The value **true** indicates that the widget can be updated periodically, and **false** indicates that the widget cannot be updated periodically.| Boolean | No | -| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes | -| updateDuration | Update frequency of a widget. The unit is 30 minutes. The value is a multiple of 30. The highest frequency of refreshing a widget is once every 30 minutes. You can also use scheduled refresh to refresh a widget at a fixed time or once every 30 minutes. If both of them are configured, the scheduled refresh takes precedence.| Number | Yes (initial value: left empty) | -| metadata | Metadata of the widget. For details, see Table 5. | Object | Yes (initial value: left empty) | -| formConfigAbility | Ability name for widget adjustment. The value is a string of up to 127 characters. The value must be in the following format:
ability:// Name of an ability.
The name must be the same as that of the current application.| String | Yes (initial value: left empty) | -| formVisibleNotify | Whether the widget is allowed to use the visibility notification. The value is **true** or **false**.| Boolean | Yes (initial value: **false**)| - -Table 13 Internal structure of the window attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | -------- | -------------------- | -| designWidth | Baseline width of the page design, in pixels. The element size is scaled by the actual device width. The value is an integer.| Number | Yes (initial value: left empty)| -| autoDesignWidth | Whether to automatically calculate the baseline width of the page design. If this parameter is set to **true**, the **designWidth** attribute is invalid. The baseline width is calculated based on the device width and screen density.| Boolean | Yes (initial value: left empty)| - -Example of the **forms** attribute structure: - -Define the **form_config.json** file (this file name is customizable) in **resources/base/profile** of the development view. - -```json -{ - "forms": [ - { - "name": "Form_Js", - "description": "$string:form_description", - "src": "./js/pages/card/index", - "window": { - "designWidth": 720, - "autoDesignWidth": true - }, - "colorMode": "auto", - "formConfigAbility": "ability://xxxxx", - "formVisibleNotify": false, - "isDefault": true, - "updateEnabled": true, - "scheduledUpdateTime": "10:30", - "updateDuration": 1, - "defaultDimension": "2*2", - "updateEnabled": true, - "scheduledUpdateTime": "21:33", - "supportDimensions": [ - "2*2" - ], - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file" - } - ] - } - ] -} -``` - -Define metadata information in the **extension** component of the **module.json5** file. - -```json -{ - "extensionAbilities": [{ - "name": "MyForm", - "type": "form", - "metadata": [{ - "name": "ohos.extability.form", - "resource": "$profile:form_config" - }] - }] -} -``` - -#### Internal Structure of the shortcuts Attribute - -This attribute identifies the shortcut information of an application. The value is an array. A maximum of four shortcuts can be configured. It contains four sub-attributes: **shortcutId**, **label**, **icon**, and **wants**. - -Specify the **shortcut** information in **metadata**, where: - -- **name** indicates the name of the shortcut, for example, **ohos.ability.shortcuts**. - -- **resource** indicates where the resources of the shortcut are stored. - -Table 14 Internal structure of the shortcuts attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | -------------------------- | -| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | -| icon | Icon of the shortcut. The value is the index to the resource file. | String | Yes (initial value: left empty)| -| wants | Wants to which the shortcut points. The attribute consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut; string type.
**abilityName**: target component name of the shortcut; string type.| Object | Yes (initial value: left empty) | - -Define the **shortcut_config.json** file (this file name is customizable) in **resources/base/profile** of the development view. - -```json -{ - "shortcuts": [{ - "shortcutId": "id_test1", - "label": "$string:shortcut", - "icon": "$media:aa_icon", - "wants": [{ - "bundleName": "com.ohos.hello", - "abilityName": "MainAbility" - }] - }] -} -``` - -Define the **metadata** information under **module** in the **module.json5** file as follows: - -```json -{ - "module": { - "name": "MyAbilityStage", - "abilities": [{ - "name": "MyAbility", - "srcEntrance": "./abilities/MyAbility.ts", - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "metadata": [{ - "name": "ohos.ability.shortcuts", - "resource": "$profile:shortcuts_config" - }] - }] - } -} -``` - -#### Internal Structure of the commonEvents Attribute - -The **commonEvents** attribute identifies the registered static common event information. The value is an array. - -Specify the **commonEvent** information in the **metadata**, where: - -- **name** indicates the name of the common event, for example, **ohos.extability.staticSubscriber**. - -- **resource** indicates where the resources of the common event are stored. - -Table 15 Internal structure of the commonEvents attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | ---------- | -------------------------- | -| name | Ability name corresponding to the current static common event. The class must be marked in the ability.| String | No | -| permission | Permission required for implementing the static common event. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.| String | Yes (initial value: left empty) | -| types | Types of the current static common event. The value is an array of strings, each of which represents a type.| String array| Yes (initial value: left empty)| -| events | Events of the intents that can be accepted by the ability. The value can be customized or be the events predefined in the system.| String array| No | - -Define the **common_event_config.json** file in **resources/base/profile** in the development view. (The file name can be defined by developers.) - -```json -{ - "commonEvents": [{ - "name": "abilityName", - "permission": "string", - "types": [ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - }] -} -``` - -Define the **metadata** information under **extension** in the **module.json5** file as follows: - -```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:common_event_config", - }], - } -] -``` - -#### Internal Structure of the distroFilter Attribute - -Distribution rules of the application. - -This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. - -Table 16 Internal structure of the distroFilter attribute - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------- | ------------------------------------------------------------ | -------- | -------------------------- | -| apiVersion | Supported API versions. For details, see Table 16. | 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 dots per inch. This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: medium-scale dots per inch. This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: large-scale dots per inch. This value is applicable for devices with a DPI in the (160, 240] range.
**xldpi**: extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (240, 320] range.
**xxldpi**: extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI in the (320, 480] range.
**xxxldpi**: extra-extra-extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (480, 640] range.| Object array| Yes (initial value: left empty)| -| countryCode | Code of the country or region to which the application is to be distributed. For details, see ISO-3166-1. Enumerated definitions of multiple countries and regions are supported. This attribute is optional. The substring of the value consists of two uppercase letters and indicates the supported countries or regions.| Object array| Yes (initial value: left empty)| - -Table 17 Internal structure of the apiVersion attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| - -Table 18 Internal structure of the screenShape attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAP files can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| - -Table 19 Internal structure of the screenWindow attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Width and height of the screen. The value is in the "width * height" format, in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| - -Table 20 Internal structure of the screenDensity attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Pixel density of the screen, in dots per inch (dpi). | Array | Yes (initial value: left empty)| - -Table 21 Internal structure of the countryCode attribute - -| Attribute| Description | Data Type| Initial Value Allowed | -| -------- | ------------------------------------------------------------ | -------- | -------------------- | -| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Code of the country or region to which the application is to be distributed. | Array | Yes (initial value: left empty)| - -Example of the **distroFilter** attribute structure: - -Define the **distroFilter_config.json** file in **resources/base/profile** of the development view. (The file name can be defined by developers.) - -```json -"distroFilter": [ - { - "apiVersion": { - "policy": "include", - "value": [4, 5] - }, - "screenShape": { - "policy": "include", - "value": ["circle", "rect"] - }, - "screenWindow": { - "policy": "include", - "value": ["454*454", "466*466"] - } - } -] -``` - -Define the **metadata** information under **extensionAbilities** in the **module.json5** file as follows: - -```json -"extensionAbilities": [ - { - "name": "mySubscriber", - "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [{ - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:distroFilter_config", - }], - } -] -``` - -#### Internal Structure of the testRunner Attribute - -Table 22 Internal structure of the testRunner attribute - -| Attribute| Description | Data Type| Initial Value Allowed| -| -------- | ---------------------- | -------- | ---------- | -| name | Name of the test runner object.| String | No| -| srcPath | Path of the test runner code.| String | No| - -``` -"testRunner": { - "name": "myTestRUnnerName", - "srcPath": "etc/test/TestRunner.ts" -} -``` +- Information about the permissions required during application running. diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index 5548032d25184e05086648501f67d52b6caf6c65..fd04d4b1e0e2551d2b2885f0314b39204692fc40 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -4,7 +4,7 @@ This document is intended for novices at developing OpenHarmony applications. It ![en-us_image_0000001364254729](figures/en-us_image_0000001364254729.png) -Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and ability. +Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and application model. ## Basic Concepts @@ -16,29 +16,25 @@ OpenHarmony provides a UI development framework, known as ArkUI. ArkUI provides ArkUI comes with two development paradigms: ArkTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice. -| **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To**| **Intended Audience**| -| -------- | -------- | -------- | -------- | -------- | -| Declarative development paradigm| ArkTS| Data-driven| Applications involving technological sophistication and teamwork| Mobile application and system application developers| -| Web-like development paradigm| JavaScript| Data-driven| Applications and service widgets with simple UIs| Frontend web developers| +| **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To** | **Intended Audience** | +| ---------------- | ------------ | -------------- | -------------------------------- | -------------------------------------- | +| Declarative development paradigm | ArkTS | Data-driven | Applications involving technological sophistication and teamwork| Mobile application and system application developers| +| Web-like development paradigm | JavaScript | Data-driven | Applications and service widgets with simple UIs | Frontend web developers | For more details, see [UI Development](../ui/arkui-overview.md). +### Application Model -### Ability +The application model is the abstraction of capabilities required by OpenHarmony applications. It provides necessary components and running mechanisms for applications. With application models, you can develop applications based on a unified set of models, making application development simpler and more efficient. For details, see [Elements of the Application Model](../application-models/application-model-composition.md). -An ability is the abstraction of a functionality that an application can provide. An application may provide various capabilities, and so it can have multiple abilities. These abilities can be deployed together or independently from each other. +Along its evolution, OpenHarmony has provided two application models: -The ability framework model has two forms: +- Feature Ability (FA) model. This model is supported by OpenHarmony API version 7 and 8. It is no longer recommended. For details about development based on the FA model, see [FA Model Development Overview](../application-models/fa-model-development-overview.md). +- Stage model. This model is supported since OpenHarmony API version 9. It is recommended and will evolve for a long time. In this model, classes such as **AbilityStage** and **WindowStage** are provided as the stage of application components and windows. That's why it is named stage model. For details about development based on the stage model, see [Stage Model Development Overview](../application-models/fa-model-development-overview.md). -- **FA model**: applies to application development using API version 8 and earlier versions. For details, see [FA Model Overview](../ability/fa-brief.md). +For details about the differences between the FA model and stage model, see [Interpretation of the Application Model](../application-models/application-model-description.md). -- **Stage model**: introduced since API version 9. For details, see [Stage Model Overview](../ability/stage-brief.md). - -The project directory structure of the FA model is different from that of the stage model. The stage model only works with the ArkTS programming language. - -For details about the differences between the FA model and stage model, see [Ability Framework Overview](../ability/ability-brief.md). - -This document provides an ability with two pages. For more information about ability development, see [Ability Development](../ability/ability-brief.md). +To help you better understand the preceding basic concepts and application development process, **Getting Started** provides a development example that contains two pages in different programming languages and application models. ## Tool Preparation 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 f1280c77658fd048619ec34bd5b6736713465ad0..197765c3119690c7529469daa85a045d7c2853fd 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -40,7 +40,7 @@ - **src > main > ets > MainAbility > pages > index.ets**: the first page in the **pages** list, also referred to as the entry to the application. - **src > main > ets > MainAbility > app.ets**: ability lifecycle file. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). - - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md). + - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md). - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. @@ -129,7 +129,7 @@ > **NOTE** > > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. - - Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows: + - Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** file. The sample code is as follows: ```json { @@ -224,6 +224,9 @@ You can implement page redirection through the [page router](../reference/apis/j // Bind the onClick event to the Next button so that clicking the button redirects the user to the second page. .onClick(() => { router.push({ url: 'pages/second' }) + // In a project of API version 9, you can use the API below instead: + // router.pushUrl({ url: 'pages/second' }) + }) } .width('100%') 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 a37eb8d3da42490bfc4027ecadbf401f21982444..3bf9d124a666b0ad057310b21e1bf3b52cdf5505 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -38,7 +38,7 @@ - **src > main > ets > entryability**: entry to your application/service. - **src > main > ets > pages**: pages included in your application/service. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories). - - **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (Stage Model)](stage-structure.md). + - **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md). - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. @@ -216,7 +216,7 @@ You can implement page redirection through the [page router](../reference/apis/j .height('5%') // Bind the onClick event to the Next button so that clicking the button redirects the user to the second page. .onClick(() => { - router.push({ url: 'pages/Second' }) + router.pushUrl({ url: 'pages/Second' }) }) } .width('100%') 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 e0b43711caa931013ca581c40f588fd6f6cfe070..ad648638defddada7565cc34b2172c67d3050765 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -39,7 +39,7 @@ - **src > main > js > MainAbility > app.js**: ability lifecycle file. - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Limitations and Access](../ui/js-framework-resource-restriction.md). - - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md). + - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [Application Configuration File Overview (FA Model)](application-configuration-file-overview-fa.md). - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation. diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 80356f76fa74323530b24e2e503ea9dc09af1e81..85bb902ce576919aadc1422f1b8c35f7afd75718 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -1,6 +1,6 @@ # Development References - [SystemCapability](syscap.md) -- [SysCap List](syscap-list.md) +- [SystemCapability List](syscap-list.md) - [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) - [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md) - [JS Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 76d12ed38f81bdf496fd228f9cbea11eb8422510..600ec7d3a634e2671d798a6ebc73fe8096317a62 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -16,7 +16,7 @@ - [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) - [@ohos.app.ability.UIAbility](js-apis-app-ability-uiAbility.md) - [@ohos.app.form.FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) - - [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md) + - [@ohos.application.DataShareExtensionAbility](js-apis-application-dataShareExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - Stage Model (To Be Deprecated Soon) - [@ohos.application.Ability](js-apis-application-ability.md) @@ -125,15 +125,20 @@ - [continuationResult](js-apis-continuation-continuationResult.md) - Common Event and Notification + - [@ohos.commonEventManager (Recommended)](js-apis-commonEventManager.md) - [@ohos.events.emitter](js-apis-emitter.md) + - [@ohos.notificationManager (Recommended)](js-apis-notificationManager.md) + - [@ohos.notificationSubscribe (Recommended)](js-apis-notificationSubscribe.md) + - [@ohos.commonEvent (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.notification](js-apis-notification.md) - - application/[EventHub](js-apis-inner-application-eventHub.md) + - application + - [EventHub](js-apis-inner-application-eventHub.md) - Bundle Management - [@ohos.bundle.appControl](js-apis-appControl.md) - [@ohos.bundle.bundleManager](js-apis-bundleManager.md) - [@ohos.bundle.bundleMonitor](js-apis-bundleMonitor.md) - [@ohos.bundle.defaultAppManager](js-apis-defaultAppManager.md) - - [@ohos.bundle.distributedBundle](js-apis-distributedBundle.md) + - [@ohos.bundle.distributedBundleManager (distributedBundleManager)](js-apis-distributedBundleManager.md) - [@ohos.bundle.freeInstall](js-apis-freeInstall.md) - [@ohos.bundle.installer](js-apis-installer.md) - [@ohos.bundle.launcherBundleManager](js-apis-launcherBundleManager.md) @@ -154,6 +159,8 @@ - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) + - [@ohos.curves](js-apis-curve.md) + - [@ohos.matrix4](js-apis-matrix4.md) - [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.promptAction](js-apis-promptAction.md) - [@ohos.router](js-apis-router.md) @@ -187,37 +194,37 @@ - [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - Security - - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - - [@ohos.privacyManager](js-apis-privacyManager.md) - - [@ohos.security.cryptoFramework](js-apis-cryptoFramework.md) - - [@ohos.security.huks ](js-apis-huks.md) - - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - - [@system.cipher](js-apis-system-cipher.md) + - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) + - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) + - [@ohos.security.cert (Certificate)](js-apis-cert.md) + - [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md) + - [@ohos.security.huks (HUKS)](js-apis-huks.md) + - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) + - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - Data Management - - [@ohos.data.dataAbility ](js-apis-data-ability.md) - - [@ohos.data.dataShare](js-apis-data-dataShare.md) - - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - - [@ohos.data.preferences](js-apis-data-preferences.md) - - [@ohos.data.rdb](js-apis-data-rdb.md) - - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md) + - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) + - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) + - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md) + - [@ohos.data.dataShareResultSet (DataShare Result Set)](js-apis-data-DataShareResultSet.md) + - [@ohos.data.distributedDataObject (Distributed Data Object)](js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md) + - [@ohos.data.preferences (Preferences)](js-apis-data-preferences.md) + - [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md) + - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - data/rdb - [resultSet](js-apis-data-resultset.md) - File Management - - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - - [@ohos.data.fileAccess](js-apis-fileAccess.md) - - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - - [@ohos.fileio](js-apis-fileio.md) - - [@ohos.filemanagement.userFileManager](js-apis-userfilemanager.md) - - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - - [@ohos.securityLabel](js-apis-securityLabel.md) - - [@ohos.statfs](js-apis-statfs.md) - - [@ohos.storageStatistics](js-apis-storage-statistics.md) - - [@ohos.volumeManager](js-apis-volumemanager.md) + - [@ohos.data.fileAccess (User File Access and Management)](js-apis-fileAccess.md) + - [@ohos.fileExtensionInfo (User File Access and Management Attributes)](js-apis-fileExtensionInfo.md) + - [@ohos.fileio (File Management)](js-apis-fileio.md) + - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) + - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) + - [@ohos.securityLabel (Data Label)](js-apis-securityLabel.md) + - [@ohos.statfs (statfs)](js-apis-statfs.md) + - [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md) + - [@ohos.volumeManager (Volume Management)](js-apis-volumemanager.md) - Telephony Service - [@ohos.contact](js-apis-contact.md) - [@ohos.telephony.call](js-apis-call.md) @@ -251,6 +258,8 @@ - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md) + - [@ohos.accessibility.GesturePat](js-apis-accessibility-GesturePath.md) + - [@ohos.accessibility.GesturePoint](js-apis-accessibility-GesturePoint.md) - [@ohos.application.AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md) - [@ohos.faultLogger](js-apis-faultLogger.md) - [@ohos.hichecker](js-apis-hichecker.md) @@ -260,10 +269,11 @@ - [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.hiviewdfx.hiAppEvent](js-apis-hiviewdfx-hiappevent.md) - - [@ohos.inputMethod](js-apis-inputmethod.md) - - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.inputmethod](js-apis-inputmethod.md) + - [@ohos.inputmethodengine](js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) + - [@ohos.inputmethodsubtype](js-apis-inputmethod-subtype.md) - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) @@ -272,12 +282,15 @@ - [@ohos.web.webview](js-apis-webview.md) - [console](js-apis-logs.md) - [Timer](js-apis-timer.md) - - application/[AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) + - application + - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) - Device Management - [@ohos.batteryInfo ](js-apis-battery-info.md) + - [@ohos.batteryStatistics](js-apis-batteryStatistics.md) - [@ohos.brightness](js-apis-brightness.md) - [@ohos.deviceInfo](js-apis-device-info.md) - [@ohos.distributedHardware.deviceManager](js-apis-device-manager.md) + - [@ohos.geoLocationManager](js-apis-geoLocationManager.md) - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) - [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md) @@ -294,6 +307,7 @@ - [@ohos.sensor](js-apis-sensor.md) - [@ohos.settings](js-apis-settings.md) - [@ohos.stationary](js-apis-stationary.md) + - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -305,9 +319,13 @@ - [@ohos.account.osAccount](js-apis-osAccount.md) - Custom Management - [@ohos.configPolicy](js-apis-configPolicy.md) - - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.deviceInfo](js-apis-enterprise-deviceInfo.md) + - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.adminManager](js-apis-enterprise-adminManager.md) + - [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md) + - Language Base Class Library - - [@ohos.buffer](js-apis-buffer.md) + - [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.process](js-apis-process.md) - [@ohos.uri](js-apis-uri.md) @@ -338,10 +356,11 @@ - [@ohos.bundle.innerBundleManager](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace](js-apis-bytrace.md) - - [@ohos.data.storage](js-apis-data-storage.md) - - [@ohos.data.distributedData](js-apis-distributed-data.md) + - [@ohos.data.distributedData (Distributed Data Management)](js-apis-distributed-data.md) + - [@ohos.data.storage (Lightweight Data Storage)](js-apis-data-storage.md) + - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md) - [@ohos.distributedBundle](js-apis-Bundle-distributedBundle.md) - - [@ohos.document](js-apis-document.md) + - [@ohos.document (File Operation)](js-apis-document.md) - [@ohos.geolocation](js-apis-geolocation.md) - [@ohos.hiAppEvent](js-apis-hiappevent.md) - [@ohos.prompt](js-apis-prompt.md) diff --git a/en/application-dev/reference/apis/commonEvent-definitions.md b/en/application-dev/reference/apis/commonEvent-definitions.md new file mode 100644 index 0000000000000000000000000000000000000000..b7cfc06174bbd90c193b1e98d4aa5330597a4b8f --- /dev/null +++ b/en/application-dev/reference/apis/commonEvent-definitions.md @@ -0,0 +1,904 @@ +# System Common Events + +This document provides indexes for system common events defined in OpenHarmony. +For details about the definition of a system common event, see [Support in @ohos.commonEvent (Common Event)](./js-apis-commonEvent.md#support). + +**System capability**: SystemCapability.Notification.CommonEvent + +## COMMON_EVENT_BOOT_COMPLETED +Indicates that the user has finished booting and the system has been loaded. +- Value: **usual.event.BOOT_COMPLETED** +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + +## COMMON_EVENT_LOCKED_BOOT_COMPLETED +(Reserved, not supported yet) Indicates that the user has finished booting and the system has been loaded but the screen is still locked. +- Value: **usual.event.LOCKED_BOOT_COMPLETED** +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + +## COMMON_EVENT_SHUTDOWN +Indicates that the device is being shut down and the final shutdown will proceed. +- Value: **usual.event.SHUTDOWN** +- Required subscriber permissions: none + +## COMMON_EVENT_BATTERY_CHANGED +Indicates that the charging state, level, and other information about the battery have changed. +- Value: **usual.event.BATTERY_CHANGED** +- Required subscriber permissions: none + +## COMMON_EVENT_BATTERY_LOW +Indicates that the battery level is low. +- Value: **usual.event.BATTERY_LOW** +- Required subscriber permissions: none + +## COMMON_EVENT_BATTERY_OKAY +Indicates that the battery level is normal. +- Value: **usual.event.BATTERY_OKAY** +- Required subscriber permissions: none + +## COMMON_EVENT_POWER_CONNECTED +Indicates that the device is connected to an external power supply. +- Value: **usual.event.POWER_CONNECTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_POWER_DISCONNECTED +Indicates that the device is disconnected from the external power supply. +- Value: **usual.event.POWER_DISCONNECTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_SCREEN_OFF +Indicates that the device screen is off and the device is in sleep mode. +- Value: **usual.event.SCREEN_OFF** +- Required subscriber permissions: none + + +## COMMON_EVENT_SCREEN_ON +Indicates that the device screen is on and the device is in interactive state. +- Value: **usual.event.SCREEN_ON** +- Required subscriber permissions: none + + +## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ +Indicates that the device's thermal level has changed. +- Value: **usual.event.THERMAL_LEVEL_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_PRESENT +(Reserved, not supported yet) Indicates that the user unlocks the device. +- Value: **usual.event.USER_PRESENT** +- Required subscriber permissions: none + + +## COMMON_EVENT_TIME_TICK +Indicates that the system time has changed as time ticks by. +- Value: **usual.event.TIME_TICK** +- Required subscriber permissions: none + + +## COMMON_EVENT_TIME_CHANGED +Indicates that the system time is set. +- Value: **usual.event.TIME_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_DATE_CHANGED +(Reserved, not supported yet) Indicates that the system date has changed. +- Value: **usual.event.DATE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_TIMEZONE_CHANGED +Indicates that the system time zone has changed. +- Value: **usual.event.TIMEZONE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_CLOSE_SYSTEM_DIALOGS +(Reserved, not supported yet) Indicates that the user closes a temporary system dialog box. +- Value: **usual.event.CLOSE_SYSTEM_DIALOGS** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_ADDED +Indicates that a new application package has been installed on the device. +- Value: **usual.event.PACKAGE_ADDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_REPLACED +(Reserved, not supported yet) Indicates that a later version of an installed application package has replaced the previous one on the device. +- Value: **usual.event.PACKAGE_REPLACED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MY_PACKAGE_REPLACED +(Reserved, not supported yet) Indicates that a later version of your application package has replaced the previous one. +- Value: **usual.event.MY_PACKAGE_REPLACED** +- Required subscriber permissions: none + +## COMMON_EVENT_PACKAGE_REMOVED +Indicates that an installed application has been uninstalled from the device with the application data retained. +- Value: **usual.event.PACKAGE_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_BUNDLE_REMOVED +(Reserved, not supported yet) Indicates that an installed bundle has been uninstalled from the device with the application data retained. +- Value: **usual.event.BUNDLE_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_FULLY_REMOVED +(Reserved, not supported yet) Indicates that an installed application, including both the application data and code, has been completely uninstalled from the device. +- Value: **usual.event.PACKAGE_FULLY_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_CHANGED +Indicates that an application package has been changed (for example, an ability in the package has been enabled or disabled). +- Value: **usual.event.PACKAGE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_RESTARTED +Indicates that the user closed all processes of the application and restarted the application. +- Value: **usual.event.PACKAGE_RESTARTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_DATA_CLEARED +Indicates that the user cleared the application package data. +- Value: **usual.event.PACKAGE_DATA_CLEARED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ +Indicates that the user cleared the application package cache. +- Value: **usual.event.PACKAGE_CACHE_CLEARED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGES_SUSPENDED +(Reserved, not supported yet) Indicates that application HAP files are suspended. +- Value: **usual.event.PACKAGES_SUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGES_UNSUSPENDED +(Reserved, not supported yet) Indicates that application HAP files are not suspended (restored from the suspended state). +- Value: **usual.event.PACKAGES_UNSUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MY_PACKAGE_SUSPENDED +Indicates that an application HAP file is suspended. +- Value: **usual.event.MY_PACKAGE_SUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MY_PACKAGE_UNSUSPENDED +Indicates that an application HAP file is not suspended. +- Value: **usual.event.MY_PACKAGE_UNSUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_UID_REMOVED +(Reserved, not supported yet) Indicates that a user ID has been removed from the system. +- Value: **usual.event.UID_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_FIRST_LAUNCH +(Reserved, not supported yet) Indicates that an installed application is started for the first time. +- Value: **usual.event.PACKAGE_FIRST_LAUNCH** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION +(Reserved, not supported yet) Indicates that an application requires system verification. +- Value: **usual.event.PACKAGE_NEEDS_VERIFICATION** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_VERIFIED +(Reserved, not supported yet) Indicates that an application has been verified by the system. +- Value: **usual.event.PACKAGE_VERIFIED** +- Required subscriber permissions: none + + +## COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE +(Reserved, not supported yet) Indicates that applications installed on the external storage are available for the system. +- Value: **usual.event.EXTERNAL_APPLICATIONS_AVAILABLE** +- Required subscriber permissions: none + + +## COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE +(Reserved, not supported yet) Indicates that applications installed on the external storage are not available for the system. +- Value: **usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE** +- Required subscriber permissions: none + + +## COMMON_EVENT_CONFIGURATION_CHANGED +(Reserved, not supported yet) Indicates that the device state (for example, orientation and locale) has changed. +- Value: **usual.event.CONFIGURATION_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_LOCALE_CHANGED +(Reserved, not supported yet) Indicates that the device locale has changed. +- Value: **usual.event.LOCALE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MANAGE_PACKAGE_STORAGE +(Reserved, not supported yet) Indicates that the device storage is insufficient. +- Value: **usual.event.MANAGE_PACKAGE_STORAGE** +- Required subscriber permissions: none + + +## COMMON_EVENT_DRIVE_MODE +(Reserved, not supported yet) Indicates that the system is in driving mode. +- Value: **common.event.DRIVE_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_HOME_MODE +(Reserved, not supported yet) Indicates that the system is in home mode. +- Value: **common.event.HOME_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_OFFICE_MODE +(Reserved, not supported yet) Indicates that the system is in office mode. +- Value: **common.event.OFFICE_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_STARTED +(Reserved, not supported yet) Indicates that the user has been started. +- Value: **usual.event.USER_STARTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_BACKGROUND +(Reserved, not supported yet) Indicates that the user has been brought to the background. +- Value: **usual.event.USER_BACKGROUND** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_FOREGROUND +(Reserved, not supported yet) Indicates that the user has been brought to the foreground. +- Value: **usual.event.USER_FOREGROUND** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_SWITCHED +Indicates that user switching is in progress. +- Value: **usual.event.USER_SWITCHED** +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_STARTING +(Reserved, not supported yet) Indicates that the user is being started. +- Value: **usual.event.USER_STARTING** +- Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_UNLOCKED +(Reserved, not supported yet) Indicates that the credential-encrypted storage has been unlocked for the current user after the device is restarted. +- Value: **usual.event.USER_UNLOCKED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_STOPPING +(Reserved, not supported yet) Indicates that the user is going to be stopped. +- Value: **usual.event.USER_STOPPING** +- Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_STOPPED +(Reserved, not supported yet) Indicates that the user has been stopped. +- Value: **usual.event.USER_STOPPED** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_POWER_STATE +Indicates that the Wi-Fi state has changed, for example, enabled or disabled. +- Value: **usual.event.wifi.POWER_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_SCAN_FINISHED +Indicates that the Wi-Fi access point has been detected and proven to be available. +- Value: **usual.event.wifi.SCAN_FINISHED** +- Required subscriber permissions: ohos.permission.LOCATION + + +## COMMON_EVENT_WIFI_RSSI_VALUE +Indicates that the Wi-Fi signal strength (RSSI) has changed. +- Value: **usual.event.wifi.RSSI_VALUE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_CONN_STATE +Indicates that the Wi-Fi connection state has changed. +- Value: **usual.event.wifi.CONN_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_HOTSPOT_STATE +Indicates that the Wi-Fi hotspot state has changed, for example, enabled or disabled. +- Value: **usual.event.wifi.HOTSPOT_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_AP_STA_JOIN +Indicates that a client has joined the Wi-Fi hotspot of the current device. +- Value: **usual.event.wifi.WIFI_HS_STA_JOIN** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_AP_STA_LEAVE +Indicates that a client has disconnected from the Wi-Fi hotspot of the current device. +- Value: **usual.event.wifi.WIFI_HS_STA_LEAVE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE +Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. +- Value: **usual.event.wifi.mplink.STATE_CHANGE** +- Required subscriber permissions: ohos.permission.MPLINK_CHANGE_STATE + + +## COMMON_EVENT_WIFI_P2P_CONN_STATE +Indicates that the Wi-Fi P2P connection state has changed. +- Value: **usual.event.wifi.p2p.CONN_STATE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + + +## COMMON_EVENT_WIFI_P2P_STATE_CHANGED +Indicates that the Wi-Fi P2P state has changed, for example, enabled or disabled. +- Value: **usual.event.wifi.p2p.STATE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED +Indicates that the state of the Wi-Fi P2P peer device has changed. +- Value: **usual.event.wifi.p2p.DEVICES_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED +Indicates that the Wi-Fi P2P discovery state has changed. +- Value: **usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED +Indicates that the state of the Wi-Fi P2P local device has changed. +- Value: **usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED +Indicates that the Wi-Fi P2P group information has changed. +- Value: **usual.event.wifi.p2p.GROUP_STATE_CHANGED** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates the connection state of Bluetooth handsfree communication. +- Value: **usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE +(Reserved, not supported yet) Indicates that the device connected through Bluetooth handsfree is active. +- Value: **usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE +(Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates the connection state of Bluetooth A2DP. +- Value: **usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE +(Reserved, not supported yet) Indicates that the device connected using Bluetooth A2DP is active. +- Value: **usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE +(Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates that the AVRCP connection state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE +(Reserved, not supported yet) Indicates that the audio codec state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED +(Reserved, not supported yet) Indicates that a remote Bluetooth device is discovered. +- Value: **usual.event.bluetooth.remotedevice.DISCOVERED** +- Required subscriber permissions: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE +(Reserved, not supported yet) Indicates that the Bluetooth class of a remote Bluetooth device has changed. +- Value: **usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED +(Reserved, not supported yet) Indicates that a low-ACL connection with a remote Bluetooth device has been established. +- Value: **usual.event.bluetooth.remotedevice.ACL_CONNECTED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED +(Reserved, not supported yet) Indicates that the low-ACL connection with a remote Bluetooth device has been terminated. +- Value: **usual.event.bluetooth.remotedevice.ACL_DISCONNECTED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE +(Reserved, not supported yet) Indicates that the friendly name of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. +- Value: **usual.event.bluetooth.remotedevice.NAME_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE +(Reserved, not supported yet) Indicates that the connection state with a remote Bluetooth device has changed. +- Value: **usual.event.bluetooth.remotedevice.PAIR_STATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE +(Reserved, not supported yet) Indicates that the battery level of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. +- Value: **usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT +(Reserved, not supported yet) Indicates the SDP state of a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.SDP_RESULT** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE +(Reserved, not supported yet) Indicates the UUID connection state with a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.UUID_VALUE** +- Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ +(Reserved, not supported yet) Indicates the pairing request from a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.PAIRING_REQ** +- Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL +(Reserved, not supported yet) Indicates that Bluetooth pairing has been canceled. +- Value: **usual.event.bluetooth.remotedevice.PAIRING_CANCEL** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ +(Reserved, not supported yet) Indicates the connection request from a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.CONNECT_REQ** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY +(Reserved, not supported yet) Indicates the response to the connection request from a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.CONNECT_REPLY** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL +(Reserved, not supported yet) Indicates that the connection to a remote Bluetooth device has been canceled. +- Value: **usual.event.bluetooth.remotedevice.CONNECT_CANCEL** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates that the connection state with a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE +(Reserved, not supported yet) Indicates that the audio state of a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT +(Reserved, not supported yet) Indicates that the audio gateway state of a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE +(Reserved, not supported yet) Indicates that the calling state of a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE +(Reserved, not supported yet) Indicates that the state of a Bluetooth adapter has changed, for example, Bluetooth has been enabled or disabled. +- Value: **usual.event.bluetooth.host.STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE +(Reserved, not supported yet) Indicates the request for the user to allow Bluetooth device scanning. +- Value: **usual.event.bluetooth.host.REQ_DISCOVERABLE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE +(Reserved, not supported yet) Indicates the request for the user to enable Bluetooth. +- Value: **usual.event.bluetooth.host.REQ_ENABLE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE +(Reserved, not supported yet) Indicates the request for the user to disable Bluetooth. +- Value: **usual.event.bluetooth.host.REQ_DISABLE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE +(Reserved, not supported yet) Indicates that the Bluetooth scanning mode of the device has changed. +- Value: **usual.event.bluetooth.host.SCAN_MODE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED +(Reserved, not supported yet) Indicates that Bluetooth scanning has been started on the device. +- Value: **usual.event.bluetooth.host.DISCOVERY_STARTED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED +(Reserved, not supported yet) Indicates that Bluetooth scanning is finished on the device. +- Value: **usual.event.bluetooth.host.DISCOVERY_FINISHED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE +(Reserved, not supported yet) Indicates that the Bluetooth adapter name of the device has changed. +- Value: **usual.event.bluetooth.host.NAME_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP Sink has changed. +- Value: **usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE +(Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP Sink has changed. +- Value: **usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE +(Reserved, not supported yet) Indicates that the audio state of Bluetooth A2DP Sink has changed. +- Value: **usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED +(Reserved, not supported yet) Indicates that the state of the device NFC adapter has changed. +- Value: **usual.event.nfc.action.ADAPTER_STATE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED +(Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the enabled state. +- Value: **usual.event.nfc.action.RF_FIELD_ON_DETECTED** +- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS + + +## COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED +(Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the disabled state. +- Value: **usual.event.nfc.action.RF_FIELD_OFF_DETECTED** +- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS + + +## COMMON_EVENT_DISCHARGING +Indicates that the system stops charging the battery. +- Value: **usual.event.DISCHARGING** +- Required subscriber permissions: none + + +## COMMON_EVENT_CHARGING +Indicates that the system starts charging the battery. +- Value: **usual.event.CHARGING** +- Required subscriber permissions: none + + +## COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED +(Reserved, not supported yet) Indicates that the system idle mode has changed. +- Value: **usual.event.DEVICE_IDLE_MODE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_POWER_SAVE_MODE_CHANGED +Indicates that the system power saving mode has changed. +- Value: **usual.event.POWER_SAVE_MODE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_ADDED +Indicates that a user has been added to the system. +- Value: **usual.event.USER_ADDED** +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_REMOVED +Indicates that a user has been removed from the system. +- Value: **usual.event.USER_REMOVED** +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + + +## COMMON_EVENT_ABILITY_ADDED +(Reserved, not supported yet) Indicates that an ability has been added. +- Value: **usual.event.ABILITY_ADDED** +- Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + + +## COMMON_EVENT_ABILITY_REMOVED +(Reserved, not supported yet) Indicates that an ability has been removed. +- Value: **usual.event.ABILITY_REMOVED** +- Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + + +## COMMON_EVENT_ABILITY_UPDATED +(Reserved, not supported yet) Indicates that an ability has been updated. +- Value: **usual.event.ABILITY_UPDATED** +- Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + + +## COMMON_EVENT_LOCATION_MODE_STATE_CHANGED +(Reserved, not supported yet) Indicates that the location mode of the system has changed. +- Value: **usual.event.location.MODE_STATE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_SLEEP +(Reserved, not supported yet) Indicates that the in-vehicle infotainment (IVI) system is in sleep mode. +- Value: **common.event.IVI_SLEEP** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_PAUSE +(Reserved, not supported yet) Indicates that the IVI system as entered sleep mode and instructs the playing application to stop playback. +- Value: **common.event.IVI_PAUSE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_STANDBY +(Reserved, not supported yet) Requests a third-party application in the IVI system to pause the current work. +- Value: **common.event.IVI_STANDBY** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_LASTMODE_SAVE +(Reserved, not supported yet) Requests a third-party application in the IVI system to save its last mode. +- Value: **common.event.IVI_LASTMODE_SAVE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_VOLTAGE_ABNORMAL +(Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is abnormal. +- Value: **common.event.IVI_VOLTAGE_ABNORMAL** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_HIGH_TEMPERATURE +(Reserved, not supported yet) Indicates that the temperature of the IVI system is high. +- Value: **common.event.IVI_HIGH_TEMPERATURE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_EXTREME_TEMPERATURE +(Reserved, not supported yet) Indicates that the temperature of the IVI system is extremely high. +- Value: **common.event.IVI_EXTREME_TEMPERATURE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL +(Reserved, not supported yet) Indicates that the IVI system is at an extreme temperature. +- Value: **common.event.IVI_TEMPERATURE_ABNORMAL** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_VOLTAGE_RECOVERY +(Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is restored to normal. +- Value: **common.event.IVI_VOLTAGE_RECOVERY** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_TEMPERATURE_RECOVERY +(Reserved, not supported yet) Indicates that the temperature of the IVI system is restored to normal. +- Value: **common.event.IVI_TEMPERATURE_RECOVERY** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_ACTIVE +(Reserved, not supported yet) Indicates that the battery service of the IVI system is active. +- Value: **common.event.IVI_ACTIVE** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_STATE9+ +Indicates that the USB device state has changed. +- Value: **usual.event.hardware.usb.action.USB_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_PORT_CHANGED9+ +Indicates that the USB port state of the device has changed. +- Value: **usual.event.hardware.usb.action.USB_PORT_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_DEVICE_ATTACHED +Indicates that a USB device has been attached to the device functioning as a USB host. +- Value: **usual.event.hardware.usb.action.USB_DEVICE_ATTACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_DEVICE_DETACHED +Indicates that a USB device has been detached from the device functioning as a USB host. +- Value: **usual.event.hardware.usb.action.USB_DEVICE_DETACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_ACCESSORY_ATTACHED +(Reserved, not supported yet) Indicates that a USB accessory was attached. +- Value: **usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_ACCESSORY_DETACHED +(Reserved, not supported yet) Indicates that a USB accessory was detached. +- Value: **usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_DISK_REMOVED +(Reserved, not supported yet) Indicates that an external storage device was removed. +- Value: **usual.event.data.DISK_REMOVED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_UNMOUNTED +(Reserved, not supported yet) Indicates that an external storage device was unmounted. +- Value: **usual.event.data.DISK_UNMOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_MOUNTED +(Reserved, not supported yet) Indicates that an external storage device was mounted. +- Value: **usual.event.data.DISK_MOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_BAD_REMOVAL +(Reserved, not supported yet) Indicates that an external storage device was removed without being unmounted. +- Value: usual.event.data.DISK_BAD_REMOVAL +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_UNMOUNTABLE +(Reserved, not supported yet) Indicates that an external storage device is unmountable when the card is inserted. +- Value: **usual.event.data.DISK_UNMOUNTABLE** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_EJECT +(Reserved, not supported yet) Indicates that an external storage device was ejected (at the software level). +- Value: **usual.event.data.DISK_EJECT** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_REMOVED9+ +Indicates that an external storage device was removed. +- Value: **usual.event.data.VOLUME_REMOVED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_UNMOUNTED9+ +Indicates that an external storage device was unmounted. +- Value: **usual.event.data.VOLUME_UNMOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_MOUNTED9+ +Indicates that an external storage device was mounted. +- Value: **usual.event.data.VOLUME_MOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ +Indicates that an external storage device was removed without being unmounted. +- Value: **usual.event.data.VOLUME_BAD_REMOVAL** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_EJECT9+ +Indicates that an external storage device was ejected (at the software level). +- Value: usual.event.data.VOLUME_EJECT +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED +(Reserved, not supported yet) Indicates that the account visibility changed. +- Value: **usual.event.data.VISIBLE_ACCOUNTS_UPDATED** +- Required subscriber permissions: ohos.permission.GET_APP_ACCOUNTS + + +## COMMON_EVENT_ACCOUNT_DELETED +(Reserved, not supported yet) Indicates that an account was deleted. +- Value: **usual.event.data.ACCOUNT_DELETED** +- Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + + +## COMMON_EVENT_FOUNDATION_READY +(Reserved, not supported yet) Indicates that the foundation is ready. +- Value: **usual.event.data.FOUNDATION_READY** +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + + +## COMMON_EVENT_AIRPLANE_MODE_CHANGED +Indicates that the airplane mode of the device has changed. +- Value: **usual.event.AIRPLANE_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_SPLIT_SCREEN8+ +Indicates that the screen has been split. +- Value: **usual.event.SPLIT_SCREEN** +- Required subscriber permissions: none + + +## COMMON_EVENT_SLOT_CHANGE9+ +Indicates that the notification slot has been updated. +- Value: **usual.event.SLOT_CHANGE** +- Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER + + +## COMMON_EVENT_SPN_INFO_CHANGED9+ +Indicates that the SPN displayed has been updated. +- Value: **usual.event.SPN_INFO_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ +Indicates the result of applying a quick fix to the application. +- Value: **usual.event.QUICK_FIX_APPLY_RESULT** +- Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/commonEventManager-definitions.md b/en/application-dev/reference/apis/commonEventManager-definitions.md new file mode 100644 index 0000000000000000000000000000000000000000..9c1d2081d8a631b8f5b963924d66dc5aa688eb99 --- /dev/null +++ b/en/application-dev/reference/apis/commonEventManager-definitions.md @@ -0,0 +1,923 @@ +# System Common Events + +This document provides indexes for system common events defined in OpenHarmony. +For details about the definition of a system common event, see [Support in @ohos.commonEventManager (Common Event)](./js-apis-commonEventManager.md#support). + +**System capability**: SystemCapability.Notification.CommonEvent + +## COMMON_EVENT_BOOT_COMPLETED +Indicates that the user has finished booting and the system has been loaded. +- Value: **usual.event.BOOT_COMPLETED** +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + +## COMMON_EVENT_LOCKED_BOOT_COMPLETED +(Reserved, not supported yet) Indicates that the user has finished booting and the system has been loaded but the screen is still locked. +- Value: **usual.event.LOCKED_BOOT_COMPLETED** +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + +## COMMON_EVENT_SHUTDOWN +Indicates that the device is being shut down and the final shutdown will proceed. +- Value: **usual.event.SHUTDOWN** +- Required subscriber permissions: none + +## COMMON_EVENT_BATTERY_CHANGED +Indicates that the charging state, level, and other information about the battery have changed. +- Value: **usual.event.BATTERY_CHANGED** +- Required subscriber permissions: none + +## COMMON_EVENT_BATTERY_LOW +Indicates that the battery level is low. +- Value: **usual.event.BATTERY_LOW** +- Required subscriber permissions: none + +## COMMON_EVENT_BATTERY_OKAY +Indicates that the battery level is normal. +- Value: **usual.event.BATTERY_OKAY** +- Required subscriber permissions: none + +## COMMON_EVENT_POWER_CONNECTED +Indicates that the device is connected to an external power supply. +- Value: **usual.event.POWER_CONNECTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_POWER_DISCONNECTED +Indicates that the device is disconnected from the external power supply. +- Value: **usual.event.POWER_DISCONNECTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_SCREEN_OFF +Indicates that the device screen is off and the device is in sleep mode. +- Value: **usual.event.SCREEN_OFF** +- Required subscriber permissions: none + + +## COMMON_EVENT_SCREEN_ON +Indicates that the device screen is on and the device is in interactive state. +- Value: **usual.event.SCREEN_ON** +- Required subscriber permissions: none + + +## COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ +Indicates that the device's thermal level has changed. +- Value: **usual.event.THERMAL_LEVEL_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_PRESENT +(Reserved, not supported yet) Indicates that the user unlocks the device. +- Value: **usual.event.USER_PRESENT** +- Required subscriber permissions: none + + +## COMMON_EVENT_TIME_TICK +Indicates that the system time has changed as time ticks by. +- Value: **usual.event.TIME_TICK** +- Required subscriber permissions: none + + +## COMMON_EVENT_TIME_CHANGED +Indicates that the system time is set. +- Value: **usual.event.TIME_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_DATE_CHANGED +(Reserved, not supported yet) Indicates that the system date has changed. +- Value: **usual.event.DATE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_TIMEZONE_CHANGED +Indicates that the system time zone has changed. +- Value: **usual.event.TIMEZONE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_CLOSE_SYSTEM_DIALOGS +(Reserved, not supported yet) Indicates that the user closes a temporary system dialog box. +- Value: **usual.event.CLOSE_SYSTEM_DIALOGS** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_ADDED +Indicates that a new application package has been installed on the device. +- Value: **usual.event.PACKAGE_ADDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_REPLACED +(Reserved, not supported yet) Indicates that a later version of an installed application package has replaced the previous one on the device. +- Value: **usual.event.PACKAGE_REPLACED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MY_PACKAGE_REPLACED +(Reserved, not supported yet) Indicates that a later version of your application package has replaced the previous one. +- Value: **usual.event.MY_PACKAGE_REPLACED** +- Required subscriber permissions: none + +## COMMON_EVENT_PACKAGE_REMOVED +Indicates that an installed application has been uninstalled from the device with the application data retained. +- Value: **usual.event.PACKAGE_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_BUNDLE_REMOVED +(Reserved, not supported yet) Indicates that an installed bundle has been uninstalled from the device with the application data retained. +- Value: **usual.event.BUNDLE_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_FULLY_REMOVED +(Reserved, not supported yet) Indicates that an installed application, including both the application data and code, has been completely uninstalled from the device. +- Value: **usual.event.PACKAGE_FULLY_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_CHANGED +Indicates that an application package has been changed (for example, an ability in the package has been enabled or disabled). +- Value: **usual.event.PACKAGE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_RESTARTED +Indicates that the user closed all processes of the application and restarted the application. +- Value: **usual.event.PACKAGE_RESTARTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_DATA_CLEARED +Indicates that the user cleared the application package data. +- Value: **usual.event.PACKAGE_DATA_CLEARED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ +Indicates that the user cleared the application package cache. +- Value: **usual.event.PACKAGE_CACHE_CLEARED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGES_SUSPENDED +(Reserved, not supported yet) Indicates that application HAP files are suspended. +- Value: **usual.event.PACKAGES_SUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGES_UNSUSPENDED +(Reserved, not supported yet) Indicates that application HAP files are not suspended (restored from the suspended state). +- Value: **usual.event.PACKAGES_UNSUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MY_PACKAGE_SUSPENDED +Indicates that an application HAP file is suspended. +- Value: **usual.event.MY_PACKAGE_SUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MY_PACKAGE_UNSUSPENDED +Indicates that an application HAP file is not suspended. +- Value: **usual.event.MY_PACKAGE_UNSUSPENDED** +- Required subscriber permissions: none + + +## COMMON_EVENT_UID_REMOVED +(Reserved, not supported yet) Indicates that a user ID has been removed from the system. +- Value: **usual.event.UID_REMOVED** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_FIRST_LAUNCH +(Reserved, not supported yet) Indicates that an installed application is started for the first time. +- Value: **usual.event.PACKAGE_FIRST_LAUNCH** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION +(Reserved, not supported yet) Indicates that an application requires system verification. +- Value: **usual.event.PACKAGE_NEEDS_VERIFICATION** +- Required subscriber permissions: none + + +## COMMON_EVENT_PACKAGE_VERIFIED +(Reserved, not supported yet) Indicates that an application has been verified by the system. +- Value: **usual.event.PACKAGE_VERIFIED** +- Required subscriber permissions: none + + +## COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE +(Reserved, not supported yet) Indicates that applications installed on the external storage are available for the system. +- Value: **usual.event.EXTERNAL_APPLICATIONS_AVAILABLE** +- Required subscriber permissions: none + + +## COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE +(Reserved, not supported yet) Indicates that applications installed on the external storage are not available for the system. +- Value: **usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE** +- Required subscriber permissions: none + + +## COMMON_EVENT_CONFIGURATION_CHANGED +(Reserved, not supported yet) Indicates that the device state (for example, orientation and locale) has changed. +- Value: **usual.event.CONFIGURATION_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_LOCALE_CHANGED +(Reserved, not supported yet) Indicates that the device locale has changed. +- Value: **usual.event.LOCALE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_MANAGE_PACKAGE_STORAGE +(Reserved, not supported yet) Indicates that the device storage is insufficient. +- Value: **usual.event.MANAGE_PACKAGE_STORAGE** +- Required subscriber permissions: none + + +## COMMON_EVENT_DRIVE_MODE +(Reserved, not supported yet) Indicates that the system is in driving mode. +- Value: **common.event.DRIVE_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_HOME_MODE +(Reserved, not supported yet) Indicates that the system is in home mode. +- Value: **common.event.HOME_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_OFFICE_MODE +(Reserved, not supported yet) Indicates that the system is in office mode. +- Value: **common.event.OFFICE_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_STARTED +(Reserved, not supported yet) Indicates that the user has been started. +- Value: **usual.event.USER_STARTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_BACKGROUND +(Reserved, not supported yet) Indicates that the user has been brought to the background. +- Value: **usual.event.USER_BACKGROUND** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_FOREGROUND +(Reserved, not supported yet) Indicates that the user has been brought to the foreground. +- Value: **usual.event.USER_FOREGROUND** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_SWITCHED +Indicates that user switching is in progress. +- Value: **usual.event.USER_SWITCHED** +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_STARTING +(Reserved, not supported yet) Indicates that the user is being started. +- Value: **usual.event.USER_STARTING** +- Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_UNLOCKED +(Reserved, not supported yet) Indicates that the credential-encrypted storage has been unlocked for the current user after the device is restarted. +- Value: **usual.event.USER_UNLOCKED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_STOPPING +(Reserved, not supported yet) Indicates that the user is going to be stopped. +- Value: **usual.event.USER_STOPPING** +- Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_STOPPED +(Reserved, not supported yet) Indicates that the user has been stopped. +- Value: **usual.event.USER_STOPPED** +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN +(Reserved, not supported yet) Indicates a successful login to a distributed account. +- Value: **usual.event.DISTRIBUTED_ACCOUNT_LOGIN** +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT +(Reserved, not supported yet) Indicates a successful logout of a distributed account. +- Value: **usual.event.DISTRIBUTED_ACCOUNT_LOGOUT** +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID +(Reserved, not supported yet) Indicates the token of a distributed account is invalid. +- Value: **usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID** +- Required subscriber permissions: none + +## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF +(Reserved, not supported yet) Indicates that a distributed account is deregistered. +- Value: **usual.event.DISTRIBUTED_ACCOUNT_LOGOFF** +- Required subscriber permissions: none + +## COMMON_EVENT_WIFI_POWER_STATE +Indicates that the Wi-Fi state has changed, for example, enabled or disabled. +- Value: **usual.event.wifi.POWER_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_SCAN_FINISHED +Indicates that the Wi-Fi access point has been detected and proven to be available. +- Value: **usual.event.wifi.SCAN_FINISHED** +- Required subscriber permissions: ohos.permission.LOCATION + + +## COMMON_EVENT_WIFI_RSSI_VALUE +Indicates that the Wi-Fi signal strength (RSSI) has changed. +- Value: **usual.event.wifi.RSSI_VALUE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_CONN_STATE +Indicates that the Wi-Fi connection state has changed. +- Value: **usual.event.wifi.CONN_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_HOTSPOT_STATE +Indicates that the Wi-Fi hotspot state has changed, for example, enabled or disabled. +- Value: **usual.event.wifi.HOTSPOT_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_WIFI_AP_STA_JOIN +Indicates that a client has joined the Wi-Fi hotspot of the current device. +- Value: **usual.event.wifi.WIFI_HS_STA_JOIN** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_AP_STA_LEAVE +Indicates that a client has disconnected from the Wi-Fi hotspot of the current device. +- Value: **usual.event.wifi.WIFI_HS_STA_LEAVE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE +Indicates that the state of MPLINK (an enhanced Wi-Fi feature) has changed. +- Value: **usual.event.wifi.mplink.STATE_CHANGE** +- Required subscriber permissions: ohos.permission.MPLINK_CHANGE_STATE + + +## COMMON_EVENT_WIFI_P2P_CONN_STATE +Indicates that the Wi-Fi P2P connection state has changed. +- Value: **usual.event.wifi.p2p.CONN_STATE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + + +## COMMON_EVENT_WIFI_P2P_STATE_CHANGED +Indicates that the Wi-Fi P2P state has changed, for example, enabled or disabled. +- Value: **usual.event.wifi.p2p.STATE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED +Indicates that the state of the Wi-Fi P2P peer device has changed. +- Value: **usual.event.wifi.p2p.DEVICES_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED +Indicates that the Wi-Fi P2P discovery state has changed. +- Value: **usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED +Indicates that the state of the Wi-Fi P2P local device has changed. +- Value: **usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED +Indicates that the Wi-Fi P2P group information has changed. +- Value: **usual.event.wifi.p2p.GROUP_STATE_CHANGED** +- Required subscriber permissions: ohos.permission.GET_WIFI_INFO + + +## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates the connection state of Bluetooth handsfree communication. +- Value: **usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE +(Reserved, not supported yet) Indicates that the device connected through Bluetooth handsfree is active. +- Value: **usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE +(Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates the connection state of Bluetooth A2DP. +- Value: **usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE +(Reserved, not supported yet) Indicates that the device connected using Bluetooth A2DP is active. +- Value: **usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE +(Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates that the AVRCP connection state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE +(Reserved, not supported yet) Indicates that the audio codec state of Bluetooth A2DP has changed. +- Value: **usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED +(Reserved, not supported yet) Indicates that a remote Bluetooth device is discovered. +- Value: **usual.event.bluetooth.remotedevice.DISCOVERED** +- Required subscriber permissions: ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE +(Reserved, not supported yet) Indicates that the Bluetooth class of a remote Bluetooth device has changed. +- Value: **usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED +(Reserved, not supported yet) Indicates that a low-ACL connection with a remote Bluetooth device has been established. +- Value: **usual.event.bluetooth.remotedevice.ACL_CONNECTED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED +(Reserved, not supported yet) Indicates that the low-ACL connection with a remote Bluetooth device has been terminated. +- Value: **usual.event.bluetooth.remotedevice.ACL_DISCONNECTED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE +(Reserved, not supported yet) Indicates that the friendly name of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. +- Value: **usual.event.bluetooth.remotedevice.NAME_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE +(Reserved, not supported yet) Indicates that the connection state with a remote Bluetooth device has changed. +- Value: **usual.event.bluetooth.remotedevice.PAIR_STATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE +(Reserved, not supported yet) Indicates that the battery level of a remote Bluetooth device is retrieved for the first time or has changed since the last retrieval. +- Value: **usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT +(Reserved, not supported yet) Indicates the SDP state of a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.SDP_RESULT** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE +(Reserved, not supported yet) Indicates the UUID connection state with a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.UUID_VALUE** +- Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ +(Reserved, not supported yet) Indicates the pairing request from a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.PAIRING_REQ** +- Required subscriber permissions: ohos.permission.DISCOVER_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL +(Reserved, not supported yet) Indicates that Bluetooth pairing has been canceled. +- Value: **usual.event.bluetooth.remotedevice.PAIRING_CANCEL** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ +(Reserved, not supported yet) Indicates the connection request from a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.CONNECT_REQ** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY +(Reserved, not supported yet) Indicates the response to the connection request from a remote Bluetooth device. +- Value: **usual.event.bluetooth.remotedevice.CONNECT_REPLY** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL +(Reserved, not supported yet) Indicates that the connection to a remote Bluetooth device has been canceled. +- Value: **usual.event.bluetooth.remotedevice.CONNECT_CANCEL** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates that the connection state with a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE +(Reserved, not supported yet) Indicates that the audio state of a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT +(Reserved, not supported yet) Indicates that the audio gateway state of a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE +(Reserved, not supported yet) Indicates that the calling state of a Bluetooth handsfree has changed. +- Value: **usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE +(Reserved, not supported yet) Indicates that the state of a Bluetooth adapter has changed, for example, Bluetooth has been enabled or disabled. +- Value: **usual.event.bluetooth.host.STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE +(Reserved, not supported yet) Indicates the request for the user to allow Bluetooth device scanning. +- Value: **usual.event.bluetooth.host.REQ_DISCOVERABLE** +- Required subscriber permissions: none + + +## COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE +(Reserved, not supported yet) Indicates the request for the user to enable Bluetooth. +- Value: **usual.event.bluetooth.host.REQ_ENABLE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE +(Reserved, not supported yet) Indicates the request for the user to disable Bluetooth. +- Value: **usual.event.bluetooth.host.REQ_DISABLE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE +(Reserved, not supported yet) Indicates that the Bluetooth scanning mode of the device has changed. +- Value: **usual.event.bluetooth.host.SCAN_MODE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED +(Reserved, not supported yet) Indicates that Bluetooth scanning has been started on the device. +- Value: **usual.event.bluetooth.host.DISCOVERY_STARTED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED +(Reserved, not supported yet) Indicates that Bluetooth scanning is finished on the device. +- Value: **usual.event.bluetooth.host.DISCOVERY_FINISHED** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE +(Reserved, not supported yet) Indicates that the Bluetooth adapter name of the device has changed. +- Value: **usual.event.bluetooth.host.NAME_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE +(Reserved, not supported yet) Indicates that the connection state of Bluetooth A2DP Sink has changed. +- Value: **usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE +(Reserved, not supported yet) Indicates that the playing state of Bluetooth A2DP Sink has changed. +- Value: **usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE +(Reserved, not supported yet) Indicates that the audio state of Bluetooth A2DP Sink has changed. +- Value: **usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE** +- Required subscriber permissions: ohos.permission.USE_BLUETOOTH + + +## COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED +(Reserved, not supported yet) Indicates that the state of the device NFC adapter has changed. +- Value: **usual.event.nfc.action.ADAPTER_STATE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED +(Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the enabled state. +- Value: **usual.event.nfc.action.RF_FIELD_ON_DETECTED** +- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS + + +## COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED +(Reserved, not supported yet) Indicates that the NFC RF field is detected to be in the disabled state. +- Value: **usual.event.nfc.action.RF_FIELD_OFF_DETECTED** +- Required subscriber permissions: ohos.permission.MANAGE_SECURE_SETTINGS + + +## COMMON_EVENT_DISCHARGING +Indicates that the system stops charging the battery. +- Value: **usual.event.DISCHARGING** +- Required subscriber permissions: none + + +## COMMON_EVENT_CHARGING +Indicates that the system starts charging the battery. +- Value: **usual.event.CHARGING** +- Required subscriber permissions: none + + +## COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED +(Reserved, not supported yet) Indicates that the system idle mode has changed. +- Value: **usual.event.DEVICE_IDLE_MODE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_POWER_SAVE_MODE_CHANGED +Indicates that the system power saving mode has changed. +- Value: **usual.event.POWER_SAVE_MODE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USER_ADDED +Indicates that a user has been added to the system. +- Value: **usual.event.USER_ADDED** +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + + +## COMMON_EVENT_USER_REMOVED +Indicates that a user has been removed from the system. +- Value: **usual.event.USER_REMOVED** +- Required subscriber permissions: ohos.permission.MANAGE_LOCAL_ACCOUNTS + + +## COMMON_EVENT_ABILITY_ADDED +(Reserved, not supported yet) Indicates that an ability has been added. +- Value: **usual.event.ABILITY_ADDED** +- Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + + +## COMMON_EVENT_ABILITY_REMOVED +(Reserved, not supported yet) Indicates that an ability has been removed. +- Value: **usual.event.ABILITY_REMOVED** +- Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + + +## COMMON_EVENT_ABILITY_UPDATED +(Reserved, not supported yet) Indicates that an ability has been updated. +- Value: **usual.event.ABILITY_UPDATED** +- Required subscriber permissions: ohos.permission.LISTEN_BUNDLE_CHANGE + + +## COMMON_EVENT_LOCATION_MODE_STATE_CHANGED +(Reserved, not supported yet) Indicates that the location mode of the system has changed. +- Value: **usual.event.location.MODE_STATE_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_SLEEP +(Reserved, not supported yet) Indicates that the in-vehicle infotainment (IVI) system is in sleep mode. +- Value: **common.event.IVI_SLEEP** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_PAUSE +(Reserved, not supported yet) Indicates that the IVI system as entered sleep mode and instructs the playing application to stop playback. +- Value: **common.event.IVI_PAUSE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_STANDBY +(Reserved, not supported yet) Requests a third-party application in the IVI system to pause the current work. +- Value: **common.event.IVI_STANDBY** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_LASTMODE_SAVE +(Reserved, not supported yet) Requests a third-party application in the IVI system to save its last mode. +- Value: **common.event.IVI_LASTMODE_SAVE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_VOLTAGE_ABNORMAL +(Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is abnormal. +- Value: **common.event.IVI_VOLTAGE_ABNORMAL** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_HIGH_TEMPERATURE +(Reserved, not supported yet) Indicates that the temperature of the IVI system is high. +- Value: **common.event.IVI_HIGH_TEMPERATURE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_EXTREME_TEMPERATURE +(Reserved, not supported yet) Indicates that the temperature of the IVI system is extremely high. +- Value: **common.event.IVI_EXTREME_TEMPERATURE** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL +(Reserved, not supported yet) Indicates that the IVI system is at an extreme temperature. +- Value: **common.event.IVI_TEMPERATURE_ABNORMAL** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_VOLTAGE_RECOVERY +(Reserved, not supported yet) Indicates that the voltage of the vehicle's power system is restored to normal. +- Value: **common.event.IVI_VOLTAGE_RECOVERY** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_TEMPERATURE_RECOVERY +(Reserved, not supported yet) Indicates that the temperature of the IVI system is restored to normal. +- Value: **common.event.IVI_TEMPERATURE_RECOVERY** +- Required subscriber permissions: none + + +## COMMON_EVENT_IVI_ACTIVE +(Reserved, not supported yet) Indicates that the battery service of the IVI system is active. +- Value: **common.event.IVI_ACTIVE** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_STATE9+ +Indicates that the USB device state has changed. +- Value: **usual.event.hardware.usb.action.USB_STATE** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_PORT_CHANGED9+ +Indicates that the USB port state of the device has changed. +- Value: **usual.event.hardware.usb.action.USB_PORT_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_DEVICE_ATTACHED +Indicates that a USB device has been attached to the device functioning as a USB host. +- Value: **usual.event.hardware.usb.action.USB_DEVICE_ATTACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_DEVICE_DETACHED +Indicates that a USB device has been detached from the device functioning as a USB host. +- Value: **usual.event.hardware.usb.action.USB_DEVICE_DETACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_ACCESSORY_ATTACHED +(Reserved, not supported yet) Indicates that a USB accessory was attached. +- Value: **usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED** +- Required subscriber permissions: none + + +## COMMON_EVENT_USB_ACCESSORY_DETACHED +(Reserved, not supported yet) Indicates that a USB accessory was detached. +- Value: **usual.event.data.DISK_MOUNTED** +- Required subscriber permissions: none + + +## COMMON_EVENT_DISK_REMOVED +(Reserved, not supported yet) Indicates that an external storage device was removed. +- Value: **usual.event.data.DISK_BAD_REMOVAL** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_UNMOUNTED +(Reserved, not supported yet) Indicates that an external storage device was unmounted. +- Value: **usual.event.data.DISK_UNMOUNTABLE** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_MOUNTED +(Reserved, not supported yet) Indicates that an external storage device was mounted. +- Value: **usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_BAD_REMOVAL +(Reserved, not supported yet) Indicates that an external storage device was removed without being unmounted. +- Value: usual.event.data.DISK_REMOVED +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_UNMOUNTABLE +(Reserved, not supported yet) Indicates that an external storage device is unmountable when the card is inserted. +- Value: **usual.event.data.DISK_UNMOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_DISK_EJECT +(Reserved, not supported yet) Indicates that an external storage device was ejected (at the software level). +- Value: **usual.event.data.DISK_EJECT** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_REMOVED9+ +Indicates that an external storage device was removed. +- Value: **usual.event.data.VOLUME_REMOVED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_UNMOUNTED9+ +Indicates that an external storage device was unmounted. +- Value: **usual.event.data.VOLUME_UNMOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_MOUNTED9+ +Indicates that an external storage device was mounted. +- Value: **usual.event.data.VOLUME_MOUNTED** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_BAD_REMOVAL9+ +Indicates that an external storage device was removed without being unmounted. +- Value: **usual.event.data.VOLUME_BAD_REMOVAL** +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VOLUME_EJECT9+ +Indicates that an external storage device was ejected (at the software level). +- Value: usual.event.data.VOLUME_EJECT +- Required subscriber permissions: ohos.permission.STORAGE_MANAGER + + +## COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED +(Reserved, not supported yet) Indicates that the account visibility changed. +- Value: **usual.event.data.VISIBLE_ACCOUNTS_UPDATED** +- Required subscriber permissions: ohos.permission.GET_APP_ACCOUNTS + + +## COMMON_EVENT_ACCOUNT_DELETED +(Reserved, not supported yet) Indicates that an account was deleted. +- Value: **usual.event.data.ACCOUNT_DELETED** +- Required subscriber permissions: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + + +## COMMON_EVENT_FOUNDATION_READY +(Reserved, not supported yet) Indicates that the foundation is ready. +- Value: **usual.event.data.FOUNDATION_READY** +- Required subscriber permissions: ohos.permission.RECEIVER_STARTUP_COMPLETED + + +## COMMON_EVENT_AIRPLANE_MODE_CHANGED +Indicates that the airplane mode of the device has changed. +- Value: **usual.event.AIRPLANE_MODE** +- Required subscriber permissions: none + + +## COMMON_EVENT_SPLIT_SCREEN +Indicates that the screen has been split. +- Value: **usual.event.SPLIT_SCREEN** +- Required subscriber permissions: ohos.permission.RECEIVER_SPLIT_SCREEN + + +## COMMON_EVENT_SLOT_CHANGE9+ +Indicates that the notification slot has been updated. +- Value: **usual.event.SLOT_CHANGE** +- Required subscriber permissions: ohos.permission.NOTIFICATION_CONTROLLER + + +## COMMON_EVENT_SPN_INFO_CHANGED9+ +Indicates that the SPN displayed has been updated. +- Value: **usual.event.SPN_INFO_CHANGED** +- Required subscriber permissions: none + + +## COMMON_EVENT_QUICK_FIX_APPLY_RESULT9+ +Indicates the result of applying a quick fix to the application. +- Value: **usual.event.QUICK_FIX_APPLY_RESULT** +- Required subscriber permissions: none diff --git a/en/application-dev/reference/apis/development-intro.md b/en/application-dev/reference/apis/development-intro.md index aaeab2f2961f4254f4bbd8d634ee0f773f996ab4..281fa66969891561b062b7cfd7185d25f7c7f474 100644 --- a/en/application-dev/reference/apis/development-intro.md +++ b/en/application-dev/reference/apis/development-intro.md @@ -9,9 +9,9 @@ In API references, the earliest versions of APIs and components are specified in - For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7." - For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid8+" indicates that the **uid** attribute is supported since API version 8. -## Ability Framework Model Description +## Application Model Description -Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md). +Along its evolution, OpenHarmony has provided two application models: FA model and stage model. For their differences, see [Interpretation of the Application Model](../../application-models/application-model-description.md). - If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model." - If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model." @@ -19,18 +19,18 @@ Ability is the minimum unit for the system to schedule applications. An applicat ## Available APIs -Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications. +Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by common applications. A description regarding system APIs will be provided in the document. - If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs." - If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API." -Non-system applications are applications whose Ability Privilege Level (APL) is **normal**. The default application level is **normal**. +A common application is an application whose application type is **hos_normal_app** in the HarmonyAppProvision configuration file. **hos_normal_app** is the default value for project creation. -For details about the APL and how to declare the APL of an application higher than **normal**, see [Access Control Overview - App APLs](../../security/accesstoken-overview.md#app-apls). - -The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use system APIs, switch to the full SDK. For details on the operation, see [Guide to Switching to Full SDK](../../quick-start/full-sdk-switch-guide.md). +The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use the system APIs, you must: +- Switch the public SDK to the full SDK by following the instructions provided in [Guide to Switching to Full SDK] (../../quick-start/full-sdk-switch-guide.md). +- Change the value of **app-feature** in the HarmonyAppProvision configuration file to **hos_system_app**. For details, see [HarmonyAppProvision Configuration File](../../security/app-provision-structure.md). ## Permission Description @@ -41,17 +41,19 @@ To call APIs to access these resources, you must apply for the corresponding per - If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx" - If an application can call an API without any permission, no special description is provided. -To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md). +To determine whether an application can request a specific permission, see [Permission Application and Use](../../security/accesstoken-overview.md#permission-application-and-use). ## System Capability Description -System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md). +System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SystemCapability](../syscap.md). The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx" +You can use the [SystemCapability List](../syscap-list.md) to query the devices supported by a specific capability set. + ## Sample Code Language Description OpenHarmony supports two development languages: JS and TS. -- When a code block is labeled with `js`, the sample code can be used in the JS and ArkTS projects. -- When a code block is labeled with `ts`, the sample code can be used only in the ArkTS project. +- When a code block is labeled with **js**, the sample code can be used in the JS and ArkTS projects. +- When a code block is labeled with **ts**, the sample code can be used only in the ArkTS project. diff --git a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md index b3476c86cce52d57a0d54c6b01c1fbed71076ef9..13fa28f551fe677055c589c11a0b4a1b581757b5 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @@ -1,10 +1,10 @@ # BundleStatusCallback -The **BundleStatusCallback** module provides bundle callback information, which is obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). +The **BundleStatusCallback** module provides callbacks for bundle status changes. The changes can be obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). > **NOTE** > -> This module is deprecated since API version 9. You are advised to use [bundleMonitor](js-apis-bundleMonitor.md) instead. +> 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. ## BundleStatusCallback(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 40725aefbf65838c8da46d75a13368c68118df0d..f45268cb699527ed412518bdee3b5f8b41f6520f 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -1,4 +1,4 @@ -# @ohos.bundle.innerBundleManager +# @ohos.bundle.innerBundleManager (innerBundleManager) The **innerBundleManager** module provides APIs for the **Home Screen** application. @@ -22,7 +22,7 @@ SystemCapability.BundleManager.BundleFramework getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; Obtains the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfo9) instead. **Required permissions** @@ -38,11 +38,11 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The value must be greater than or equal to 0.| -| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| bundleName | string | Yes | Bundle name. | +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information.| ## innerBundleManager.getLauncherAbilityInfos(deprecated) @@ -50,7 +50,7 @@ This is a system API and cannot be called by third-party applications. getLauncherAbilityInfos(bundleName: string, userId: number) : Promise<Array<LauncherAbilityInfo>> Obtains the launcher ability information based on a given bundle name. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfo9) instead. **Required permissions** @@ -66,9 +66,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ----------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ----------------------------- | +| bundleName | string | Yes | Bundle name. | | userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** @@ -82,7 +82,7 @@ This is a system API and cannot be called by third-party applications. on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback<string>) : void; Registers a callback to receive bundle status changes. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#on](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.on](js-apis-bundleMonitor.md#bundlemonitoron) instead. **Required permissions** @@ -109,7 +109,7 @@ This is a system API and cannot be called by third-party applications. on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback) : Promise<string> Registers a callback to receive bundle status changes. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#on](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.on](js-apis-bundleMonitor.md#bundlemonitoron) instead. **Required permissions** @@ -141,7 +141,7 @@ This is a system API and cannot be called by third-party applications. off(type:"BundleStatusChange", callback: AsyncCallback<string>) : void; Deregisters the callback that receives bundle status changes. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#off](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.off](js-apis-bundleMonitor.md#bundlemonitoroff) instead. **Required permissions** @@ -167,7 +167,7 @@ This is a system API and cannot be called by third-party applications. off(type:"BundleStatusChange") : Promise<string> Deregisters the callback that receives bundle status changes. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [bundleMonitor#off](js-apis-bundleMonitor.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleMonitor.off](js-apis-bundleMonitor.md#bundlemonitoroff) instead. **Required permissions** @@ -198,7 +198,7 @@ This is a system API and cannot be called by third-party applications. getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; Obtains the information about all launcher abilities. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetalllauncherabilityinfo9) instead. **Required permissions** @@ -224,7 +224,7 @@ This is a system API and cannot be called by third-party applications. getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>> Obtains the information about all launcher abilities. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetalllauncherabilityinfo9) instead. **Required permissions** @@ -255,7 +255,7 @@ This is a system API and cannot be called by third-party applications. getShortcutInfos(bundleName :string, callback: AsyncCallback<Array<ShortcutInfo>>) : void; Obtains the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getShortcutInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9) instead. **Required permissions** @@ -273,7 +273,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| bundleName | string | Yes | Bundle name. | | callback | AsyncCallback\> | Yes | Callback used to return an array of the shortcut information.| ## innerBundleManager.getShortcutInfos(deprecated) @@ -281,7 +281,7 @@ This is a system API and cannot be called by third-party applications. getShortcutInfos(bundleName : string) : Promise<Array<ShortcutInfo>> Obtains the shortcut information based on a given bundle name. This API uses a promise to return the result. -> This API is deprecated since API version 9. You are advised to use [launcherBundleManager#getShortcutInfo](js-apis-launcherBundleManager.md) instead. +> This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9) instead. **Required permissions** @@ -299,7 +299,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md index 493b263bd25d74fa7cfa5d9c59a45659fb4b5740..eda69bbe8857d6d787753bc91247dcde124f9633 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -1,4 +1,4 @@ -# distributedBundle +# @ohos.distributedBundle (Distributed Bundle Management) The **distributedBundle** module manages distributed bundles. @@ -26,7 +26,7 @@ For details, see [Permission Levels](../../security/accesstoken-overview.md#perm ## distributedBundle.getRemoteAbilityInfodeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void; @@ -55,7 +55,7 @@ This is a system API and cannot be called by third-party applications. ## distributedBundle.getRemoteAbilityInfodeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> @@ -87,7 +87,7 @@ This is a system API and cannot be called by third-party applications. ## distributedBundle.getRemoteAbilityInfosdeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void; @@ -116,7 +116,7 @@ This is a system API and cannot be called by third-party applications. ## distributedBundle.getRemoteAbilityInfosdeprecated -> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo(@ohos.bundle.distributedBundleManager)](js-apis-distributedBundleManager.md) instead. getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 83cf9c77d2899e1c0c0969be8199c602e4374816..5908fc527c4d6f1c1a3391671a0ac9dcc4b41d6f 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,4 +1,4 @@ -# @ohos.bundle +# @ohos.bundle (Bundle) The **bundle** module provides APIs for obtaining information about an application, including [bundle information](js-apis-bundle-BundleInfo.md), [application information](js-apis-bundle-ApplicationInfo.md), and [ability information](js-apis-bundle-AbilityInfo.md). It also provides APIs to obtain and set the application disabling state. @@ -15,10 +15,11 @@ import bundle from '@ohos.bundle'; | Required Permissions | Permission Level | Description | |--------------------------------------------|--------------|---------------| -| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | +| ohos.permission.CHANGE_ABILITY_ENABLED_STATE | system_basic | Permission to enable or disable an application or ability.| +| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle.| | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles. | | ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles. | -| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status.| +| ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -44,7 +45,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | @@ -90,9 +91,9 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -133,8 +134,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -172,20 +173,21 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** | Type | Description | | --------------------------- | -------------------------- | -| Promise> | Promise used to return the information of all available bundles.| +| Promise> | Promise used to return the information of all bundles.| **Example** ```ts let bundleFlag = 0; let userId = 100; + bundle.getAllBundleInfo(bundleFlag, userId) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -215,7 +217,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | **Example** @@ -252,7 +254,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | |------------|-------------------------------------------------------------------|-----|---------------------------------------------------------------------| -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | | @@ -294,9 +296,9 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- |---------------------------------------------------------------------| -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | No | Options that contain the user ID. | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| +| options | [BundleOptions](#bundleoptionsdeprecated) | No | Options that contain the user ID. | **Return value** @@ -310,7 +312,7 @@ SystemCapability.BundleManager.BundleFramework let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { - "userId" : 100 + "userId": 100 }; bundle.getBundleInfo(bundleName, bundleFlags, options) .then((data) => { @@ -340,11 +342,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------------- | ---- |---------------------------------------------------------------------| -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -360,7 +362,6 @@ bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { }) ``` - ## bundle.getBundleInfodeprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo) instead. @@ -383,9 +384,9 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| +| options | [BundleOptions](#bundleoptionsdeprecated) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -394,7 +395,7 @@ SystemCapability.BundleManager.BundleFramework let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { - "userId" : 100 + "userId": 100 }; bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { if (err) { @@ -504,7 +505,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -545,7 +546,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** @@ -589,7 +590,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- |--------------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -629,9 +630,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- |------------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ----------------------------------------------- | +| bundleName | string | Yes | Bundle name. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| **Return value** @@ -720,7 +721,7 @@ let flag = bundle.BundleFlag.GET_ABILITY_INFO_WITH_PERMISSION; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.getAbilityInfo(want, flag, userId).then((abilityInfo) => { @@ -760,7 +761,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | | permissionName | string | Yes | Name of the permission. | -| callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | Yes | Callback used to return the permission details.| +| callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef.md)> | Yes | Callback used to return the permission details.| **Example** @@ -805,7 +806,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------------------ | ------------------------------------------------------ | -| Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | Promise used to return the permission details.| +| Promise<[PermissionDef](js-apis-bundle-PermissionDef.md)> | Promise used to return the permission details.| **Example** @@ -838,7 +839,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -880,7 +881,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the application information. | @@ -919,7 +920,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -952,11 +953,11 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The absolute path of the application and the data directory sandbox path are supported.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| **Return value** -| Type | Description | -| -------------- | -------------------------------------- | +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | | Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the information about the bundles.| **Example** @@ -989,7 +990,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored.. The absolute path of the application and the data directory sandbox path are supported.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflagdeprecated).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** @@ -1006,7 +1007,6 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { }) ``` - ## bundle.getAbilityInfodeprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo) instead. @@ -1029,7 +1029,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- |------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name.| | abilityName | string | Yes | Ability name.| **Return value** @@ -1042,7 +1042,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1073,7 +1073,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------ | ---- |----------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | abilityName | string | Yes | Ability name. | | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| @@ -1081,7 +1081,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1111,10 +1111,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|--------|-----|------------| -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name.| +| abilityName | string | Yes | Ability name. | **Return value** @@ -1126,7 +1126,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityLabel(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1155,17 +1155,17 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|------------------------|-----|-------------------------| -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Ability name. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| abilityName | string | Yes | Ability name. | | callback | AsyncCallback\ | Yes | Callback used to return the application name.| **Example** ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1197,13 +1197,13 @@ SystemCapability.BundleManager.BundleFramework | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return the result. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ bundle.isAbilityEnabled(abilityInfo).then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1230,13 +1230,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ----------------------- | | info | [AbilityInfo](js-apis-bundle-AbilityInfo.md) | Yes | Ability information. | -| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ability is enabled, and **false** means the opposite.| **Example** ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ bundle.isAbilityEnabled(abilityInfo, (err, data) => { if (err) { @@ -1264,13 +1264,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return the result. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -1300,8 +1300,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ----------------------- | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of the application.| -| callback | AsyncCallback\ | Yes | Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned. | +| bundleName | string | Yes | Bundle name.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -1322,7 +1322,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> -Obtains the ability information based on a given want. This API uses a promise to return the result. +Obtains the ability information based on given Want. This API uses a promise to return the result. No permission is required for obtaining the caller's own information. @@ -1338,8 +1338,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ------------------------------------- | -| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| want | [Want](js-apis-application-want.md) | Yes | Want containing the bundle name | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -1355,7 +1355,7 @@ let bundleFlags = 0; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, userId) .then((data) => { @@ -1373,7 +1373,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the ability information of the specified user based on a given want. This API uses an asynchronous callback to return the result. +Obtains the ability information of the specified user based on given Want. This API uses an asynchronous callback to return the result. No permission is required for obtaining the caller's own information. @@ -1387,12 +1387,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| -| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Want containing the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflagdeprecated).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -1401,7 +1401,7 @@ let bundleFlags = 0; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { if (err) { @@ -1418,7 +1418,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; -Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. +Obtains the ability information based on given Want. This API uses an asynchronous callback to return the result. No permission is required for obtaining the caller's own information. @@ -1432,11 +1432,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| -| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Want containing the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflagdeprecated).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -1444,7 +1444,7 @@ SystemCapability.BundleManager.BundleFramework let bundleFlags = 0; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { if (err) { @@ -1477,7 +1477,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** | Type | Description | @@ -1516,7 +1516,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the **Want** object.| **Example** @@ -1582,9 +1582,9 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -|----------|------------------------|-----|----------------------------| -| uid | number | Yes | UID based on which the bundle name is to obtain. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ----------------------------------------------------- | +| uid | number | Yes | UID based on which the bundle name is to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -1621,10 +1621,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- |-----------------| -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------ | +| bundleName | string | Yes | Bundle name.| +| abilityName | string | Yes | Ability name. | **Return value** | Type | Description | @@ -1635,7 +1635,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityIcon(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1667,7 +1667,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- |-------------------------------------------------| -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | abilityName | string | Yes | Ability name. | | callback | AsyncCallback\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| @@ -1675,7 +1675,7 @@ SystemCapability.BundleManager.BundleFramework ```ts let bundleName = "com.example.myapplication"; -let abilityName = "com.example.myapplication.MainAbility"; +let abilityName = "EntryAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index c9cc2b79ba9aed4400fdc52bd938c5e3db711b6b..a55ab990ef39072d83989526e66723eab794ca63 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.EnterpriseAdminExtensionAbility +# @ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility) The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators. diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index e7be32c9b840dbe67f99e120e3798ad5ecd9fcd4..a22f7b48a977066e085da4b9ddfcdeb24f21463f 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -1,4 +1,4 @@ -# Work Scheduler Callbacks +# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks) The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks. 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 84033dd0a9d22eba5ffe275c38f078bfb0649b83..37bf04c704a91f0580fddf99b14f9f52fb94d683 100644 --- a/en/application-dev/reference/apis/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -1,4 +1,4 @@ -# @ohos.ability.ability +# @ohos.ability.ability (Ability) The **Ability** module provides all level-2 module APIs for developers to export. diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index f77fd415a1bb7dd8a7d8968f96dce2718f2873ed..d345bbb9db0739da16156ecfc0bd4fe344989149 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -14,10 +14,10 @@ This module provides APIs for accessing ability-specific resources. You can use Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. ```ts -import Ability from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; - let context = undefined; -class MainAbility extends Ability { +let context = undefined; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { context = this.context; } @@ -30,8 +30,8 @@ class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| +| 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 @@ -40,6 +40,11 @@ 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** @@ -54,13 +59,14 @@ Starts an ability. This API uses an asynchronous callback to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; @@ -89,6 +95,11 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<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** @@ -104,15 +115,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0 @@ -142,6 +154,11 @@ 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** @@ -162,13 +179,14 @@ Starts an ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; var options = { @@ -198,7 +216,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. +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 @@ -214,15 +237,16 @@ Starts an ability. This API uses an asynchronous callback to return the result w | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -248,7 +272,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. +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 @@ -265,15 +294,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0, @@ -303,7 +333,12 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. This API uses a promise to return the result when the ability is terminated. +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 @@ -326,13 +361,14 @@ Starts an ability. This API uses a promise to return the result when the ability | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; var options = { @@ -361,9 +397,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -375,22 +416,23 @@ Starts an ability. This API uses an asynchronous callback to return the result w | -------- | -------- | -------- | -------- | | 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.| +| 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 other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -418,9 +460,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -440,15 +487,16 @@ Starts an ability with the start options specified. This API uses an asynchronou | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -479,9 +527,14 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -499,22 +552,23 @@ Starts an ability with the start options specified. This API uses a promise to r | Type| Description| | -------- | -------- | -| Promise<AbilityResult> | Promise used to return the result.| +| 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 other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -543,7 +597,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -561,15 +615,16 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -594,7 +649,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -611,15 +666,16 @@ Starts a new Service Extension ability. This API uses a promise to return the re | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -644,9 +700,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -665,15 +721,16 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -699,9 +756,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -719,15 +776,16 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -752,7 +810,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -770,20 +828,27 @@ Stops a Service Extension ability in the same application. This API uses an asyn | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + 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) { + if (error.code != 0) { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + ' error.message: ' + JSON.stringify(error.message)); @@ -803,7 +868,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -820,18 +885,25 @@ Stops a Service Extension ability in the same application. This API uses a promi | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + 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. @@ -853,9 +925,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -874,19 +946,26 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + 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. @@ -908,9 +987,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -928,19 +1007,26 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + 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. @@ -977,7 +1063,8 @@ Terminates this ability. This API uses an asynchronous callback to return the re | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1014,7 +1101,8 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1034,7 +1122,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. +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 @@ -1050,7 +1138,8 @@ Terminates this ability. This API uses an asynchronous callback to return the ab | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1088,8 +1177,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). ## AbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult): Promise<void>; - -Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. +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 @@ -1110,7 +1198,8 @@ Terminates this ability. This API uses a promise to return the ability result in | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1173,15 +1262,16 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, @@ -1204,9 +1294,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1231,15 +1321,16 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1283,7 +1374,8 @@ Disconnects a connection. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1329,7 +1421,8 @@ Disconnects a connection. This API uses an asynchronous callback to return the r | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1361,6 +1454,11 @@ 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. @@ -1388,7 +1486,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }; @@ -1419,7 +1517,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "", parameters: { "ohos.aafwk.param.callAbilityToForeground": true @@ -1450,7 +1548,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -1469,15 +1572,16 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -1506,7 +1610,12 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -1526,15 +1635,16 @@ Starts an ability with the account ID and start options specified. This API uses | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1566,7 +1676,12 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Starts an ability with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -1585,15 +1700,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu | ID| Error Message| | ------- | -------------------------------- | | 401 | If the input parameter is not valid parameter. | -For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1618,65 +1734,6 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). } ``` -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Yes| Callback used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Promise used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - - ## AbilityContext.setMissionLabel setMissionLabel(label: string, callback:AsyncCallback<void>): void; @@ -1696,7 +1753,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ```ts this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + console.log('setMissionLabel result:' + JSON.stringify(result)); }); ``` @@ -1744,7 +1801,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | image.PixelMap | Yes| Icon of the ability to set.| +| 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** @@ -1786,7 +1843,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | image.PixelMap | Yes| Icon of the ability to set.| +| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| **Return value** 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 108345299ae8e55e185b6d33df259400afe2dada..f1301ad877dcf5a0bd2fec5ad5be10452ee88716 100644 --- a/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -1,6 +1,6 @@ -# @ohos.ability.dataUriUtils +# @ohos.ability.dataUriUtils (dataUriUtils) -The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. 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. +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. > **NOTE** > @@ -24,18 +24,18 @@ Obtains the ID attached to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object from which the ID is to be obtained.| +| uri | string | Yes | Target URI object.| **Return value** | Type | Description | | ------ | ------------------------ | -| number | ID obtained from the URI object.| +| number | ID obtained.| **Example** ```ts -dataUriUtils.getId("com.example.dataUriUtils/1221") +let id = dataUriUtils.getId("com.example.dataUriUtils/1221"); ``` @@ -52,7 +52,7 @@ Attaches an ID to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object to which an ID is to be attached.| +| uri | string | Yes | Target URI object.| | id | number | Yes | ID to be attached. | **Return value** @@ -64,10 +64,10 @@ Attaches an ID to the end of a given URI. **Example** ```ts -var idint = 1122; -dataUriUtils.attachId( +let id = 1122; +let uri = dataUriUtils.attachId( "com.example.dataUriUtils", - idint, + id, ) ``` @@ -96,9 +96,11 @@ Deletes the ID from the end of a given URI. **Example** ```ts -dataUriUtils.deleteId("com.example.dataUriUtils/1221") +let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") ``` + + ## dataUriUtils.updateId updateId(uri: string, id: number): string @@ -111,7 +113,7 @@ Updates the ID in a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------- | -| uri | string | Yes | URI object to be updated.| +| uri | string | Yes | Target URI object.| | id | number | Yes | New ID. | **Return value** @@ -123,9 +125,9 @@ Updates the ID in a given URI. **Example** ```ts -var idint = 1122; -dataUriUtils.updateId( - "com.example.dataUriUtils", - idint +let id = 1122; +let uri = dataUriUtils.updateId( + "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 c6e16f3f0cbe2bd0dd18dd5ea7fd72c8a0f44fb7..dc0e8ae8928a9191f70b555e84a3f58b09e4b876 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -1,9 +1,9 @@ -# @ohos.ability.errorCode +# @ohos.ability.errorCode (ErrorCode) -The **ErrorCode** module defines the error codes that can be used when the ability is started. - - **NOTE** +The **ErrorCode** module defines the error codes that may be returned when an ability is started. +> **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. ## Modules to Import @@ -14,13 +14,13 @@ import errorCode from '@ohos.ability.errorCode' ## ErrorCode -Defines the error codes used when the ability is started. +Enumerates the error codes that may be returned when an ability is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------------------------ | ---- | ---------------------------------------- | -| NO_ERROR | 0 | No error occurs. | +| NO_ERROR | 0 | No error. | | INVALID_PARAMETER | -1 | Invalid parameter.| | ABILITY_NOT_FOUND | -2 | The ability is not found.| | PERMISSION_DENY | -3 | Permission denied. | 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 2f1b927b6191b6b87b649f1b4a85067deb705541..b527edfcf7911fec83b4e8d5a01a2761772e95f1 100644 --- a/en/application-dev/reference/apis/js-apis-ability-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -1,6 +1,6 @@ -# @ohos.ability.featureAbility +# @ohos.ability.featureAbility (FeatureAbility) -The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability. +The **FeatureAbility** module provides APIs that enable user interaction. You can use the APIs to start or terminate an ability, obtain a **dataAbilityHelper** object, obtain the window corresponding to the current ability, and connect to or disconnect from a ServiceAbility. > **NOTE** > @@ -9,7 +9,7 @@ The **FeatureAbility** module provides a UI for interacting with users. You can ## Constraints -APIs of the **FeatureAbility** module can be called only by Page abilities. +The APIs of the **FeatureAbility** module can be called only by PageAbilities. ## Modules to Import @@ -23,6 +23,11 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\) 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -48,7 +53,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri: "" }, }, @@ -66,6 +71,11 @@ startAbility(parameter: StartAbilityParameter): Promise\ 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -74,6 +84,12 @@ Starts an ability. This API uses a promise to return the result. | --------- | ---------------------------------------- | ---- | -------------- | | parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result.| + **Example** ```ts @@ -90,7 +106,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri: "" }, } @@ -105,6 +121,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper Obtains a **dataAbilityHelper** object. +Observe the following when using this API: + - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**). + - If an application running in the background needs to call this API to access a DataAbility, 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -117,7 +139,7 @@ Obtains a **dataAbilityHelper** object. | Type | Description | | ----------------- | ------------------------------- | -| DataAbilityHelper | A utility class used to help other abilities access the Data ability.| +| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access the Data ability.| **Example** @@ -132,7 +154,12 @@ var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts an ability. This API uses an asynchronous callback to return the execution result when the ability is destroyed. +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. + +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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -159,7 +186,7 @@ featureAbility.startAbilityForResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"" }, }, @@ -173,7 +200,12 @@ featureAbility.startAbilityForResult( startAbilityForResult(parameter: StartAbilityParameter): Promise\ -Starts an ability. This API uses a promise to return the execution result when the ability is destroyed. +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. + +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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -187,7 +219,7 @@ Starts an ability. This API uses a promise to return the execution result when t | Type | Description | | ---------------------------------------- | ------- | -| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promised returned with the execution result.| +| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Example** @@ -205,7 +237,7 @@ featureAbility.startAbilityForResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { @@ -229,7 +261,7 @@ featureAbility.startAbilityForResult( terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), 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.FAModel @@ -237,7 +269,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | -------------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -257,7 +289,7 @@ featureAbility.terminateSelfWithResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { mykey0: 2222, @@ -281,7 +313,7 @@ featureAbility.terminateSelfWithResult( terminateSelfWithResult(parameter: AbilityResult): Promise\ -Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), 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.FAModel @@ -289,7 +321,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | ------------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Ability to start.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.| **Return value** @@ -314,7 +346,7 @@ featureAbility.terminateSelfWithResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { mykey0: 2222, @@ -345,7 +377,7 @@ Checks whether the main window of this ability has the focus. This API uses an a | Name | Type | Mandatory | Description | | -------- | ----------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
If the main window has the focus, **true** is returned. Otherwise, **false** is returned.| **Example** @@ -368,7 +400,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr | Type | Description | | ----------------- | ------------------------------------- | -| Promise\ | Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| Promise\ | Promise used to return the result. If the main window has the focus, **true** is returned. Otherwise, **false** is returned.| **Example** @@ -383,7 +415,7 @@ featureAbility.hasWindowFocus().then((data) => { getWant(callback: AsyncCallback\): void -Obtains the **Want** object sent from this ability. This API uses an asynchronous callback to return the result. +Obtains the Want corresponding to the ability to start. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -391,7 +423,7 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | ----------------------------- | ---- | --------- | -| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the Want.| **Example** @@ -406,7 +438,7 @@ featureAbility.getWant((err, data) => { getWant(): Promise\ -Obtains the **Want** object sent from this ability. This API uses a promise to return the result. +Obtains the Want corresponding to the ability to start. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -414,7 +446,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r | Type | Description | | ----------------------- | ---------------- | -| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the result.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the Want.| **Example** @@ -453,7 +485,7 @@ context.getBundleName((err, data) => { terminateSelf(callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. +Terminates this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -478,7 +510,7 @@ featureAbility.terminateSelf( terminateSelf(): Promise\ -Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result. +Terminates this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -501,7 +533,13 @@ featureAbility.terminateSelf().then((data) => { connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses an asynchronous callback to return the result. +Connects this ability to a ServiceAbility. + +Observe the following when using this API: + - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).. + - If an application running in the background needs to call this API to connect to a ServiceAbility, 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -509,14 +547,14 @@ Connects this ability to a specific Service ability. This API uses an asynchrono | Name | Type | Mandatory | Description | | ------- | -------------- | ---- | --------------------- | -| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.| -| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Callback used to return the result. | +| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. | **Return value** | Type | Description | | ------ | -------------------- | -| number | ID of the Service ability connected.| +| number | ID of the connected ServiceAbility. The ID starts from 0 and is incremented by 1 each time a connection is set up.| **Example** @@ -536,7 +574,7 @@ var connectId = featureAbility.connectAbility( { deviceId: "", bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -550,7 +588,7 @@ var connectId = featureAbility.connectAbility( disconnectAbility(connection: number, callback:AsyncCallback\): void -Disconnects this ability from a specific Service ability. This API uses an asynchronous callback to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -558,7 +596,7 @@ Disconnects this ability from a specific Service ability. This API uses an async | Name | Type | Mandatory | Description | | ---------- | -------------------- | ---- | ----------------------- | -| connection | number | Yes | ID of the Service ability to disconnect.| +| connection | number | Yes | ID of the ServiceAbility to disconnect.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -578,7 +616,7 @@ function onFailedCallback(code){ var connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -597,7 +635,7 @@ var result = featureAbility.disconnectAbility(connectId, disconnectAbility(connection: number): Promise\ -Disconnects this ability from a specific Service ability. This API uses a promise to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -605,7 +643,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ----------------------- | -| connection | number | Yes | ID of the Service ability to disconnect.| +| connection | number | Yes | ID of the ServiceAbility to disconnect.| **Return value** @@ -630,7 +668,7 @@ function onFailedCallback(code){ var connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -659,7 +697,7 @@ Obtains the window corresponding to this ability. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the window.| +| callback | AsyncCallback\<[window.Window](js-apis-window.md#window)> | Yes | Callback used to return the window.| **Example** @@ -681,7 +719,7 @@ Obtains the window corresponding to this ability. This API uses a promise to ret | Type | Description | | ----------------------- | ----------------------------- | -| Promise\ | Promise used to return the window.| +| Promise\<[window.Window](js-apis-window.md#window)> | Promise used to return the window.| **Example** @@ -693,7 +731,7 @@ featureAbility.getWindow().then((data) => { ## AbilityWindowConfiguration -The value is obtained through the **featureAbility.AbilityWindowConfiguration** API. +Defines the window configuration corresponding to this ability. The configuration is obtained through **featureAbility.AbilityWindowConfiguration**. **Example** @@ -705,18 +743,18 @@ featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED | Name | Value | Description | | ---------------------------------------- | ---- | ---------------------------------------- | -| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.| -| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode. | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.| -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.| -| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.| +| 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_FLOATING7+ | 102 | The PageAbility is displayed in floating window mode.| ## AbilityStartSetting -The **AbilityStartSetting** attribute is an object defined as [key: string]: any. The key is a type of **AbilityStartSetting**, and the value is a type of **AbilityWindowConfiguration**. +Defines the window attribute corresponding to this ability. The **abilityStartSetting** attribute is an object defined in the format of [**key: string]: any**, where **key** is an enumerated value of **AbilityStartSetting** and **value** is an enumerated value of **AbilityWindowConfiguration**. -The value is obtained through the **featureAbility.AbilityStartSetting** API. +The value is obtained through **featureAbility.AbilityStartSetting**. **Example** @@ -734,7 +772,7 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY ## ErrorCode -Enumerates error codes. +Enumerates the error codes. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -743,12 +781,12 @@ Enumerates error codes. | NO_ERROR7+ | 0 | No error occurs.| | INVALID_PARAMETER7+ | -1 | Invalid parameter.| | ABILITY_NOT_FOUND7+ | -2 | The ability is not found.| -| PERMISSION_DENY7+ | -3 | The request is denied.| +| PERMISSION_DENY7+ | -3 | Permission denied.| ## DataAbilityOperationType -Enumerates operation types of the Data ability. +Enumerates the operation types of a DataAbility. The DataAbility can use an enumerated value to specify the operation type when operating data in batches. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -761,23 +799,25 @@ Enumerates operation types of the Data ability. ## flags +Enumerates the flags that specify how the Want will be handled. + **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ---------------------------------------- | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Continues the ability on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether the FormAbility is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ability is started in the foreground regardless of whether the host application is started.
**System API**: This is a system API and cannot be called by third-party applications. | | 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_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| +| 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 46355b926228755520d3d215d4275af03ecd88bc..7d00454ea5ce5b0051c2fff6856f9653be89b455 100644 --- a/en/application-dev/reference/apis/js-apis-ability-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -1,6 +1,6 @@ -# @ohos.ability.particleAbility +# @ohos.ability.particleAbility (ParticleAbility) -The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability. +The **particleAbility** module provides APIs for operating a ServiceAbility. You can use the APIs to start and terminate a ParticleAbility, obtain a **dataAbilityHelper** object, and connect to or disconnect from a ServiceAbility. > **NOTE** > @@ -21,7 +21,12 @@ import particleAbility from '@ohos.ability.particleAbility' startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts a Particle ability. This API uses an asynchronous callback to return the result. +Starts a ParticleAbility. 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -48,7 +53,7 @@ particleAbility.startAbility( flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, deviceId: "", bundleName: "com.example.Data", - abilityName: "com.example.Data.MainAbility", + abilityName: "EntryAbility", uri: "" }, }, @@ -62,7 +67,12 @@ particleAbility.startAbility( startAbility(parameter: StartAbilityParameter): Promise\; -Starts a Particle ability. This API uses a promise to return the result. +Starts a ParticleAbility. 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -94,7 +104,7 @@ particleAbility.startAbility( flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, deviceId: "", bundleName: "com.example.Data", - abilityName: "com.example. Data.MainAbility", + abilityName: "EntryAbility", uri: "" }, }, @@ -107,7 +117,7 @@ particleAbility.startAbility( terminateSelf(callback: AsyncCallback\): void -Terminates this Particle ability. This API uses an asynchronous callback to return the result. +Terminates this ParticleAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -133,7 +143,7 @@ particleAbility.terminateSelf( terminateSelf(): Promise\ -Terminates this Particle ability. This API uses a promise to return the result. +Terminates this ParticleAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -161,6 +171,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper Obtains a **dataAbilityHelper** object. +Observe the following when using this API: + - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**). + - If an application running in the background needs to call this API to access a DataAbility, 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -173,7 +189,7 @@ Obtains a **dataAbilityHelper** object. | Type | Description | | ----------------- | -------------------------------------------- | -| DataAbilityHelper | A utility class used to help other abilities access a Data ability.| +| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access a DataAbility.| **Example** @@ -222,7 +238,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -283,7 +299,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -349,7 +365,7 @@ particleAbility.cancelBackgroundRunning(callback); cancelBackgroundRunning(): Promise<void>; -Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). +Requests to cancel a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -376,7 +392,13 @@ particleAbility.cancelBackgroundRunning().then(() => { connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses a callback to return the result. +Connects this ability to a specific ServiceAbility. + +Observe the following when using this API: + - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).. + - If an application running in the background needs to call this API to connect to a ServiceAbility, 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 FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -384,23 +406,14 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | ---------------------------- | -| request | [Want](js-apis-application-want.md) | Yes | Service ability to connect.| -| options | ConnectOptions | Yes | Callback used to return the result. | - - -ConnectOptions +| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. | -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Mandatory | Description | -| ------------ | -------- | ---- | ------------------------- | -| onConnect | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | function | Yes | Callback invoked when the connection fails. | -| onFailed | function | Yes | Callback invoked when **connectAbility** fails to be called.| **Example** ```ts +import particleAbility from '@ohos.ability.particleAbility' import rpc from '@ohos.rpc' function onConnectCallback(element, remote) { @@ -439,7 +452,7 @@ particleAbility.disconnectAbility(connId).then((data) => { disconnectAbility(connection: number, callback:AsyncCallback\): void; -Disconnects this ability from the Service ability. This API uses a callback to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -452,7 +465,8 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** ```ts -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)); @@ -489,7 +503,7 @@ var result = particleAbility.disconnectAbility(connId).then((data) => { disconnectAbility(connection: number): Promise\; -Disconnects this ability from the Service ability. This API uses a promise to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -502,7 +516,8 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** ```ts -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)); @@ -538,7 +553,7 @@ particleAbility.disconnectAbility(connId).then((data) => { ## ErrorCode -Enumerates error codes. +Enumerates the error codes. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel 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 30fb8b3b970b22513f2dd520d43a11b76f66e47d..87b52688c5bec0a80bc44d9c8dcba63fe00283f2 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,4 +1,4 @@ -# @ohos.ability.wantConstant +# @ohos.ability.wantConstant (wantConstant) The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. @@ -14,7 +14,7 @@ import wantConstant from '@ohos.ability.wantConstant'; ## wantConstant.Action -Enumerates the action constants of the **Want** object. +Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. **System capability**: SystemCapability.Ability.AbilityBase @@ -57,7 +57,7 @@ Enumerates the action constants of the **Want** object. ## wantConstant.Entity -Enumerates the entity constants of the **Want** object. +Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. **System capability**: SystemCapability.Ability.AbilityBase @@ -72,25 +72,25 @@ Enumerates the entity constants of the **Want** object. ## wantConstant.Flags -Describes flags. +Enumerates the flags that specify how the Want will be handled. **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ------------------------------------------------------------ | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | | FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ServiceAbility is started regardless of whether the host application has been started. | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | 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_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history 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-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index d593cf5a61697773be5837287f0e63d33cff3ce8..88ffbc6255e15705d88259e65392fa9e4f6a3193 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,4 +1,4 @@ -# Ability Access Control +# @ohos.abilityAccessCtrl (Application Access Control) The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. @@ -40,7 +40,7 @@ Implements ability access control. checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> -Checks whether an application has the specified permission. This API uses a promise to return the result. +Checks whether a permission is granted to an application. This API uses a promise to return the result. **System capability**: SystemCapability.Security.AccessToken @@ -48,8 +48,8 @@ Checks whether an application has the specified permission. This API uses a prom | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Permission to check.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to check. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -71,7 +71,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { atManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); @@ -87,7 +87,7 @@ try { verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus -Verifies whether an application has the specified permission. This API returns the result synchronously. +Verifies whether a permission is granted to an application. This API returns the result synchronously. **System capability**: SystemCapability.Security.AccessToken @@ -95,8 +95,8 @@ Verifies whether an application has the specified permission. This API returns t | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. | -| permissionName | Permissions | Yes | Name of the permission to verify.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -116,7 +116,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let data = atManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` @@ -137,8 +137,8 @@ Grants a user_grant permission to an application. This API uses a promise to ret | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to grant.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** @@ -165,7 +165,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -194,10 +194,10 @@ Grants a user_grant permission to an application. This API uses an asynchronous | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| -| permissionName | Permissions | Yes | Name of the permission to grant.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -208,7 +208,8 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | -| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | +| 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100007 | Service is abnormal. | **Example** @@ -216,7 +217,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -247,8 +248,8 @@ Revokes a user_grant permission from an application. This API uses a promise to | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to revoke.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** @@ -275,7 +276,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -304,10 +305,10 @@ Revokes a user_grant permission from an application. This API uses an asynchrono | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to revoke.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -318,7 +319,8 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | -| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | +| 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100007 | Service is abnormal. | **Example** @@ -326,7 +328,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -357,8 +359,8 @@ Obtains the flags of the specified permission of an application. This API uses a | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to query.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Target permission. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -375,7 +377,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | -| 12100006 | The operation is not allowd. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | | 12100007 | Service is abnormal. | **Example** @@ -384,7 +386,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); @@ -525,7 +527,7 @@ try { verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> -Verifies whether an application has the specified permission. This API uses a promise to return the result. +Verifies whether a permission is granted to an application. This API uses a promise to return the result. > **NOTE**
You are advised to use [checkAccessToken](#checkaccesstoken9). @@ -535,8 +537,8 @@ Verifies whether an application has the specified permission. This API uses a pr | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to verify. Only valid permission names are supported.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -550,18 +552,107 @@ Verifies whether an application has the specified permission. This API uses a pr import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); ``` +### requestPermissionsFromUser9+ + +requestPermissionsFromUser(context: Context, permissions: Array<Permissions>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; + +Requests user authorization in a dialog box. This API uses an asynchronous callback to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Ability context of the application that requests the permission.| +| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +| ID| Error Message| +| -------- | -------- | +| 12100001 | Parameter invalid. | + +**Example** + + ```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"], (err, data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} + ``` + +### requestPermissionsFromUser9+ + +requestPermissionsFromUser(context: Context, permissions: Array<Permissions>) : Promise<PermissionRequestResult>; + +Requests user authorization in a dialog box. This API uses a promise to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Ability context of the application that requests the permission.| +| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +| ID| Error Message| +| -------- | -------- | +| 12100001 | Parameter invalid. | + +**Example** + + ```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }).catch((err) => { + console.info("data:" + JSON.stringify(err)); + }) +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} + ``` + ### verifyAccessToken(deprecated) verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> -Verifies whether an application has the specified permission. This API uses a promise to return the result. +Verifies whether a permission is granted to an application. This API uses a promise to return the result. > NOTE
This API is deprecated since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9). @@ -571,8 +662,8 @@ Verifies whether an application has the specified permission. This API uses a pr | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | string | Yes | Name of the permission to verify.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | string | Yes | Permission to check.| **Return value** @@ -586,7 +677,7 @@ Verifies whether an application has the specified permission. This API uses a pr import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); @@ -629,4 +720,4 @@ Defines the detailed permission grant state change information. | -------------- | ------------------------- | ---- | ---- | ------------------ | | change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. | | tokenID | number | Yes | No | Token ID of the application whose permission grant state changes are subscribed.| -| permissionName | Permissions | Yes | No | Name of the permission whose grant state is changed.| +| permissionName | Permissions | Yes | No | permission whose grant state is changed. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md index 34d4df8dd99bb528ae79d8d13de74f491f75f3db..8de8db11bbe1705c18b6e58add5631de38bed992 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -1,4 +1,4 @@ -# @ohos.accessibility.GesturePath +# @ohos.accessibility.GesturePath (Gesture Path) The **GesturePath** module provides APIs for creating gesture path information required for an accessibility application to inject gestures. diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md index 5792c44cd9fc89cf495e943a4e40463ce89281c4..f6923044ffcbf763486510364a385f61b9127eab 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -1,6 +1,6 @@ -# @ohos.accessibility.GesturePoint +# @ohos.accessibility.GesturePoint (Gesture Point) - The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to inject gestures. +The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to inject gestures. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md index 33b6f586279309125be085e8a28d5423b271fae3..673d820d17407a35991da01b0b25ee48cd51c7eb 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -1,4 +1,4 @@ -# @ohos.accessibility.config +# @ohos.accessibility.config (System Accessibility Configuration) The System Accessibility Configuration module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. diff --git a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md deleted file mode 100644 index 9fee7500eae2ec8435f0c3bdc2b48c986b14686a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ /dev/null @@ -1,379 +0,0 @@ -# AccessibilityExtensionContext - -The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities. - -You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures. - -> **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 **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. - -```js -import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' -class MainAbility extends AccessibilityExtensionAbility { - onConnect(): void { - console.log("AxExtensionAbility onConnect"); - let axContext = this.context; - } -} -``` - -## FocusDirection - -Enumerates the focus directions. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| -------- | ------- | -| up | Search for the next focusable item above the current item in focus.| -| down | Search for the next focusable item below the current item in focus.| -| left | Search for the next focusable item on the left of the current item in focus.| -| right | Search for the next focusable item on the right of the current item in focus.| -| forward | Search for the next focusable item before the current item in focus.| -| backward | Search for the next focusable item after the current item in focus.| - -## FocusType - -Enumerates the focus types. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| ------------- | ----------- | -| accessibility | Accessibility focus.| -| normal | Normal focus. | - -## Rect - -Defines a rectangle. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | --------- | -| left | number | Yes | No | Left boundary of the rectangle.| -| top | number | Yes | No | Top boundary of the rectangle.| -| width | number | Yes | No | Width of the rectangle. | -| height | number | Yes | No | Height of the rectangle. | - -## WindowType - -Enumerates the window types. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| ----------- | --------- | -| application | Application window.| -| system | System window.| - -## AccessibilityExtensionContext.setTargetBundleName - -setTargetBundleName(targetNames: Array\): Promise\; - -Sets the concerned target bundle. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | -------- | -| targetNames | Array<string> | Yes | Name of the target bundle.| - -**Return value** - -| Type | Description | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| - -**Example** - -```ts -this.context.setTargetBundleName(['com.ohos.mms']); -``` - -## AccessibilityExtensionContext.getFocusElement - -getFocusElement(isAccessibilityFocus?: boolean): Promise\; - -Obtains the focus element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | -| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| - -**Return value** - -| Type | Description | -| ----------------------------------- | ---------------------- | -| Promise<AccessibilityElement> | Promise used to return the current focus element.| - -**Example** - -```ts -this.context.getFocusElement().then(focusElement => { - console.log("AxExtensionAbility getFocusElement success"); -}) -``` - -## AccessibilityExtensionContext.getWindowRootElement - -getWindowRootElement(windowId?: number): Promise\; - -Obtains the root element of a window. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | --------------------------- | -| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| - -**Return value** - -| Type | Description | -| ----------------------------------- | ----------------------- | -| Promise<AccessibilityElement> | Promise used to return the root element.| - -**Example** - -```ts -this.context.getWindowRootElement().then(rootElement => { - console.log("AxExtensionAbility getWindowRootElement success"); -}) -``` - -## AccessibilityExtensionContext.getWindows - -getWindows(displayId?: number): Promise>; - -Obtains the list of windows visible to users. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ------------------------- | -| displayId | number | No | Screen from which the window information is obtained. If this parameter is not specified, it indicates the default home screen.| - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<AccessibilityElement>> | Promise used to return the window list. | - -**Example** - -```ts -this.context.getWindows().then(windows => { - console.log("AxExtensionAbility getWindows success"); -}) -``` - -## AccessibilityExtensionContext.injectGesture - -injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void - -Injects a gesture. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```ts -let gesturePath = new GesturePath(100); -for (let i = 0; i < 10; i++) { - let gesturePoint = new GesturePosition(100, i * 200); - gesturePath.positions.push(gesturePoint); -} -this.context.gestureInject(gesturePath, (result) => { - console.info('gestureInject result: ' + result); -}) -``` -## AccessibilityElement.attributeNames - -attributeNames\(): Promise\>; - -Obtains all attribute names of this element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<T>> | Promise used to return all attribute names of the element.| - -**Example** - -```ts -let accessibilityElement; -try { - accessibilityElement.attributeNames().then((values) => { - console.log("get attribute names success"); - }).catch((err) => { - console.log("get attribute names err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.attributeValue - -attributeValue\(attributeName: T): Promise\; - -Obtains the attribute value based on an attribute name. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| attributeName | T | Yes | Attribute name. | - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<ElementAttributeValues[T]>> | Promise used to return the attribute value.| - -**Example** - -```ts -let accessibilityElement; -try { - let attributeName = 'name'; - accessibilityElement.attributeValue(attributeName).then((value) => { - console.log("get attribute value by name success"); - }).catch((err) => { - console.log("get attribute value by name err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.actionNames - -actionNames(): Promise\>; - -Obtains the names of all actions supported by this element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<string>> | Promise used to return the names of all actions supported by the element.| - -**Example** - -```ts -let accessibilityElement; -try { - accessibilityElement.actionNames().then((values) => { - console.log("get action names success"); - }).catch((err) => { - console.log("get action names err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.performAction - -performAction(actionName: string, parameters?: object): Promise\; - -Performs an action based on the specified action name. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. | -| parameters | object | No | Parameter required for performing the target action. | - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<boolean>> | Promise used to return the result.| - -**Example** - -```ts -let accessibilityElement; -try { - - accessibilityElement.performAction('action').then((result) => { - console.info('perform action result: ' + result); - }).catch((err) => { - console.log("perform action err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -## AccessibilityElement.findElement - -findElement(type: 'content', condition: string): Promise\>; - -Queries the information about this element based on the specified information type and condition. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| type | string | Yes | Information type. The value is fixed at **'content'**. | -| condition | string | Yes | Search criteria. | - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<T>> | Promise used to return the result.| - -**Example** - -```ts -let accessibilityElement; -try { - let condition = 'keyword'; - accessibilityElement.findElement('content', condition).then((values) => { - console.log("find element success"); - }).catch((err) => { - console.log("find element err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index cf4443c60f4b58a17986bdb7ae5160fd6a95347c..8121b906b88726624f649211a6e82b05bc722023 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -1,4 +1,4 @@ -# @ohos.accessibility +# @ohos.accessibility (Accessibility) The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration. diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index 4086ca77e506b148c95fdf81e942f44642a5ffca..b0bfec0f18357dd7ce82d36b90d0f159f398c42f 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -1,6 +1,6 @@ -# @ohos.animator +# @ohos.animator (Animator) -The **animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order. +The **Animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order. > **NOTE** > @@ -40,10 +40,10 @@ Creates an **Animator** object. easing: 'friction', delay: 0, fill: 'forwards', - direction: "normal", + direction: 'normal', iterations: 3, begin: 200.0, - end: 400.0, + end: 400.0 }; animator.create(options); ``` @@ -83,10 +83,10 @@ let options = { easing: 'friction', delay: 0, fill: 'forwards', - direction: "normal", + direction: 'normal', iterations: 3, begin: 200.0, - end: 400.0, + end: 400.0 }; try { animator.reset(options); @@ -283,7 +283,7 @@ export default { easing: 'friction', delay: 0, fill: 'forwards', - direction: "normal", + direction: 'normal', iterations: 2, begin: 200.0, end: 400.0 @@ -516,7 +516,7 @@ let options = { easing: 'friction', delay: 0, fill: 'forwards', - direction: "normal", + 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 59e1e229f2e8396ae11584dee80a439ea74fdf6b..cfa11ddc30560c1ffa6a03eb8efccb8ea60b6d5b 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 @@ -1,18 +1,12 @@ -# @ohos.app.ability.Ability +# @ohos.app.ability.Ability (Ability Base Class) -The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. +This is the base class of [UIAbility](js-apis-app-ability-uiAbility.md) and [ExtensionAbility](js-apis-app-ability-extensionAbility.md). It provides the callbacks for system configuration updates and memory level updates. You cannot inherit from this base class. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Modules to Import - -```ts -import Ability from '@ohos.app.ability.Ability'; -``` - ## Ability.onConfigurationUpdate onConfigurationUpdate(newConfig: Configuration): void; @@ -23,40 +17,45 @@ Called when the configuration of the environment where the ability is running is **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| **Example** - ```ts - class myAbility extends Ability { - onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); - } - } +// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example. +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } +} ``` ## 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. +Called when the system adjusts the memory level. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **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.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| **Example** - + ```ts - class myAbility extends Ability { +// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example. +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { onMemoryLevel(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 5d6c93e6e2b45b33ca9cb7ec9976435c17fd2a56..766636a7c7d4cda38cb2b71395fd3f2575e2f784 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 @@ -1,8 +1,6 @@ -# @ohos.app.ability.AbilityConstant +# @ohos.app.ability.AbilityConstant (AbilityConstant) -The **AbilityConstant** module provides ability launch parameters. - -The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. +The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. > **NOTE** > @@ -17,31 +15,48 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ## Attributes +## AbilityConstant.LaunchParam + +Defines the parameters for starting an ability. + **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason, which is an enumerated type.| +| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit, which is an enumerated type.| ## AbilityConstant.LaunchReason -Enumerates the ability launch reasons. +Enumerates the initial ability launch reasons. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| -| START_ABILITY | 1 | Ability startup.| -| CALL | 2 | Call.| -| CONTINUATION | 3 | Ability continuation.| -| APP_RECOVERY | 4 | Application recovery.| +| 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).| +| 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.| + +**Example** +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onCreate(want, launchParam) { + if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) { + console.log("The ability has been started by the way of startAbility."); + } + } +} +``` ## AbilityConstant.LastExitReason -Enumerates reasons for the last exit. +Enumerates the reasons for the last exit. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -49,12 +64,25 @@ Enumerates reasons for the last exit. | ----------------------------- | ---- | ------------------------------------------------------------ | | UNKNOWN | 0 | Unknown reason.| | ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| -| NORMAL | 2 | Normal status.| +| NORMAL | 2 | The ability exits normally.| +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onCreate(want, launchParam) { + if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) { + console.log("The ability has exit last because the ability was not responding."); + } + } +} +``` ## AbilityConstant.OnContinueResult -Enumerates ability continuation results. +Enumerates the ability continuation results. You can use it together with [onContinue(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncontinue) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -64,9 +92,21 @@ Enumerates ability continuation results. | REJECT | 1 | Continuation denied.| | MISMATCH | 2 | Mismatch.| +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onContinue(wantParam) { + return AbilityConstant.OnConinueResult.AGREE; + } +} +``` + ## AbilityConstant.WindowMode -Enumerates the window modes in which an ability can be displayed at startup. +Enumerates the window modes in which an ability can be displayed at startup. It can be used in **startAbility()** to specify the window mode when the ability is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -78,36 +118,81 @@ Enumerates the window modes in which an ability can be displayed at startup. | WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | | WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| +**Example** + +```ts +let want = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" +}; +let option = { + windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN +}; + +// Ensure that the context is obtained. +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)); +}); +``` + ## AbilityConstant.MemoryLevel -Enumerates the memory levels. +Enumerates the memory levels. You can use it in [onMemoryLevel(level)](js-apis-app-ability-ability.md#abilityonmemorylevel) of [Ability](js-apis-app-ability-ability.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value| Description | -| --- | --- | --- | -| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. | -| MEMORY_LEVEL_LOW | 1 | Low memory usage. | +| --- | --- | --- | +| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage.| +| MEMORY_LEVEL_LOW | 1 | Low memory usage. | | MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onMemoryLevel(level) { + if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) { + console.log("The memory of device is critical, please release some memory."); + } + } +} +``` + ## AbilityConstant.OnSaveResult -Enumerates the result types for the operation of saving application data. +Enumerates the result types for the operation of saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | -| ALL_AGREE | 0 | Agreed to save the status.| +| ALL_AGREE | 0 | Always agreed to save the status.| | CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| | CONTINUATION_MISMATCH | 2 | Continuation mismatch.| | RECOVERY_AGREE | 3 | Agreed to restore the saved status.| | RECOVERY_REJECT | 4 | Rejected to restore the saved state.| -| ALL_REJECT | 5 | Rejected to save the status.| +| ALL_REJECT | 5 | Always rejected to save the status.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onSaveState(reason, wantParam) { + return AbilityConstant.OnSaveResult.ALL_AGREE; + } +} +``` ## AbilityConstant.StateType -Enumerates the scenarios for saving application data. +Enumerates the scenarios for saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -115,3 +200,18 @@ Enumerates the scenarios for saving application data. | ----------------------------- | ---- | ------------------------------------------------------------ | | CONTINUATION | 0 | Saving the status in continuation.| | APP_RECOVERY | 1 | Saving the status in application recovery.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onSaveState(reason, wantParam) { + if (reason === AbilityConstant.StateType.CONTINUATION) { + console.log("Save the ability data when the ability continuation."); + } + return AbilityConstant.OnSaveResult.ALL_AGREE; + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md index 78fb6181c03380c6d69eb31318d1d459dec307fe..5cfa437047868a9183ae4bb4f41ff42eec47f5d7 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 @@ -1,26 +1,27 @@ -# @ohos.app.ability.abilityDelegatorRegistry +# @ohos.app.ability.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. +**AbilityDelegatorRegistry**, a module of the [Test Framework](../../ability-deprecated/ability-delegator.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters. > **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 can be used only in the test framework. ## Modules to Import ```ts -import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; ``` ## AbilityLifecycleState -Enumerates the ability lifecycle states. +Enumerates the ability lifecycle states. It can be used in [getAbilityState(ability)](js-apis-inner-application-abilityDelegator.md#getabilitystate9) of [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) to return different ability lifecycle states. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------- | ---- | --------------------------- | -| UNINITIALIZED | 0 | The ability is in an invalid state. | +| UNINITIALIZED | 0 | The ability is in an invalid state. | | CREATE | 1 | The ability is created.| | FOREGROUND | 2 | The ability is running in the foreground. | | BACKGROUND | 3 | The ability is running in the background. | @@ -30,7 +31,7 @@ Enumerates the ability lifecycle states. getAbilityDelegator(): AbilityDelegator -Obtains the **AbilityDelegator** object of the application. +Obtains an [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) object. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -38,20 +39,33 @@ Obtains the **AbilityDelegator** object of the application. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| +| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule the functionalities of the test framework.| **Example** ```ts -var abilityDelegator; -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); + +let want = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" +}; +abilityDelegator.startAbility(want, (err) => { + if (err.code !== 0) { + console.log("Success start ability."); + } else { + console.log("Failed start ability, error: " + JSON.stringify(err)); + } +}) ``` ## AbilityDelegatorRegistry.getArguments getArguments(): AbilityDelegatorArgs -Obtains the **AbilityDelegatorArgs** object of the application. +Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) object. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -64,8 +78,11 @@ Obtains the **AbilityDelegatorArgs** object of the application. **Example** ```ts -var args = AbilityDelegatorRegistry.getArguments(); +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +let args = AbilityDelegatorRegistry.getArguments(); console.info("getArguments bundleName:" + args.bundleName); +console.info("getArguments parameters:" + JSON.stringify(args.parameters)); console.info("getArguments testCaseNames:" + args.testCaseNames); console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); ``` 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 f3e6e08396d0b819efd6acda39218af497e83ef9..84be19350707fee37328ff8040b2986588afd2f8 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 @@ -1,6 +1,6 @@ -# @ohos.app.ability.abilityLifecycleCallback +# @ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback) -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module defines the callbacks to receive lifecycle changes of [ApplicationContext](js-apis-inner-application-applicationContext.md). The callbacks include [onAbilityCreate](#abilitylifecyclecallbackonabilitycreate), [onWindowStageCreate](#abilitylifecyclecallbackonwindowstagecreate), [onWindowStageActive](#abilitylifecyclecallbackonwindowstageactive), [onWindowStageInactive](#abilitylifecyclecallbackonwindowstageinactive), [onWindowStageDestroy](#abilitylifecyclecallbackonwindowstagedestroy), [onAbilityDestroy](#abilitylifecyclecallbackonabilitydestroy), [onAbilityForeground](#abilitylifecyclecallbackonabilityforeground), [onAbilityBackground](#abilitylifecyclecallbackonabilitybackground), and [onAbilityContinue](#abilitylifecyclecallbackonabilitycontinue). > **NOTE** > @@ -25,10 +25,18 @@ Called when an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageCreate @@ -40,11 +48,19 @@ Called when the window stage of an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageActive @@ -56,11 +72,19 @@ Called when the window stage of an ability gains focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageInactive @@ -72,11 +96,19 @@ Called when the window stage of an ability loses focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive."); + } +}; +``` ## AbilityLifecycleCallback.onWindowStageDestroy @@ -88,11 +120,19 @@ Called when the window stage of an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityDestroy @@ -104,10 +144,18 @@ Called when an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityForeground @@ -119,10 +167,18 @@ Called when an ability is switched from the background to the foreground. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityBackground @@ -134,10 +190,18 @@ Called when an ability is switched from the foreground to the background. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground."); + } +}; +``` ## AbilityLifecycleCallback.onAbilityContinue @@ -149,63 +213,91 @@ Called when an ability is continued on another device. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [UIAbility](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue."); + } +}; +``` + +## Usage of AbilityLifecycleCallback **Example** - - - ```ts - import UIAbility from "@ohos.app.ability.UIAbility"; - - export default class MyAbility extends UIAbility { - onCreate() { - console.log("MyAbility onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); - }, - onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); - }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback 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. - let lifecycleid = applicationContext.on("abilityLifecycle", AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - }, - onDestroy() { - let applicationContext = this.context.getApplicationContext(); - applicationContext.off("abilityLifecycle", lifecycleid, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - } - } - ``` + +MyFirstAbility.ts +```ts +import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; +import AbilityStage from "@ohos.app.ability.AbilityStage"; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured. +let abilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate."); + }, + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate."); + }, + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive."); + }, + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive."); + }, + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy."); + }, + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy."); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground."); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground."); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue."); + } +}; + +export default class MyFirstAbility extends UIAbility { + onCreate() { + console.log("MyAbilityStage onCreate"); + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Register the listener for the ability lifecycle changes through the applicationContext object. + try { + globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + } catch (paramError) { + console.log("error: " + paramError.code + " ," + paramError.message); + } + } +} +``` + +MySecondAbility.ts +```ts +import UIAbility from "ohos.app.ability.UIAbility"; + +export default class MySecondAbility extends UIAbility { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + // 3. Deregister the listener for the environment changes through the applicationContext object. + applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => { + if (error.code != 0) { + console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error)); + } 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 0a191c0038f3a5811018346ffe779dc558b3ad20..f7f9c49a4cdf1c9e8c92ad8b7c8bd977df525477 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 @@ -1,6 +1,6 @@ -# @ohos.app.ability.abilityManager +# @ohos.app.ability.abilityManager (AbilityManager) -The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. +The **AbilityManager** module provides APIs for obtaining, adding, and updating ability running information and state information. > **NOTE** > @@ -10,24 +10,24 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ## Modules to Import ```ts -import AbilityManager from '@ohos.app.ability.abilityManager' +import abilityManager from '@ohos.app.ability.abilityManager'; ``` ## AbilityState -Enumerates the ability states. +Enumerates the ability states. This enum can be used together with [AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md) to return the ability state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This enum is an internal definition of a system API and cannot be called by third-party applications. | Name| Value| Description| | -------- | -------- | -------- | | INITIAL | 0 | The ability is in the initial state.| | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | +| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | ## updateConfiguration @@ -43,25 +43,42 @@ Updates the configuration. This API uses an asynchronous callback to return the | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.| +| callback | AsyncCallback\ | Yes | Callback used to return the API call result. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var config = { - language: 'chinese' -} +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. + displayId: 1, // The application is displayed on the display with ID 1. + hasPointerDevice: true, // A pointer device is connected. +}; try { - abilitymanager.updateConfiguration(config, () => { - console.log('------------ updateConfiguration -----------'); - }) + abilityManager.updateConfiguration(config, (err) => { + if (err.code !== 0) { + console.log("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.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -79,32 +96,45 @@ Updates the configuration. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.| **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var config = { - language: 'chinese' -} +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. + displayId: 1, // The application is displayed on the display with ID 1. + hasPointerDevice: true, // A pointer device is connected. +}; try { - abilitymanager.updateConfiguration(config).then(() => { - console.log('updateConfiguration success'); - }).catch((err) => { - console.log('updateConfiguration fail'); - }) + abilityManager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success.'); + }).catch((err) => { + console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); + }) } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -122,20 +152,32 @@ Obtains the ability running information. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; try { - abilitymanager.getAbilityRunningInfos((err,data) => { - console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); - }); + abilityManager.getAbilityRunningInfos((err, data) => { + if (err.code !== 0) { + console.log("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.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -153,22 +195,30 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; - +import abilityManager from '@ohos.app.ability.abilityManager'; + try { - abilitymanager.getAbilityRunningInfos().then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) - }).catch((err) => { - console.log("getAbilityRunningInfos err: " + err) - }); + abilityManager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)) + }).catch((err) => { + console.log("getAbilityRunningInfos fail, err: " + JSON.stringify(err)); + }); } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -176,7 +226,7 @@ try { getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void -Obtains the extension running information. This API uses an asynchronous callback to return the result. +Obtains the ExtensionAbility running information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -186,23 +236,35 @@ Obtains the extension running information. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | Yes| Maximum number of messages that can be obtained.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 231-1.| +| callback | AsyncCallback\> | Yes | Callback used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var upperLimit = 0; +let upperLimit = 10; try { - abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); - }); + abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => { + if (err.code !== 0) { + console.log("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.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -210,7 +272,7 @@ try { getExtensionRunningInfos(upperLimit: number): Promise\> -Obtains the extension running information. This API uses a promise to return the result. +Obtains the ExtensionAbility running information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -220,30 +282,38 @@ Obtains the extension running information. This API uses a promise to return the | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| upperLimit | number | Yes| Maximum number of messages that can be obtained.| +| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 231-1.| **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -var upperLimit = 0; +let upperLimit = 10; try { - abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { - console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); - }).catch((err) => { - console.log("getAbilityRunningInfos err: " + err); - }) + abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { + console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); + }) } catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -259,21 +329,28 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; - -try { - abilitymanager.getTopAbility((err,data) => { - console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); - }); -} catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); -} +import abilityManager from '@ohos.app.ability.abilityManager'; + +abilityManager.getTopAbility((err, data) => { + if (err.code !== 0) { + console.log("getTopAbility fail, err: " + JSON.stringify(err)); + } else { + console.log("getTopAbility success, data: " + JSON.stringify(data)); + } +}); ``` ## getTopAbility @@ -288,21 +365,24 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Type | Description | | ---------------------------------------- | ------- | -| Promise\| Promise used to return the result.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -import abilitymanager from '@ohos.app.ability.abilityManager'; +import abilityManager from '@ohos.app.ability.abilityManager'; -try { - abilitymanager.getTopAbility().then((data) => { - console.log("getTopAbility data: " + JSON.stringify(data)); - }).catch((err) => { - console.log("getTopAbility err: " + err); - }) -} catch (paramError) { - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); -} +abilityManager.getTopAbility().then((data) => { + console.log("getTopAbility success, data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getTopAbility fail, err: " + JSON.stringify(err)); +}) ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md index b1226842409c7d03c82d25d33319042a716b9d86..50feb82791f8992894641a296d6cb831fdc86680 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md @@ -1,4 +1,4 @@ -# @ohos.app.ability.AbilityStage +# @ohos.app.ability.AbilityStage (AbilityStage) **AbilityStage** is a runtime class for HAP files. @@ -25,13 +25,15 @@ Called when the application is created. **Example** - ```ts - class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage.onCreate is called") - } - } - ``` +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage.onCreate is called"); + } +} +``` ## AbilityStage.onAcceptWant @@ -44,9 +46,9 @@ Called when a specified ability is started. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| **Return value** @@ -56,14 +58,16 @@ Called when a specified ability is started. **Example** - ```ts - class MyAbilityStage extends AbilityStage { - onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; - } - } - ``` +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onAcceptWant(want) { + console.log("MyAbilityStage.onAcceptWant called"); + return "com.example.test"; + } +} +``` ## AbilityStage.onConfigurationUpdate @@ -82,13 +86,15 @@ Called when the global configuration is updated. **Example** - ```ts - class MyAbilityStage extends AbilityStage { - onConfigurationUpdate(config) { - console.log('onConfigurationUpdate, language:' + config.language); - } - } - ``` +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, language:' + config.language); + } +} +``` ## AbilityStage.onMemoryLevel @@ -106,22 +112,24 @@ Called when the system has decided to adjust the memory level. For example, this **Example** - ```ts - class MyAbilityStage extends AbilityStage { +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); } - } - ``` +} +``` ## AbilityStage.context context: AbilityStageContext; -Describes the configuration information about the context. +Defines the context of **AbilityStage**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Description | | ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.| +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | The context is obtained in the callback invoked when initialization is performed during ability startup.| 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 b6fae35d6d03575442b1223c63cbcd4150773bb9..840a395eac9e17558918dd7466aa9e0b178b1c4d 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.appManager +# @ohos.app.ability.appManager (appManager) The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. @@ -12,7 +12,7 @@ The **appManager** module implements application management. You can use the API import appManager from '@ohos.app.ability.appManager'; ``` -## appManager.isRunningInStabilityTest9+ +## appManager.isRunningInStabilityTest static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void @@ -22,21 +22,34 @@ 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.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest((err, flag) => { - console.log('startAbility result:' + JSON.stringify(err)); - }) - ``` +```ts +import appManager from '@ohos.app.ability.appManager'; -## appManager.isRunningInStabilityTest9+ +appManager.isRunningInStabilityTest((err, flag) => { + if (err.code !== 0) { + console.log("isRunningInStabilityTest faile, err: " + JSON.stringify(err)); + } else { + console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); + } +}) +``` + + +## appManager.isRunningInStabilityTest static isRunningInStabilityTest(): Promise<boolean> @@ -48,18 +61,27 @@ Checks whether this application is undergoing a stability test. This API uses a | 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.| + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest().then((flag) => { - console.log('success:' + JSON.stringify(flag)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +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)); +}); +``` ## appManager.isRamConstrainedDevice @@ -74,17 +96,27 @@ Checks whether this application is running on a RAM constrained device. This API | 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.| + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.isRamConstrainedDevice().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +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)); +}); +``` ## appManager.isRamConstrainedDevice @@ -96,18 +128,31 @@ 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.| + | Type| Description| + | -------- | -------- | + | AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.isRamConstrainedDevice((err, data) => { - console.log('startAbility result failed:' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRamConstrainedDevice((err, data) => { + if (err.code !== 0) { + console.log("isRamConstrainedDevice faile, err: " + JSON.stringify(err)); + } else { + console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); + } +}) +``` ## appManager.getAppMemorySize @@ -121,17 +166,27 @@ Obtains the memory size of this application. This API uses a promise to return t | Type| Description| | -------- | -------- | - | Promise<number> | Size of the application memory.| + | Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getAppMemorySize().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +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)); +}); +``` ## appManager.getAppMemorySize @@ -143,20 +198,33 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | Yes| Size of the application memory.| + | Type| Description| + | -------- | -------- | + |AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getAppMemorySize((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` -## appManager.getProcessRunningInformation9+ +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getAppMemorySize((err, data) => { + if (err.code !== 0) { + console.log("getAppMemorySize faile, err: " + JSON.stringify(err)); + } else { + console.log("The size of app memory is:" + JSON.stringify(data)); + } +}) +``` + +## appManager.getProcessRunningInformation getProcessRunningInformation(): Promise\>; @@ -172,17 +240,27 @@ Obtains information about the running processes. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the process information.| +| Promise\> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getProcessRunningInformation().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getProcessRunningInformation().then((data) => { + console.log("The process running information is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` ## appManager.getProcessRunningInformation9+ @@ -198,18 +276,31 @@ Obtains information about the running processes. This API uses an asynchronous c **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the process information.| +| 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.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getProcessRunningInformation((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getProcessRunningInformation((err, data) => { + if (err.code !== 0) { + console.log("getProcessRunningInformation faile, err: " + JSON.stringify(err)); + } else { + console.log("The process running information is:" + JSON.stringify(data)); + } +}) +``` ## appManager.on @@ -227,37 +318,52 @@ Registers an observer to listen for the state changes of all applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| + +**Return value** + +| Type| Description| +| --- | --- | +| number | Digital code of the observer, which will be used in **off()** to deregister the observer.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var applicationStateObserver = { + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); }, onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); }, onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); }, onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); }, onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - } - try { - const observerCode = app.on(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); - } - - ``` +} +try { + const observerId = appManager.on('applicationState', applicationStateObserver); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` ## appManager.on @@ -275,39 +381,55 @@ Registers an observer to listen for the state changes of a specified application | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| -| bundleNameList | Array | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| +| bundleNameList | `Array` | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| + +**Return value** + +| Type| Description| +| --- | --- | +| number | Digital code of the observer, which will be used in **off()** to deregister the observer.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var applicationStateObserver = { + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); }, onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); }, onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); }, onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); }, onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - } - var bundleNameList = ['bundleName1', 'bundleName2']; - try { - const observerCode = app.on("applicationState", applicationStateObserver, bundleNameList); - console.log('-------- observerCode: ---------', observerCode); - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); - } +} +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} `); +} +``` - ``` ## appManager.off off(type: "applicationState", observerId: number, callback: AsyncCallback\): void; @@ -321,29 +443,68 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observerId | number | Yes| Digital code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var observerId = 100; - function unregisterApplicationStateObserverCallback(err) { - if (err) { - console.log('------------ unregisterApplicationStateObserverCallback ------------', err); - } +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observeId = 0; + +// 1. Register an application state observer. +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); } - try { - app.off(observerId, unregisterApplicationStateObserverCallback); - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); +} +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} `); +} + +// 2. Deregister the application state observer. +function unregisterApplicationStateObserverCallback(err) { + if (err.code !== 0) { + console.log("unregisterApplicationStateObserverCallback faile, err: " + JSON.stringify(err)); + } else { + console.log("unregisterApplicationStateObserverCallback success."); } - ``` +} +try { + appManager.off("applicationState", observerId, unregisterApplicationStateObserverCallback); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); +} +``` ## appManager.off @@ -361,38 +522,73 @@ Deregisters the application state observer. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observerId | number | Yes| Digital code of the observer.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```js - var observerId = 100; - - try { - app.off(observerId) - .then((data) => { - console.log('----------- unregisterApplicationStateObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) - } catch (paramError) { - console.log('error: ' + paramError.code + ', ' + paramError.message); + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observeId = 0; + +// 1. Register an application state observer. +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + 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} `); +} + +// 2. Deregister the application state observer. +try { + appManager.off("applicationState", observerId).then((data) => { + console.log("unregisterApplicationStateObserver success, data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("unregisterApplicationStateObserver faile, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); +} +``` ## appManager.getForegroundApplications getForegroundApplications(callback: AsyncCallback\>): void; -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -400,96 +596,44 @@ Obtains applications that are running in the foreground. This API uses an asynch **System API**: This is a system API and cannot be called by third-party applications. -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| - -**Example** - - ```js - function getForegroundApplicationsCallback(err, data) { - if (err) { - console.log('--------- getForegroundApplicationsCallback fail ---------', err.code + ': ' + err.message); - } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) - } - } - app.getForegroundApplications(getForegroundApplicationsCallback); - ``` - -unregisterApplicationStateObserver(observerId: number): Promise\; - -Deregisters the application state observer. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER +**Error codes** -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | -**System API**: This is a system API and cannot be called by third-party applications. +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observerId | number | Yes| Numeric code of the observer.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| +| callback | AsyncCallback\> | Yes| Callback used to return the API call result and an array holding the application state data. You can perform error handling or custom processing in this callback.| **Example** - - ```ts - var observerId = 100; - app.unregisterApplicationStateObserver(observerId) - .then((data) => { - console.log('----------- unregisterApplicationStateObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) - ``` - -## appManager.getForegroundApplications9+ - -getForegroundApplications(callback: AsyncCallback\>): void; - -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO -**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| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| +```ts +import appManager from '@ohos.app.ability.appManager'; -**Example** - - ```ts - function getForegroundApplicationsCallback(err, data) { - if (err) { - console.log('--------- getForegroundApplicationsCallback fail ---------', err); +function getForegroundApplicationsCallback(err, data) { + if (err.code !== 0) { + console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err)); } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) + console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data)); } - } - app.getForegroundApplications(getForegroundApplicationsCallback); - ``` +} +try { + appManager.getForegroundApplications(getForegroundApplicationsCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## appManager.getForegroundApplications9+ +## appManager.getForegroundApplications getForegroundApplications(): Promise\>; -Obtains applications that are running in the foreground. This API uses a promise to return the result. +Obtains applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -501,27 +645,35 @@ Obtains applications that are running in the foreground. This API uses a promise | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the application state data.| +| Promise\> | Promise used to return an array holding the application state data| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - app.getForegroundApplications() - .then((data) => { - console.log('--------- getForegroundApplications success -------', data); - }) - .catch((err) => { - console.log('--------- getForegroundApplications fail -------', err); - }) - ``` - -## appManager.killProcessWithAccount9+ + +```ts +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)); +}) +``` + +## appManager.killProcessWithAccount killProcessWithAccount(bundleName: string, accountId: number): Promise\ Kills a process by bundle name and account ID. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -529,27 +681,39 @@ Kills a process by bundle name and account ID. This API uses a promise to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -var bundleName = 'bundleName'; -var accountId = 0; -app.killProcessWithAccount(bundleName, accountId) - .then((data) => { - console.log('------------ killProcessWithAccount success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessWithAccount fail ------------', err); - }) +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +let accountId = 0; +try { + appManager.killProcessWithAccount(bundleName, accountId).then(() => { + console.log("killProcessWithAccount success"); + }).catch((err) => { + console.log("killProcessWithAccount fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` -## appManager.killProcessWithAccount9+ +## appManager.killProcessWithAccount killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void @@ -559,32 +723,42 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **System API**: This is a system API and cannot be called by third-party applications. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| + | bundleName | string | Yes| Bundle name.| | 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.| + | callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts -var bundleName = 'bundleName'; -var accountId = 0; +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +let accountId = 0; function killProcessWithAccountCallback(err, data) { - if (err) { - console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); - } else { - console.log('------------- killProcessWithAccountCallback success, data: --------------', data); - } + if (err.code !== 0) { + console.log("killProcessWithAccountCallback fail, err: " + JSON.stringify(err)); + } else { + console.log("killProcessWithAccountCallback success."); + } } -app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); ``` -## appManager.killProcessesByBundleName9+ +## appManager.killProcessesByBundleName killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); @@ -600,24 +774,38 @@ Kills a process by bundle name. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - var bundleName = 'bundleName'; - function killProcessesByBundleNameCallback(err, data) { - if (err) { - console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +function killProcessesByBundleNameCallback(err, data) { + if (err.code !== 0) { + console.log("killProcessesByBundleNameCallback fail, err: " + JSON.stringify(err)); } else { - console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); + console.log("killProcessesByBundleNameCallback success."); } - } - app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); - ``` +} +try { + appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## appManager.killProcessesByBundleName9+ +## appManager.killProcessesByBundleName killProcessesByBundleName(bundleName: string): Promise\; @@ -633,7 +821,7 @@ Kills a process by bundle name. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** @@ -641,20 +829,32 @@ Kills a process by bundle name. This API uses a promise to return the result. | -------- | -------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + **Example** - - ```ts -var bundleName = 'bundleName'; -app.killProcessesByBundleName(bundleName) - .then((data) => { - console.log('------------ killProcessesByBundleName success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessesByBundleName fail ------------', err); - }) - ``` - -## appManager.clearUpApplicationData9+ + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +try { + appManager.killProcessesByBundleName(bundleName).then((data) => { + console.log("killProcessesByBundleName success."); + }).catch((err) => { + console.log("killProcessesByBundleName fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appManager.clearUpApplicationData clearUpApplicationData(bundleName: string, callback: AsyncCallback\); @@ -670,24 +870,38 @@ Clears application data by bundle name. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - var bundleName = 'bundleName'; - function clearUpApplicationDataCallback(err, data) { + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +function clearUpApplicationDataCallback(err, data) { if (err) { - console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); + console.log("clearUpApplicationDataCallback fail, err: " + JSON.stringify(err)); } else { - console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); + console.log("clearUpApplicationDataCallback success."); } - } - app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); - ``` +} +try { + appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## appManager.clearUpApplicationData9+ +## appManager.clearUpApplicationData clearUpApplicationData(bundleName: string): Promise\; @@ -703,28 +917,42 @@ Clears application data by bundle name. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** | Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** - - ```ts - var bundleName = 'bundleName'; - app.clearUpApplicationData(bundleName) - .then((data) => { - console.log('------------ clearUpApplicationData success ------------', data); - }) - .catch((err) => { - console.log('------------ clearUpApplicationData fail ------------', err); + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +try { + appManager.clearUpApplicationData(bundleName).then((data) => { + console.log("clearUpApplicationData success."); + }).catch((err) => { + console.log("clearUpApplicationData fail, err: " + JSON.stringify(err)); }) - ``` +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` -## ApplicationState9+ +## ApplicationState + +Enumerates the application states. This enum can be used together with [AbilityStateData](js-apis-inner-application-appStateData.md) to return the application state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -738,7 +966,9 @@ Clears application data by bundle name. This API uses a promise to return the re | STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | | STATE_DESTROY | 5 | State indicating that the application is destroyed. | -## ProcessState9+ +## ProcessState + +Enumerates the process states. This enum can be used together with [ProcessData](js-apis-inner-application-processData.md) to return the process state. **System capability**: SystemCapability.Ability.AbilityRuntime.Core 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 80c507b83ab0012aafbdc9745810730a54997293..e066ac119344842ffce617fd7934efa3712d895f 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.appRecovery +# @ohos.app.ability.appRecovery (appRecovery) The **appRecovery** module provides APIs for recovering faulty applications. @@ -8,13 +8,13 @@ The **appRecovery** module provides APIs for recovering faulty applications. ## Modules to Import ```ts -import appRecovery from '@ohos.app.ability.appRecovery' +import appRecovery from '@ohos.app.ability.appRecovery'; ``` ## appRecovery.RestartFlag -Enumerates the application restart options used in [enableAppRecovery](#apprecoveryenableapprecovery). +Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -28,7 +28,7 @@ Enumerates the application restart options used in [enableAppRecovery](#apprecov ## appRecovery.SaveOccasionFlag -Enumerates the scenarios for saving the application state, which is used in [enableAppRecovery](#apprecoveryenableapprecovery). +Enumerates the scenarios for saving the application state. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -39,7 +39,7 @@ Enumerates the scenarios for saving the application state, which is used in [ena ## appRecovery.SaveModeFlag -Enumerates the application state saving modes used in [enableAppRecovery](#apprecoveryenableapprecovery). +Enumerates the application state saving modes. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -50,7 +50,7 @@ Enumerates the application state saving modes used in [enableAppRecovery](#appre ## appRecovery.enableAppRecovery -enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; +enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void; Enables application recovery. @@ -67,9 +67,17 @@ Enables application recovery. **Example** ```ts -export default class MyAbilityStage extends AbilityStage { +import appRecovery from '@ohos.app.ability.appRecovery'; +import AbilityStage from '@ohos.app.ability.AbilityStage'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class MyAbility extends UIAbility { onCreate() { - appRecovery.enableAppRecovery(RestartFlag::ALWAYS_RESTART, SaveOccasionFlag::SAVE_WHEN_ERROR, SaveModeFlag::SAVE_WITH_FILE); + appRecovery.enableAppRecovery( + appRecovery.RestartFlag::ALWAYS_RESTART, + appRecovery.SaveOccasionFlag::SAVE_WHEN_ERROR, + appRecovery.SaveModeFlag::SAVE_WITH_FILE + ); } } ``` @@ -86,13 +94,21 @@ Restarts the application. This API can be used together with APIs of [errorManag **Example** ```ts -var observer = { +import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + +let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) appRecovery.restartApp(); } -} +}; +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` ## appRecovery.saveAppState @@ -107,15 +123,24 @@ Saves the application state. This API can be used together with APIs of [errorMa | Type| Description| | -------- | -------- | -| boolean | Whether the saving is successful.| +| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.| **Example** ```ts -var observer = { +import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + +let observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) appRecovery.saveAppState(); } +}; + +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md index 23184c6036f12bd3c914d7b500fece72afafc538..5cc9b61b90fb3072aacf530fdaee0ae2633f7ac0 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.common +# @ohos.app.ability.common (Context) The **Common** module provides all level-2 module APIs for developers to export. @@ -15,21 +15,21 @@ import common from '@ohos.app.ability.common' **System capability**: SystemCapability.Ability.AbilityBase -| Name | Type | Mandatory| Description | -| ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No | Level-2 module **UIAbilityContext**. | -| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.| -| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.| -| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.| -| Context | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.| -| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.| -| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.| -| AreaMode | [AreaMode](#areamode) | No | Enumerated values of **AreaMode**.| -| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.| -| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.| -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | No | Level-2 module **PacMap**.| -| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | Level-2 module **AbilityResult**.| -| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | Level-2 module **ConnectOptions**.| +| Name | Type | Description | +| ----------- | -------------------- | ------------------------------------------------------------ | +| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Level-2 module **UIAbilityContext**. | +| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Level-2 module **AbilityStageContext**.| +| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | Level-2 module **ApplicationContext**.| +| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | Level-2 module **BaseContext**.| +| 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**.| +| 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 @@ -52,11 +52,11 @@ let connectOptions: common.ConnectOptions; ## AreaMode -Defines the area where the file to be access is located. Each area has its own content. +Enumerates the data encryption levels. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | --------------- | ---- | --------------- | -| EL1 | 0 | Device-level encryption area. | -| EL2 | 1 | User credential encryption area. The default value is **EL2**.| +| 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 90075377af701150b8de77600ed3ae3808b50d41..88aab2d4026afac5edaf8c3c7ff58033976e3e66 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,4 +1,4 @@ -# @ohos.app.ability.Configuration +# @ohos.app.ability.Configuration (Configuration) The **Configuration** module defines environment change information. @@ -14,34 +14,42 @@ 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.| +| 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 | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity | ScreenDensity | 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).| +| 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).| | 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.| For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file. -**Example** - +**Example** + ```ts - let envCallback = { - onConfigurationUpdated(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; + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let envCallback = { + onConfigurationUpdated(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; + } + }; + try { + let applicationContext = this.context.getApplicationContext(); + let callbackId = applicationContext.on("environment", envCallback); + console.log("callbackId: " + callbackId); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } } - }; - try { - var callbackId = applicationContext.on("environment", envCallback); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md index 24b6b4745b1ba606cdb40c741fa2fcf10376cc06..bd56e256603930f874c9ba2c064462c8fad594a8 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.ConfigurationConstant +# @ohos.app.ability.ConfigurationConstant (ConfigurationConstant) The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. @@ -25,7 +25,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | COLOR_MODE_LIGHT | 1 | Light mode.| -## ConfigurationConstant.Direction9+ +## ConfigurationConstant.Direction You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. @@ -38,7 +38,7 @@ You can obtain the value of this constant by calling the **ConfigurationConstant | DIRECTION_HORIZONTAL | 1 | Horizontal direction.| -## ConfigurationConstant.ScreenDensity9+ +## ConfigurationConstant.ScreenDensity You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. diff --git a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md index dc1b5a1430c8c063de23cc87126ff891d5363b80..0c39c8fa01fe62a537614287f3d27645c8b0f354 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md @@ -1,6 +1,6 @@ -# @ohos.app.ability.contextConstant +# @ohos.app.ability.contextConstant (ContextConstant) -The **ContextConstant** module defines data encryption levels. +The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of data encryption levels. > **NOTE** > @@ -19,7 +19,7 @@ You can obtain the value of this constant by calling the **ContextConstant.AreaM **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| EL1 | 0 | Device-level encryption area.| -| EL2 | 1 | User credential encryption area.| +| 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-dataUriUtils.md b/en/application-dev/reference/apis/js-apis-app-ability-dataUriUtils.md index a13e0f73daea27a21a57b6af321dcc9ee8afa038..9a869f051a08c4a79c9dac58e8f4dceb9dc4658b 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 @@ -1,6 +1,6 @@ -# ohos.app.ability.dataUriUtils +# @ohos.app.ability.dataUriUtils (DataUriUtils) -The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. 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. +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. > **NOTE** > @@ -24,13 +24,13 @@ Obtains the ID attached to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object from which the ID is to be obtained.| +| uri | string | Yes | Target URI object.| **Return value** | Type | Description | | ------ | ------------------------ | -| number | ID obtained from the URI object.| +| number | ID obtained.| **Example** @@ -49,7 +49,7 @@ try { attachId(uri: string, id: number): string -Attaches an ID to the end of a given URI. It can be used to generate a new URI. +Attaches an ID to the end of a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -57,7 +57,7 @@ Attaches an ID to the end of a given URI. It can be used to generate a new URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object to which an ID is to be attached.| +| uri | string | Yes | Target URI object.| | id | number | Yes | ID to be attached. | **Return value** @@ -69,11 +69,11 @@ Attaches an ID to the end of a given URI. It can be used to generate a new URI. **Example** ```ts -var idint = 1122; +var id = 1122; try { var uri = dataUriUtils.attachId( "com.example.dataUriUtils", - idint, + id, ) console.info('attachId the uri is: ' + uri) } catch (err) { @@ -130,7 +130,7 @@ Updates the ID in a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------- | -| uri | string | Yes | URI object to be updated.| +| uri | string | Yes | Target URI object.| | id | number | Yes | New ID. | **Return value** @@ -144,10 +144,10 @@ Updates the ID in a given URI. ```ts try { - var idint = 1122; + var id = 1122; var uri = dataUriUtils.updateId( - "com.example.dataUriUtils", - idint + "com.example.dataUriUtils/1221", + id ) } catch (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 1208aeb8dabdbc09b77a9395e0ad313b1bf7e8cd..0cb95a9abfd6b90f1efacc431070ef6b3397e1e6 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.EnvironmentCallback +# @ohos.app.ability.EnvironmentCallback (EnvironmentCallback) The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. @@ -33,18 +33,18 @@ Called when the system environment changes. ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from "@ohos.app.ability.Ability"; var callbackId; -export default class MyAbility extends Ability { +export default class MyAbility extends UIAbility { onCreate() { console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); - }, + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; 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 3fb88a2b8ad93d3dbb5adf627f105d117ca86fda..e543a93e9ceb5af52f3cdb939a0cfd5d24145968 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 @@ -1,13 +1,13 @@ -# @ohos.app.ability.errorManager +# @ohos.app.ability.errorManager (ErrorManager) -The **ErrorManager** module provides APIs for registering and deregistering error observers. +The **ErrorManager** module provides APIs for registering and deregistering error observers. For example, you can use the APIs to register an observer when your application wants to capture JS crashes. > **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 errorManager from '@ohos.app.ability.errorManager' ``` @@ -23,19 +23,26 @@ Registers an error observer. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | number | Index of the observer.| **Example** -```js +```ts var observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) } } +var observerId = -1; try { - errorManager.on("error", observer); + observerId = errorManager.on("error", observer); } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } @@ -53,13 +60,13 @@ Deregisters an error observer. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observerId | number | Yes| Index of the observer returned by **on()**.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** -```js +```ts var observerId = 100; function unregisterErrorObserverCallback(err) { @@ -86,8 +93,8 @@ Deregisters an error observer. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call.| -| observerId | number | Yes| Numeric code of the observer.| +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observerId | number | Yes| Index of the observer returned by **on()**.| **Return value** @@ -97,7 +104,7 @@ Deregisters an error observer. This API uses a promise to return the result. **Example** -```js +```ts var observerId = 100; try { errorManager.off("error", observerId) diff --git a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md index b53881f7fdb5df90cf0a1783c04554ce93240b04..d532723b43a1c31f2b01b35799747ec689df5099 100644 --- a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md @@ -1,30 +1,10 @@ -# @ohos.app.ability.ExtensionAbility +# @ohos.app.ability.ExtensionAbility (ExtensionAbility Base Class) -The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information. +**ExtensionAbility** is the base class for scenario-specific ExtensionAbilities. It is inherited from [Ability](js-apis-app-ability-ability.md), with no attribute or method added. You cannot inherit from this base class. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Modules to Import - -```ts -import ExtensionAbility from '@ohos.app.ability.ExtensionAbility'; -``` - **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` 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 4f989652d549a118d01097b3a8ec2f5084ec0031..434fb19383e072a36352012300c2a755769d6c1f 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 @@ -1,15 +1,15 @@ -# @ohos.app.ability.missionManager +# @ohos.app.ability.missionManager (missionManager) The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. > **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 missionManager from '@ohos.app.ability.missionManager' +import missionManager from '@ohos.app.ability.missionManager'; ``` ## Required Permissions @@ -32,19 +32,19 @@ Registers a listener to observe the mission status. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listener | MissionListener | Yes| Listener to register.| + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.| **Return value** | Type| Description| | -------- | -------- | - | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + | number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** ```ts -import Ability from '@ohos.application.Ability' import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, @@ -52,14 +52,15 @@ var listener = { 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-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; var listenerId = -1; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate"); globalThis.abilityWant = want; globalThis.context = this.context; } @@ -74,12 +75,12 @@ export default class MainAbility extends Ability { } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") try { listenerId = missionManager.on("mission", listener); } catch (paramError) { @@ -106,7 +107,7 @@ export default class MainAbility extends Ability { off(type: "mission", listenerId: number, callback: AsyncCallback<void>): void; -Deregisters a mission status listener. This API uses an asynchronous callback to return the result. +Deregisters a mission status listener. **Required permissions**: ohos.permission.MANAGE_MISSIONS @@ -118,14 +119,14 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts -import Ability from '@ohos.application.Ability' import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, @@ -133,14 +134,15 @@ var listener = { 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-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; var listenerId = -1; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") globalThis.abilityWant = want; globalThis.context = this.context; } @@ -155,12 +157,12 @@ export default class MainAbility extends Ability { } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") try { listenerId = missionManager.on("mission", listener); } catch (paramError) { @@ -199,19 +201,19 @@ Deregisters a mission status listener. This API uses a promise to return the res | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** ```ts -import Ability from '@ohos.application.Ability' import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, @@ -219,14 +221,15 @@ var listener = { 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-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; var listenerId = -1; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate") + console.log("[Demo] EntryAbility onCreate") globalThis.abilityWant = want; globalThis.context = this.context; } @@ -241,12 +244,12 @@ export default class MainAbility extends Ability { } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } - console.log("[Demo] MainAbility onDestroy") + console.log("[Demo] EntryAbility onDestroy") } onWindowStageCreate(windowStage) { // The main window is created. Set a main page for this ability. - console.log("[Demo] MainAbility onWindowStageCreate") + console.log("[Demo] EntryAbility onWindowStageCreate") try { listenerId = missionManager.on("mission", listener); } catch (paramError) { @@ -292,19 +295,28 @@ Obtains the information about a given mission. This API uses an asynchronous cal **Example** ```ts - import missionManager from '@ohos.app.ability.missionManager' + import missionManager from '@ohos.app.ability.missionManager'; + let testMissionId = 1; try { - var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); - missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { - console.log("getMissionInfo is called, error.code = " + error.code) - 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); - }); + var 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) => { + if (error) { + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + } else { + console.log("mission.missionId = " + mission.missionId); + console.log("mission.runningState = " + mission.runningState); + console.log("mission.lockedState = " + mission.lockedState); + console.log("mission.timestamp = " + mission.timestamp); + console.log("mission.label = " + mission.label); + console.log("mission.iconPath = " + mission.iconPath); + } + }); } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } @@ -338,18 +350,20 @@ Obtains the information about a given mission. This API uses a promise to return **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var mission = missionManager.getMissionInfo("", 10).catch(function (err){ - console.log(err); +let testMissionId = 1; +try { + missionManager.getMissionInfo("", testMissionId).then((data) => { + console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionInfo failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('getMissionInfo failed. Cause: ' + error.message); +} +``` ## missionManager.getMissionInfos @@ -374,13 +388,17 @@ Obtains information about all missions. This API uses an asynchronous callback t **Example** ```ts - import missionManager from '@ohos.app.ability.missionManager' + import missionManager from '@ohos.app.ability.missionManager'; try { missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); + if (error) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + } else { + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + } }) } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); @@ -415,18 +433,19 @@ Obtains information about all missions. This API uses a promise to return the re **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ - console.log(err); +try { + missionManager.getMissionInfos("", 10).then((data) => { + console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionInfos failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('getMissionInfos failed. Cause: ' + error.message); +} +``` ## missionManager.getMissionSnapShot @@ -449,27 +468,22 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +let testMissionId = 2; +try { + missionManager.getMissionSnapShot("", testMissionId, (err, data) => { + if (err) { + console.error('getMissionSnapShot failed:' + err.message); + } else { + console.info('getMissionSnapShot successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getMissionSnapShot failed:' + err.message); +} +``` ## missionManager.getMissionSnapShot @@ -497,26 +511,20 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ - console.log(err); - }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +let testMissionId = 2; +try { + missionManager.getMissionSnapShot("", testMissionId).then((data) => { + console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionSnapShot failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getMissionSnapShot failed. Cause: ' + error.message); +} +``` ## missionManager.getLowResolutionMissionSnapShot @@ -539,27 +547,22 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { - console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) - }) - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +let testMissionId = 2; +try { + missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => { + if (err) { + console.error('getLowResolutionMissionSnapShot failed:' + err.message); + } else { + console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getLowResolutionMissionSnapShot failed:' + err.message); +} +``` ## missionManager.getLowResolutionMissionSnapShot @@ -588,25 +591,20 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ - console.log(err); - }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +let testMissionId = 2; +try { + missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => { + console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); +} +``` ## missionManager.lockMission @@ -630,25 +628,22 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.lockMission(id).then(() => { - console.log("lockMission is called "); - }); +let testMissionId = 2; +try { + missionManager.lockMission(testMissionId, (err, data) => { + if (err) { + console.error('lockMission failed:' + err.message); + } else { + console.info('lockMission successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('lockMission failed:' + err.message); +} +``` ## missionManager.lockMission @@ -670,32 +665,25 @@ Locks a given mission. This API uses a promise to return the result. **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.lockMission(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.lockMission(testMissionId).then((data) => { + console.info('lockMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('lockMission failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('lockMission failed. Cause: ' + error.message); +} +``` ## missionManager.unlockMission @@ -717,26 +705,22 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.unlockMission(id).then(() => { - console.log("unlockMission is called "); - }); +let testMissionId = 2; +try { + missionManager.unlockMission(testMissionId, (err, data) => { + if (err) { + console.error('unlockMission failed:' + err.message); + } else { + console.info('unlockMission successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('unlockMission failed:' + err.message); +} +``` ## missionManager.unlockMission @@ -758,35 +742,26 @@ Unlocks a given mission. This API uses a promise to return the result. **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.lockMission(id).catch(function (err){ - console.log(err); - }); - missionManager.unlockMission(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.unlockMission(testMissionId).then((data) => { + console.info('unlockMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('unlockMission failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('unlockMission failed. Cause: ' + error.message); +} +``` ## missionManager.clearMission @@ -809,24 +784,22 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.clearMission(id).then(() => { - console.log("clearMission is called "); - }); +let testMissionId = 2; +try { + missionManager.clearMission(testMissionId, (err, data) => { + if (err) { + console.error('clearMission failed:' + err.message); + } else { + console.info('clearMission successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +} catch (err) { + console.error('clearMission failed:' + err.message); +} +``` ## missionManager.clearMission @@ -849,32 +822,26 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.clearMission(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.clearMission(testMissionId).then((data) => { + console.info('clearMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('clearMission failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (error) { + console.error('clearMission failed. Cause: ' + error.message); +} +``` ## missionManager.clearAllMissions @@ -890,14 +857,21 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' - - missionManager.clearAllMissions().then(() => { - console.log("clearAllMissions is called "); - }); - ``` +```ts +import missionManager from '@ohos.app.ability.missionManager'; +try { + missionManager.clearAllMissions(err => { + if (err) { + console.error('clearAllMissions failed:' + err.message); + } else { + console.info('clearAllMissions successfully.'); + } + }); +} catch (err) { + console.error('clearAllMissions failed:' + err.message); +} +``` ## missionManager.clearAllMissions @@ -913,19 +887,25 @@ Clears all unlocked missions. This API uses a promise to return the result. **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' - missionManager.clearAllMissions().catch(function (err){ - console.log(err); - }); - ``` +```ts +import missionManager from '@ohos.app.ability.missionManager'; +try { + missionManager.clearAllMissions(bundleName).then(() => { + console.info('clearAllMissions successfully.'); + }).catch(err => { + console.error('clearAllMissions failed:' + err.message); + }); +} catch (err) { + console.error('clearAllMissions failed:' + err.message); +} +``` ## missionManager.moveMissionToFront @@ -948,25 +928,22 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.moveMissionToFront(id).then(() => { - console.log("moveMissionToFront is called "); - }); +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId, (err, data) => { + if (err) { + console.error('moveMissionToFront failed:' + err.message); + } else { + console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('moveMissionToFront failed:' + err.message); +} +``` ## missionManager.moveMissionToFront @@ -990,25 +967,22 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.moveMissionToFront(id,{windowMode : 101}).then(() => { - console.log("moveMissionToFront is called "); - }); +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => { + if (err) { + console.error('moveMissionToFront failed:' + err.message); + } else { + console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + } }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` - +} catch (err) { + console.error('moveMissionToFront failed:' + err.message); +} +``` ## missionManager.moveMissionToFront @@ -1031,28 +1005,23 @@ Switches a given mission to the foreground, with the startup parameters for the **Return value** - | Type| Description| + | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise used to return the result.| **Example** - ```ts - import missionManager from '@ohos.app.ability.missionManager' +```ts +import missionManager from '@ohos.app.ability.missionManager'; - try { - var allMissions; - missionManager.getMissionInfos("",10).then(function(res){ - allMissions=res; - }).catch(function(err){console.log(err);}); - console.log("size = " + allMissions.length); - console.log("missions = " + JSON.stringify(allMissions)); - var id = allMissions[0].missionId; - - missionManager.moveMissionToFront(id).catch(function (err){ - console.log(err); +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId).then((data) => { + console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('moveMissionToFront failed. Cause: ' + error.message); }); - } catch (paramError) { - console.log("error: " + paramError.code + ", " + paramError.message); - } - ``` +} catch (error) { + 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 c703726492eb8bc4ddd1211f97d95a3490a8938a..a2090ed00e60cac1b5452bf6357f47cfb3c7be2e 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.quickFixManager +# @ohos.app.ability.quickFixManager (quickFixManager) 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. @@ -36,7 +36,7 @@ Defines the quick fix information at the application level. | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name. | | bundleVersionCode | number | Yes | Internal version number of the application. | | bundleVersionName | string | Yes | Version number of the application that is shown to users. | | quickFixVersionCode | number | Yes | Version code of the quick fix patch package. | @@ -65,8 +65,6 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - try { let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { @@ -108,8 +106,6 @@ Applies a quick fix patch. This API uses a promise to return the result. **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] try { quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { @@ -136,16 +132,14 @@ Obtains the quick fix information of the application. This API uses an asynchron **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes|Bundle name of the application. | - | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes|Bundle name. | +| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - try { let bundleName = "bundleName" quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { @@ -174,9 +168,9 @@ Obtains the quick fix information of the application. This API uses a promise to **Parameters** - | Parameter| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of the application. | +| Parameter| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| **Return value** @@ -187,8 +181,6 @@ Obtains the quick fix information of the application. This API uses a promise to **Example** ```ts - import quickFixManager from '@ohos.app.ability.quickFixManager' - try { let bundleName = "bundleName" quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { @@ -199,4 +191,4 @@ Obtains the quick fix information of the application. This API uses a promise to } catch (paramError) { console.log("error: " + paramError.code + ", " + paramError.message); } -``` + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md index 6c3e0e6e2a0e116120aa405758506d46175c3468..0efdb59d5eaed4c2b70e5ff666b0c9d63b11212f 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 @@ -1,10 +1,10 @@ -# @ohos.app.ability.ServiceExtensionAbility +# @ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility) -The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. +The **ServiceExtensionAbility** module provides lifecycle callbacks when a ServiceExtensionAbility (background service) is created, destroyed, connected, or disconnected. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The 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 @@ -23,16 +23,16 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| ServiceExtensionContext, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate onCreate(want: Want): void; -Called when a Service Extension ability is created to initialize the service logic. +Called when a ServiceExtensionAbility is created to initialize the service logic. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -40,9 +40,9 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Example** @@ -59,7 +59,7 @@ Called when a Service Extension ability is created to initialize the service log onDestroy(): void; -Called when this Service Extension ability is destroyed to clear resources. +Called when this ServiceExtensionAbility is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -80,7 +80,7 @@ Called when this Service Extension ability is destroyed to clear resources. onRequest(want: Want, startId: number): void; -Called after **onCreate** is invoked when a Service Extension ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **startAbility()**. The value of **startId** is incremented for each ability that is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -88,10 +88,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -108,7 +108,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started onConnect(want: Want): rpc.RemoteObject; -Called after **onCreate** is invoked when a Service Extension ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **connectAbility()**. A **RemoteObject** object is returned for communication between the server and client. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -116,15 +116,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication between the server and client.| **Example** @@ -150,7 +150,7 @@ Called after **onCreate** is invoked when a Service Extension ability is started onDisconnect(want: Want): void; -Called when this Service Extension ability is disconnected. +Called when a client is disconnected from this ServiceExtensionAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -158,9 +158,9 @@ Called when this Service Extension ability is disconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Example** @@ -176,7 +176,7 @@ Called when this Service Extension ability is disconnected. onReconnect(want: Want): void; -Called when this Service Extension ability is reconnected. +Called when a new client attempts to connect to this ServiceExtensionAbility after all previous clients are disconnected. This capability is reserved. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -184,9 +184,9 @@ Called when this Service Extension ability is reconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| **Example** @@ -202,7 +202,7 @@ Called when this Service Extension ability is reconnected. onConfigurationUpdate(newConfig: Configuration): void; -Called when the configuration of this Service Extension ability is updated. +Called when the configuration of this ServiceExtensionAbility is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -210,9 +210,9 @@ Called when the configuration of this Service Extension ability is updated. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| **Example** @@ -236,9 +236,9 @@ Dumps the client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md index fc5215fe400919172a7c2f2dd7c5a567e44acae3..3e95fbf541e7ed79834673c2ca97b1398bc73989 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 @@ -1,6 +1,6 @@ -# @ohos.app.ability.StartOptions +# @ohos.app.ability.StartOptions (StartOptions) -The **StartOptions** module implements ability startup options. +**StartOptions** is used as an input parameter of [startAbility()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1) to specify the window mode of an ability. > **NOTE** > @@ -21,4 +21,4 @@ import StartOptions from '@ohos.app.ability.StartOptions'; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| -| displayId | number | No| Display ID.| +| displayId | number | No| Display ID. The default value is **0**, indicating the current display.| 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 cce8b81738f29586417ae5f9814da2448f053e17..38d9f5428c37873ae9f786ed0f391142f30a011b 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 @@ -1,11 +1,9 @@ -# @ohos.app.ability.UIAbility +# @ohos.app.ability.UIAbility (UIAbility) -The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. +UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callback such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration: -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. +- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee). +- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). > **NOTE** > @@ -15,39 +13,39 @@ This module provides the following common ability-related functions: ## Modules to Import ```ts -import Ability from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; ``` ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Type| Readable| Writable| Description| +| 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.| +| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.| +| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.| +| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| -## Ability.onCreate +## UIAbility.onCreate onCreate(want: Want, param: AbilityConstant.LaunchParam): void; -Called to initialize the service logic when an ability is created. +Called to initialize the service logic when a UIAbility 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.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.| +| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); } @@ -55,24 +53,24 @@ Called to initialize the service logic when an ability is created. ``` -## Ability.onWindowStageCreate +## UIAbility.onWindowStageCreate onWindowStageCreate(windowStage: window.WindowStage): void -Called when a **WindowStage** is created for this ability. +Called when a **WindowStage** is created for this UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); } @@ -80,18 +78,18 @@ Called when a **WindowStage** is created for this ability. ``` -## Ability.onWindowStageDestroy +## UIAbility.onWindowStageDestroy onWindowStageDestroy(): void -Called when the **WindowStage** is destroyed for this ability. +Called when the **WindowStage** is destroyed for this UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onWindowStageDestroy() { console.log('onWindowStageDestroy'); } @@ -99,24 +97,24 @@ Called when the **WindowStage** is destroyed for this ability. ``` -## Ability.onWindowStageRestore +## UIAbility.onWindowStageRestore onWindowStageRestore(windowStage: window.WindowStage): void -Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability. +Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); } @@ -124,18 +122,18 @@ Called when the **WindowStage** is restored during the migration of this ability ``` -## Ability.onDestroy +## UIAbility.onDestroy onDestroy(): void; -Called when this ability is destroyed to clear resources. +Called when this UIAbility is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onDestroy() { console.log('onDestroy'); } @@ -143,18 +141,18 @@ Called when this ability is destroyed to clear resources. ``` -## Ability.onForeground +## UIAbility.onForeground onForeground(): void; -Called when this ability is switched from the background to the foreground. +Called when this UIAbility is switched from the background to the foreground. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onForeground() { console.log('onForeground'); } @@ -162,18 +160,18 @@ Called when this ability is switched from the background to the foreground. ``` -## Ability.onBackground +## UIAbility.onBackground onBackground(): void; -Called when this ability is switched from the foreground to the background. +Called when this UIAbility is switched from the foreground to the background. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onBackground() { console.log('onBackground'); } @@ -181,7 +179,7 @@ Called when this ability is switched from the foreground to the background. ``` -## Ability.onContinue +## UIAbility.onContinue onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; @@ -191,21 +189,21 @@ Called to save data during the ability migration preparation process. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | wantParam | {[key: string]: any} | Yes| **want** parameter.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wantParam | {[key: string]: any} | Yes| **want** parameter.| **Return value** - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnContinueResult | Continuation result.| +| Type| Description| +| -------- | -------- | +| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.| **Example** ```ts - import AbilityConstant from "@ohos.application.AbilityConstant" - class myAbility extends Ability { + import AbilityConstant from "@ohos.app.ability.AbilityConstant" + class MyUIAbility extends UIAbility { onContinue(wantParams) { console.log('onContinue'); wantParams["myData"] = "my1234567"; @@ -215,32 +213,33 @@ Called to save data during the ability migration preparation process. ``` -## Ability.onNewWant +## UIAbility.onNewWant onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; -Called when the ability startup mode is set to singleton. +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 parameters, such as the ability name and bundle name.| - | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| +| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| **Example** ```ts - class myAbility extends Ability { - onNewWant(want) { + class MyUIAbility extends UIAbility { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); } } ``` -## Ability.onDump +## UIAbility.onDump onDump(params: Array\): Array\; @@ -250,14 +249,14 @@ Dumps client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** ```ts - class myAbility extends Ability { + class MyUIAbility extends UIAbility { onDump(params) { console.log('dump, params:' + JSON.stringify(params)); return ["params"] @@ -266,33 +265,33 @@ Dumps client information. ``` -## Ability.onSaveState +## UIAbility.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). +Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility. **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.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.| +| wantParam | {[key: string]: any} | Yes| **want** parameter.| **Return value** - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnSaveResult | Whether the ability state is saved.| +| Type| Description| +| -------- | -------- | +| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.| **Example** ```ts -import AbilityConstant from '@ohos.application.AbilityConstant' +import AbilityConstant from '@ohos.app.ability.AbilityConstant' -class myAbility extends Ability { +class MyUIAbility extends UIAbility { onSaveState(reason, wantParam) { console.log('onSaveState'); wantParam["myData"] = "my1234567"; @@ -305,7 +304,7 @@ class myAbility extends Ability { ## Caller -Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). +Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility). ## Caller.call @@ -317,29 +316,29 @@ Sends sequenceable data to the target ability. **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.| +| 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](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return a response.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return a response.| **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). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; - class MyMessageAble{ // Custom sequenceable data structure + class MyMessageAble{ // Custom sequenceable data structure. name:"" str:"" num: 1 @@ -360,13 +359,13 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). return true; } }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities + var method = 'call_Function'; // Notification message string negotiated by the two abilities. var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -398,28 +397,28 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **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.| +| 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](js-apis-rpc.md#sequenceabledeprecated) | 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.| +| Type| Description| +| -------- | -------- | +| Promise<[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)> | Promise used to return the sequenceable data from the target ability.| **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). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -443,11 +442,11 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). }; var method = 'call_Function'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -491,13 +490,12 @@ Releases the caller interface of the target ability. **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -525,20 +523,19 @@ Registers a callback that is invoked when the stub on the target ability is disc **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| **Example** ```ts - import Ability from '@ohos.application.Ability'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -568,28 +565,28 @@ Registers a callback that is invoked when the stub on the target ability is disc **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **release**.| - | callback | OnReleaseCallback | Yes| Callback used for the **onRelease** API.| +| 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.| **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). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; var caller; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ + this.context.startUIAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "MainUIAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -624,22 +621,22 @@ Registers a caller notification callback, which is invoked when the target abili **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.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities.| +| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.| **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). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -668,7 +665,7 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). pdata.readSequenceable(msg); return new MyMessageAble("test1", "Callee test"); } - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -691,24 +688,24 @@ Deregisters a caller notification callback, which is invoked when the target abi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Registered notification message string.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Registered notification message string.| **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). + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; var method = 'call_Function'; - export default class MainAbility extends Ability { + export default class MainUIAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -727,9 +724,9 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Readable| Writable| Type| Description| +| Name| Readable| Writable| Type| Description| | -------- | -------- | -------- | -------- | -------- | -| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| +| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| ## CalleeCallback @@ -737,6 +734,6 @@ For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name| Readable| Writable| Type| Description| +| Name| Readable| Writable| Type| Description| | -------- | -------- | -------- | -------- | -------- | -| (indata: rpc.MessageParcel) | Yes| No| rpc.Sequenceable | Prototype of the listener function registered by the callee.| +| (indata: [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.| 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 c7bd4f6e9693c9bcc7ac71286e204f4d0b5005a8..c96e29d90f3a10a563df41bc8a545cb42dfdeba4 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 @@ -1,6 +1,6 @@ -# @ohos.app.ability.Want +# @ohos.app.ability.Want (Want) -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a 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. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a 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. When UIAbility A needs to start UIAbility B and transfer some data to UIAbility B, it can use Want a carrier to transfer the data. > **NOTE** > @@ -18,26 +18,26 @@ import Want from '@ohos.app.ability.Want'; | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. | -| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| 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.| -| 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. | -| 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. | -| 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. | -| moduleName | string | No | Module to which the ability belongs.| +| [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.| +| 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. | +| [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 +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). ```ts - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", "moduleName": "entry" // moduleName is optional. }; this.context.startAbility(want, (error) => { @@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want'; }) ``` -- Data is transferred through user-defined fields. The following data types are supported: +- 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): * String ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForString: "str", }, @@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want'; * Number ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForInt: 100, keyForDouble: 99.99, @@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want'; * Boolean ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForBool: true, }, @@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want'; * Object ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForObject: { keyForObjectString: "str", @@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want'; * Array ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForArrayString: ["str1", "str2", "str3"], keyForArrayInt: [100, 200, 300, 400], @@ -109,26 +109,28 @@ import Want from '@ohos.app.ability.Want'; ``` * File descriptor (FD) ```ts - import fileio from '@ohos.fileio'; - var fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); + import fileio from '@ohos.fileio'; + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} } - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} - } - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + }; + 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) + }) ``` - +- 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 bfc8b4f99cf05e7dd20c420b3314b695c880f8d1..43b95743b25c34bdae9457c1e1ed1cf01f8e986e 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 @@ -1,6 +1,6 @@ -# @ohos.app.ability.wantAgent +# @ohos.app.ability.wantAgent (WantAgent) -The **app.ability.WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. +The **app.ability.WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. > **NOTE** > @@ -24,7 +24,7 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ----------------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Error codes** @@ -43,7 +43,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -54,33 +54,30 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| - **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -92,15 +89,15 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(err)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -119,7 +116,7 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------------- | ---- | ------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| **Return value** @@ -143,7 +140,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -157,28 +154,25 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -217,6 +211,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). | ID | Error Message | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -231,7 +226,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -245,28 +240,27 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -278,7 +272,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -297,9 +291,9 @@ function getWantAgentCallback(err, data) { console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -342,7 +336,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -356,29 +350,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -390,7 +382,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -405,9 +397,9 @@ function getWantAgentCallback(err, data) { console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -445,7 +437,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -461,26 +453,26 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ```ts import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -492,7 +484,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(err)); @@ -511,9 +503,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -556,7 +548,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -570,29 +562,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent; +// WantAgent object +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -604,7 +594,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -619,9 +609,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -642,11 +632,10 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------- | | agent | WantAgent | Yes | Target **WantAgent** object. | -| callback | AsyncCallback\ | Yes | Callback used to return the want.| +| callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.| **Error codes** For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). - | ID | Error Message | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -661,7 +650,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -675,28 +664,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -708,7 +696,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -727,9 +715,9 @@ function getWantAgentCallback(err, data) { console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -774,7 +762,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -788,29 +776,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent; +// WantAgent object +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -822,7 +808,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -837,9 +823,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -877,7 +863,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -891,28 +877,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -924,7 +909,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -943,9 +928,9 @@ function getWantAgentCallback(err, data) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -988,7 +973,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1002,29 +987,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1036,7 +1019,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -1051,17 +1034,13 @@ function getWantAgentCallback(err, data) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` - -//TODO WantAgent.trigger Callback - - ## WantAgent.trigger trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\): void @@ -1075,8 +1054,8 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ----------- | ----------------------------- | ---- | ------------------------------- | | agent | WantAgent | Yes | Target **WantAgent** object. | -| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. | -| callback | AsyncCallback\ | No | Callback used to return the result.| +| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | +| callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.| **Error codes** For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). @@ -1094,7 +1073,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1108,32 +1087,31 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // triggerInfo -var triggerInfo = { - code: 0 +let triggerInfo = { + code: 0 // Custom result code. } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1145,7 +1123,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -1164,9 +1142,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1177,7 +1155,7 @@ try{ equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void -Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1205,7 +1183,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1219,29 +1197,28 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1253,7 +1230,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent1 = data; wantAgent2 = data; } else { @@ -1273,9 +1250,9 @@ function getWantAgentCallback(err, data) { console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1286,7 +1263,7 @@ try{ equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1319,7 +1296,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1333,30 +1310,28 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent1; -var wantAgent2; +// WantAgent object +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1368,7 +1343,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent1 = data; wantAgent2 = data; } else { @@ -1384,9 +1359,9 @@ function getWantAgentCallback(err, data) { console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1422,7 +1397,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1436,28 +1411,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1469,7 +1443,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -1488,9 +1462,9 @@ function getWantAgentCallback(err, data) { console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1531,7 +1505,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error | 16000011 | Context does not exist.| | 16000050 | Internal Error.| | 16000051 | Network error. The network is abnormal.| -| 16000052 | Free install not support. The application does not support free install. | +| 16000052 | Free install not support. The application does not support free install.| | 16000053 | Not top ability. The application is not top ability.| | 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| | 16000055 | Free install timeout.| @@ -1545,29 +1519,27 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error **Example** ```ts -import WantAgent from '@ohos.app.ability.wantAgent'; - - // WantAgent object -var wantAgent; +// WantAgent object +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1579,7 +1551,7 @@ var wantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -1594,9 +1566,9 @@ function getWantAgentCallback(err, data) { console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` 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 ece4baa69e5d3b2883e971655e2367e23acf7812..4d7a483eab8a55c91d4dbb89287fa611f980ef34 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 @@ -1,4 +1,4 @@ -# @ohos.app.ability.wantConstant +# @ohos.app.ability.wantConstant (wantConstant) The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. @@ -14,7 +14,7 @@ import wantConstant from '@ohos.app.ability.wantConstant'; ## wantConstant.Action -Enumerates the action constants of the **Want** object. +Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. **System capability**: SystemCapability.Ability.AbilityBase @@ -44,7 +44,7 @@ Enumerates the action constants of the **Want** object. | 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. | | +| 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. | @@ -56,7 +56,7 @@ Enumerates the action constants of the **Want** object. ## wantConstant.Entity -Enumerates the entity constants of the **Want** object. +Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. **System capability**: SystemCapability.Ability.AbilityBase @@ -71,7 +71,7 @@ Enumerates the entity constants of the **Want** object. ## wantConstant.Flags -Describes flags. + Enumerates the flags that specify how the Want will be handled. **System capability**: SystemCapability.Ability.AbilityBase @@ -79,17 +79,4 @@ Describes flags. | ------------------------------------ | ---------- | ------------------------------------------------------------ | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | | FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | -| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | -| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | -| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | 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_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| 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 bf3f9cbb803b4bed60bba43d88813e6acf38fcb2..51637975d72ea807f428f235aec90310f69b197f 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 @@ -1,4 +1,4 @@ -# @ohos.app.form.formBindingData +# @ohos.application.formBindingData (formBindingData) The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. @@ -48,20 +48,17 @@ Creates a **FormBindingData** object. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility'; -import fileio from '@ohos.fileio'; -let context=featureAbility.getContext(); -context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); +import fs from '@ohos.file.fs'; +import formBindingData from '@ohos.app.form.formBindingData'; + +try { + let fd = fs.openSync('/path/to/form.png') let obj = { "temperature": "21°", - "formImages": {"image": fd} + "formImages": { "image": fd } }; - try { - formBindingData.createFormBindingData(obj); - } catch (error) { - console.log(`catch err->${JSON.stringify(err)}`); - } -}) + formBindingData.createFormBindingData(obj); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index c2bedd6d4dc1b50b6575120b88c0ab88423e7846..ef4e93e215b868013f025722737472735a1016f7 100644 --- a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -1,6 +1,6 @@ -# @ohos.app.form.FormExtensionAbility +# @ohos.app.form.FormExtensionAbility (FormExtensionAbility) -The **FormExtensionAbility** module provides APIs related to Form Extension abilities. +The **FormExtensionAbility** module provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. > **NOTE** > @@ -17,9 +17,9 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; **System capability**: SystemCapability.Ability.Form -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtensionAbility**. This context is inherited from **ExtensionContext**.| +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the FormExtensionAbility. This context is inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).| ## onAddForm @@ -33,7 +33,7 @@ Called to notify the widget provider that a **Form** instance (widget) has been | Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | Yes | Information related to the Extension ability, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| +| want | [Want](js-apis-application-want.md) | Yes | Want information related to the FormExtensionAbility, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| **Return value** @@ -45,17 +45,19 @@ Called to notify the widget provider that a **Form** instance (widget) has been ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want) { console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); let dataObj1 = { - temperature:"11c", - "time":"11:00" + temperature: "11c", + "time": "11:00" }; let obj1 = formBindingData.createFormBindingData(dataObj1); return obj1; } -} +}; ``` ## onCastToNormalForm @@ -75,18 +77,20 @@ Called to notify the widget provider that a temporary widget has been converted **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onCastToNormalForm(formId) { console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); } -} +}; ``` ## onUpdateForm onUpdateForm(formId: string): void -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data. +Called to notify the widget provider that a widget has been updated. After obtaining the latest data, your application should call [updateForm](js-apis-app-form-formProvider.md#updateform) of **formProvider** to update the widget data. **System capability**: SystemCapability.Ability.Form @@ -99,17 +103,24 @@ Called to notify the widget provider that a widget has been updated. After obtai **Example** ```ts -import formBindingData from '@ohos.app.form.formBindingData' +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onUpdateForm(formId) { console.log('FormExtensionAbility onUpdateForm, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2).then((data)=>{ + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + formProvider.updateForm(formId, obj2).then((data) => { console.log('FormExtensionAbility context updateForm, data:' + data); }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } -} + console.error('Operation updateForm failed. Cause: ' + error); + }); + } +}; ``` ## onChangeFormVisibility @@ -129,21 +140,28 @@ Called to notify the widget provider of the change of visibility. **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData' +import formProvider from '@ohos.app.form.formProvider'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onChangeFormVisibility(newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2).then((data)=>{ + console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + + for (let key in newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); + formProvider.updateForm(key, obj2).then((data) => { console.log('FormExtensionAbility context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error); + }); } } -} +}; ``` ## onFormEvent @@ -164,11 +182,13 @@ Called to instruct the widget provider to receive and process the widget event. **Example** ```ts -export default class MyFormExtension extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onFormEvent(formId, message) { console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); } -} +}; ``` ## onRemoveForm @@ -188,11 +208,13 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onRemoveForm(formId) { console.log('FormExtensionAbility onRemoveForm, formId:' + formId); } -} +}; ``` ## onConfigurationUpdate @@ -207,16 +229,18 @@ Called when the configuration of the environment where the ability is running is | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| newConfig | [Configuration](js-apis-configuration.md) | Yes| New configuration.| +| newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| **Example** ```ts -class MyFormExtensionAbility extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onConfigurationUpdate(config) { console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); } -} +}; ``` ## onAcquireFormState @@ -236,13 +260,15 @@ Called when the widget provider receives the status query result of a widget. By **Example** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formInfo from '@ohos.app.form.formInfo'; -class MyFormExtensionAbility extends FormExtensionAbility { + +export default class MyFormExtensionAbility extends FormExtensionAbility { onAcquireFormState(want) { console.log('FormExtensionAbility onAcquireFormState, want:' + want); return formInfo.FormState.UNKNOWN; } -} +}; ``` ## onShareForm @@ -270,14 +296,16 @@ Called by the widget provider to receive shared widget data. **Example** ```ts -class MyFormExtensionAbility extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onShareForm(formId) { console.log('FormExtensionAbility onShareForm, formId:' + formId); let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", + "temperature": "20", + "time": "2022-8-8 09:59", }; return wantParams; } -} +}; ``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md index 826050a278af8fa031a54ddcbf701b8759e4132a..e78cf3647a1298ed77b4993d811393ede4e2e5b6 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 @@ -1,6 +1,6 @@ -# @ohos.app.form.formHost +# @ohos.app.form.formHost (formHost) -The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. +The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. > **NOTE** > @@ -28,31 +28,32 @@ Deletes a widget. After this API is called, the application can no longer use th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.deleteForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.deleteForm(formId, (error) => { if (error) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost deleteForm success'); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } - ``` ## deleteForm @@ -82,21 +83,23 @@ Deletes a widget. After this API is called, the application can no longer use th | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Parameters** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -115,27 +118,29 @@ Releases a widget. After this API is called, the application can no longer use t | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.releaseForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.releaseForm(formId, (error) => { if (error) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -155,27 +160,29 @@ Releases a widget. After this API is called, the application can no longer use t | -------------- | ------ | ---- | ----------- | | formId | string | Yes | Widget ID. | | isReleaseCache | boolean | Yes | Whether to release the cache.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.releaseForm(formId, true, (error, data) => { + let formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error) => { if (error) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -206,21 +213,23 @@ Releases a widget. After this API is called, the application can no longer use t | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -239,27 +248,29 @@ Requests a widget update. This API uses an asynchronous callback to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.requestForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.requestForm(formId, (error) => { if (error) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -289,21 +300,23 @@ Requests a widget update. This API uses a promise to return the result. | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -323,27 +336,29 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; - formHost.castToNormalForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.castToNormalForm(formId, (error) => { if (error) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -373,21 +388,23 @@ Converts a temporary widget to a normal one. This API uses a promise to return t | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.castToNormalForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -406,27 +423,29 @@ Instructs the widget framework to make a widget visible. After this API is calle | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId, (error) => { if (error) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -456,21 +475,23 @@ Instructs the widget framework to make a widget visible. After this API is calle | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -489,27 +510,29 @@ Instructs the widget framework to make a widget invisible. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId, (error) => { if (error) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -539,21 +562,23 @@ Instructs the widget framework to make a widget invisible. After this API is cal | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -572,27 +597,29 @@ Instructs the widget framework to make a widget updatable. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId, (error) => { if (error) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -622,21 +649,23 @@ Instructs the widget framework to make a widget updatable. After this API is cal | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -655,27 +684,29 @@ Instructs the widget framework to make a widget not updatable. After this API is | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId, (error) => { if (error) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -705,21 +736,23 @@ Instructs the widget framework to make a widget not updatable. After this API is | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -735,20 +768,21 @@ Checks whether the system is ready. This API uses an asynchronous callback to re | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; formHost.isSystemReady((error, data) => { if (error) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -769,15 +803,16 @@ Checks whether the system is ready. This API uses a promise to return the result **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formId = "12400633174999288"; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -795,21 +830,23 @@ Obtains the widget information provided by all applications on the device. This | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getAllFormsInfo((error, data) => { if (error) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -825,21 +862,23 @@ Obtains the widget information provided by all applications on the device. This **Return value** -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Type | Description | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts +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('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -857,29 +896,31 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { if (error) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -897,30 +938,32 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | Yes| Module name.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { if (error) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -938,33 +981,35 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | No| Module name.| **Return value** -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Type | Description | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +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)); }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -983,22 +1028,24 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of valid widget IDs.| -| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds, (error, data) => { if (error) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1027,15 +1074,17 @@ Deletes invalid widgets from the list. This API uses a promise to return the res **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + try { - var formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1053,20 +1102,22 @@ Obtains the widget state. This API uses an asynchronous callback to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| -| callback | AsyncCallback<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formHost from '@ohos.app.form.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -1079,13 +1130,13 @@ var want = { try { formHost.acquireFormState(want, (error, data) => { if (error) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } else { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1103,25 +1154,27 @@ Obtains the widget state. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| +| Promise<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formHost from '@ohos.app.form.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -1135,10 +1188,10 @@ try { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1160,6 +1213,8 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to **Example** ```ts +import formHost from '@ohos.app.form.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -1179,11 +1234,13 @@ 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.| +| 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** ```ts +import formHost from '@ohos.app.form.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -1206,27 +1263,29 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isVisible | boolean | Yes | Whether to make the widgets visible.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { - formHost.notifyFormsVisible(formIds, true, (error, data) => { + formHost.notifyFormsVisible(formIds, true, (error) => { if (error) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1257,21 +1316,23 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1291,27 +1352,29 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { - formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + formHost.notifyFormsEnableUpdate(formIds, true, (error) => { if (error) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1342,21 +1405,23 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` ## shareForm @@ -1375,29 +1440,30 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca | ------ | ------ | ---- | ------- | | 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, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). - +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.app.form.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; try { - formHost.shareForm(formId, deviceId, (error, data) => { + formHost.shareForm(formId, deviceId, (error) => { if (error) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1428,22 +1494,24 @@ Shares a specified widget with a remote device. This API uses a promise to retur | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| -**Parameters** +**Example** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.app.form.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; try { formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` @@ -1451,6 +1519,8 @@ try { notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): 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 @@ -1459,20 +1529,75 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| +| formIds | Array\ | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If privacy protection is set successfully, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID | Error Message | +| ------------------------------------------------------------ | ------------------ | +| 401 | Incorrect input parameter.| +| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| | + +**Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsPrivacyProtected + +function notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean): Promise\; + +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\ | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID | Error Message | +| ------------------------------------------------------------ | ------------------ | +| 401 | Incorrect input parameter.| +| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| | + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost shareForm success'); + console.log('formHost notifyFormsPrivacyProtected success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message}`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message}`); } ``` - - \ No newline at end of file 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 5f1ff73b163ffd2c1c5b0feeb1c26a4f3f60cb78..84b40a57a56038b89ddf7ee06caef5f492e252f0 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 @@ -1,6 +1,6 @@ -# @ohos.app.form.formInfo +# @ohos.app.form.formInfo (formInfo) -The **FormInfo** module provides widget information and state. +The **formInfo** module provides types and enums related to the widget information and state. > **NOTE** > @@ -20,8 +20,8 @@ Describes widget information. | Name | Type | Readable | Writable | Description | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | -| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | -| moduleName | string | Yes | No | Name of the module to which the widget belongs. | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| moduleName | string | Yes | No | Name of the module to which the widget belongs. | | abilityName | string | Yes | No | Name of the ability to which the widget belongs. | | name | string | Yes | No | Widget name. | | description | string | Yes | No | Description of the widget. | @@ -30,11 +30,11 @@ Describes widget information. | colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | | isDefault | boolean | Yes | No | Whether the widget is the default one. | | updateEnabled | boolean | Yes | No | Whether the widget is updatable. | -| formVisibleNotify | string | 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. | +| 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 | string | Yes | No | Update period of the widget.| +| updateDuration | number | Yes | No | Update period of the widget.| | defaultDimension | number | Yes | No | Default dimension of the widget. | | supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension). | | customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | @@ -100,8 +100,8 @@ Enumerates the widget parameters. | 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.
**System API**: This is a system API. | +| 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 @@ -125,9 +125,9 @@ Defines the widget information filter. Only the widget information that meets th **System capability**: SystemCapability.Ability.Form -| Name | Description | -| ----------- | ------------ | -| moduleName | Only the information about the widget whose **moduleName** is the same as the provided value is returned.| +| Name | Type | Description | +| ----------- | ---- | ------------ | +| moduleName | string | 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. | ## VisibilityType 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 392f053b31f4fdb51033abb04a83514b8d3cfbd8..d61484f86b36bafd74ded1860272ac1a4b86089a 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 @@ -1,4 +1,4 @@ -# @ohos.app.form.formProvider +# @ohos.app.form.formProvider (formProvider) The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. @@ -31,23 +31,25 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider setFormNextRefreshTime success`); } }); } catch (error) { - console.log("error" + JSON.stringify(error)) + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -76,21 +78,23 @@ Sets the next refresh time for a widget. This API uses a promise to return the r | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log(`formProvider setFormNextRefreshTime success`); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -114,25 +118,27 @@ Updates a widget. This API uses an asynchronous callback to return the result. | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj, (error, data) => { if (error) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider updateForm success`); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -161,23 +167,25 @@ Updates a widget. This API uses a promise to return the result. | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -var formId = "12400633174999288"; -let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); try { formProvider.updateForm(formId, obj).then(() => { - console.log('formProvider updateForm success'); + console.log(`formProvider updateForm success`); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -193,29 +201,31 @@ Obtains the application's widget information on the device. This API uses an asy | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.getFormsInfo((error, data) => { if (error) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` ## getFormsInfo @@ -231,33 +241,35 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -import formInfo from '@ohos.application.formInfo'; -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" }; try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); } }); -} catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -279,31 +291,33 @@ Obtains the application's widget information on the device. This API uses a prom | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -import formInfo from '@ohos.application.formInfo'; -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" }; try { formProvider.getFormsInfo(filter).then((data) => { console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -322,21 +336,23 @@ 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" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| 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.| **Error codes** | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -345,16 +361,16 @@ var want = { } }; 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('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -379,13 +395,15 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -396,15 +414,14 @@ var want = { try { formProvider.requestPublishForm(want, (error, data) => { if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - ``` ## requestPublishForm @@ -422,7 +439,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" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | **Return value** @@ -434,13 +451,15 @@ Requests to publish a widget to the widget host. This API uses a promise to retu | Error Code ID| Error Message| | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md). +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| **Example** ```ts -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -452,10 +471,10 @@ try { 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)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -478,37 +497,38 @@ Checks whether a widget can be published to the widget host. This API uses an as **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.isRequestPublishFormSupported((error, isSupported) => { - if (error) { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); - } else { - if (isSupported) { - var 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" - } - }; - try { - formProvider.requestPublishForm(want, (error, data) => { - if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + if (isSupported) { + var 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" } - }); - } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + }; + try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); + } catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); + } } - } - } -}); + }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -531,34 +551,33 @@ Checks whether a widget can be published to the widget host. This API uses a pro **Example** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { var 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" - } + abilityName: "FormAbility", + parameters: { + "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)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - } }).catch((error) => { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-appControl.md b/en/application-dev/reference/apis/js-apis-appControl.md index 1cb94f68880afc18137b22ed6f73ed3350caffb4..06b334d58cad8e7dd26a45c0344cfa48e1fdf0d6 100644 --- a/en/application-dev/reference/apis/js-apis-appControl.md +++ b/en/application-dev/reference/apis/js-apis-appControl.md @@ -1,4 +1,4 @@ -# appControl +# @ohos.bundle.appControl (appControl) The **appControl** module provides APIs for setting, obtaining, and deleting the disposed status of an application. An application in the disposed state is forbidden to run. When a user clicks the application icon on the home screen, the corresponding page is displayed based on the disposal intent. @@ -30,7 +30,7 @@ Sets the disposed status for an application. This API uses a promise to return t | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | disposedWant | Want | Yes| Disposal intent of the application.| **Return value** @@ -81,7 +81,7 @@ Sets the disposed status for an application. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | disposedWant | Want | Yes| Disposal intent of the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| @@ -128,7 +128,7 @@ Obtains the disposed status of an application. This API uses a promise to return | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | **Return value** @@ -177,7 +177,7 @@ Obtains the disposed status of an application. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the disposed status obtained; otherwise, **err** is an error object. | **Error codes** @@ -222,7 +222,7 @@ Deletes the disposed status for an application. This API uses a promise to retur | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | **Return value** @@ -271,7 +271,7 @@ Deletes the disposed status for an application. This API uses an asynchronous ca | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 8c1c83988c352d24ac4bc7d64b61d53f3378156a..efba928564b2c9aa34e35b2af7485674ea99274d 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,4 +1,4 @@ -# @ohos.application.Ability +# @ohos.application.Ability (Ability) The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. @@ -15,7 +15,7 @@ This module provides the following common ability-related functions: ## Modules to Import ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; ``` ## Attributes @@ -47,7 +47,7 @@ Called to initialize the service logic when an ability is created. **Example** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); } @@ -67,7 +67,7 @@ Called when a **WindowStage** is created for this ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** @@ -111,7 +111,7 @@ Called when the **WindowStage** is restored during the migration of this ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** @@ -219,23 +219,24 @@ Called to save data during the ability migration preparation process. onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; -Called when the ability startup mode is set to singleton. +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 parameters, such as the ability name and bundle name.| - | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| +| 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 class myAbility extends Ability { - onNewWant(want) { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); } } ``` @@ -388,8 +389,9 @@ Sends sequenceable data to the target ability. **Example** ```ts - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ // Custom sequenceable data structure + import UIAbility from '@ohos.app.ability.UIAbility'; + + class MyMessageAble{ // Custom sequenceable data structure. name:"" str:"" num: 1 @@ -412,11 +414,11 @@ Sends sequenceable data to the target ability. }; var method = 'call_Function'; // Notification message string negotiated by the two abilities var caller; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -472,7 +474,8 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ name:"" str:"" @@ -496,11 +499,11 @@ Sends sequenceable data to the target ability and obtains the sequenceable data }; var method = 'call_Function'; var caller; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -543,14 +546,17 @@ Releases the caller interface of the target ability. **Example** + ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var caller; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -585,13 +591,15 @@ Registers a callback that is invoked when the stub on the target ability is disc **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var caller; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -642,7 +650,7 @@ Registers a caller notification callback, which is invoked when the target abili **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -671,7 +679,7 @@ Registers a caller notification callback, which is invoked when the target abili pdata.readSequenceable(msg); return new MyMessageAble("test1", "Callee test"); } - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -710,9 +718,11 @@ Deregisters a caller notification callback, which is invoked when the target abi **Example** ```ts - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var method = 'call_Function'; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -724,7 +734,7 @@ Deregisters a caller notification callback, which is invoked when the target abi } } ``` - + ## OnReleaseCallBack (msg: string): void; diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md index c97e344590f1bdd6b0d0242c1b61003053908e37..70d679e5f44e1089e91ff7377b687ded761e29e6 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md @@ -1,12 +1,10 @@ -# @ohos.application.AbilityConstant +# @ohos.application.AbilityConstant (AbilityConstant) -The **AbilityConstant** module provides ability launch parameters. - -The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. +The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -21,12 +19,12 @@ import AbilityConstant from '@ohos.application.AbilityConstant'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason.| +| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit.| ## AbilityConstant.LaunchReason -Enumerates ability launch reasons. +Enumerates the initial ability launch reasons. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -41,7 +39,7 @@ Enumerates ability launch reasons. ## AbilityConstant.LastExitReason -Enumerates reasons for the last exit. +Enumerates the reasons for the last exit. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -54,7 +52,7 @@ Enumerates reasons for the last exit. ## AbilityConstant.OnContinueResult -Enumerates ability continuation results. +Enumerates the ability continuation results. **System capability**: SystemCapability.Ability.AbilityRuntime.Core 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 c58eae8878a6df52715e9b4ec06738aeef34bf01..ae72afeca2e3214d00a785c0639793e8df47d715 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,10 +1,10 @@ -# @ohos.application.abilityDelegatorRegistry +# @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. > **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 of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index cd4a4db73667651bae07a865d0a088321cda0ce6..040448220bb9da59779f0d449c43a59d8ab920bd 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,10 +1,10 @@ -# @ohos.application.AbilityLifecycleCallback +# @ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback) -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. 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 and deprecated since 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 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. @@ -25,9 +25,9 @@ Called when an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onWindowStageCreate @@ -40,10 +40,10 @@ Called when the window stage of an ability is created. **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.| +| 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 @@ -56,10 +56,10 @@ Called when the window stage of an ability gains focus. **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.| +| 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 @@ -72,10 +72,10 @@ Called when the window stage of an ability loses focus. **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.| +| 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 @@ -88,10 +88,10 @@ Called when the window stage of an ability is destroyed. **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.| +| 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 @@ -104,9 +104,9 @@ Called when an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityForeground @@ -119,9 +119,9 @@ Called when an ability is switched from the background to the foreground. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityBackground @@ -134,9 +134,9 @@ Called when an ability is switched from the foreground to the background. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityContinue @@ -149,64 +149,64 @@ Called when an ability is continued on another device. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| **Example** - ```ts import AbilityStage from "@ohos.application.AbilityStage"; -var lifecycleid; +var lifecycleId; export default class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + let AbilityLifecycleCallback = { + onAbilityCreate(ability) { + console.log("onAbilityCreate ability:" + JSON.stringify(ability)); }, - onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + onWindowStageCreate(ability, windowStage) { + console.log("onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive 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("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive 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("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy 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("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + onAbilityDestroy(ability) { + console.log("onAbilityDestroy ability:" + JSON.stringify(ability)); }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + onAbilityForeground(ability) { + console.log("onAbilityForeground ability:" + JSON.stringify(ability)); }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + onAbilityBackground(ability) { + console.log("onAbilityBackground ability:" + JSON.stringify(ability)); }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue 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)); + 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)); + 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 cf7f8da5870889e80853b396a433932afc895679..e509a1b5d13a2d0d20b8d6dee4efee9487c5ee92 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -1,16 +1,16 @@ -# @ohos.application.abilityManager +# @ohos.application.abilityManager (AbilityManager) The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. > **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 of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) instead. 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. ## Modules to Import ```ts -import AbilityManager from '@ohos.application.abilityManager' +import abilityManager from '@ohos.application.abilityManager' ``` ## AbilityState @@ -26,8 +26,8 @@ Enumerates the ability states. | INITIAL | 0 | The ability is in the initial state.| | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | +| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | ## updateConfiguration @@ -49,13 +49,11 @@ Updates the configuration. This API uses an asynchronous callback to return the **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var config = { language: 'chinese' } -abilitymanager.updateConfiguration(config, () => { +abilityManager.updateConfiguration(config, () => { console.log('------------ updateConfiguration -----------'); }) ``` @@ -85,13 +83,11 @@ Updates the configuration. This API uses a promise to return the result. **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var config = { language: 'chinese' } -abilitymanager.updateConfiguration(config).then(() => { +abilityManager.updateConfiguration(config).then(() => { console.log('updateConfiguration success'); }).catch((err) => { console.log('updateConfiguration fail'); @@ -112,14 +108,12 @@ Obtains the ability running information. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getAbilityRunningInfos((err,data) => { +abilityManager.getAbilityRunningInfos((err,data) => { console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -138,14 +132,12 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getAbilityRunningInfos().then((data) => { +abilityManager.getAbilityRunningInfos().then((data) => { console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) }).catch((err) => { console.log("getAbilityRunningInfos err: " + err) @@ -167,16 +159,14 @@ Obtains the extension running information. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | | upperLimit | number | Yes| Maximum number of messages that can be obtained.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var upperLimit = 0; -abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { +abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -201,16 +191,14 @@ Obtains the extension running information. This API uses a promise to return the | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - var upperLimit = 0; -abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { +abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); }).catch((err) => { console.log("getAbilityRunningInfos err: " + err); @@ -229,14 +217,12 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the result. | **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getTopAbility((err,data) => { +abilityManager.getTopAbility((err,data) => { console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -253,14 +239,12 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Type | Description | | ---------------------------------------- | ------- | -| Promise\| Promise used to return the result.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the result.| **Example** ```ts -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getTopAbility().then((data) => { +abilityManager.getTopAbility().then((data) => { console.log("getTopAbility data: " + JSON.stringify(data)); }).catch((err) => { console.log("getTopAbility err: " + err); diff --git a/en/application-dev/reference/apis/js-apis-application-abilityStage.md b/en/application-dev/reference/apis/js-apis-application-abilityStage.md index 45227a89b2a6ed8d01997b8c699f8fc8c320b955..1421dcd723028b9a7f052e76e2534f1ea7c4017a 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityStage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityStage.md @@ -1,4 +1,4 @@ -# @ohos.application.AbilityStage +# @ohos.application.AbilityStage (AbilityStage) **AbilityStage** is a runtime class for HAP files. @@ -38,21 +38,21 @@ Called when the application is created. onAcceptWant(want: Want): string; -Called when a specified ability is started. +Called when a UIAbility is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target UIAbility, such as the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| +| Type| Description| +| -------- | -------- | +| string | Returns a UIAbility ID. If this UIAbility has been started, no new instance is created and the UIAbility is placed at the top of the stack. Otherwise, a new instance is created and started.| **Example** @@ -76,9 +76,9 @@ Called when the global configuration is updated. **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.| +| 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** @@ -100,9 +100,9 @@ Called when the system has decided to adjust the memory level. For example, this **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.| +| 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** @@ -118,10 +118,10 @@ Called when the system has decided to adjust the memory level. For example, this context: AbilityStageContext; -Describes the configuration information about the context. +Defines the **Context** object of **AbilityStage**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Description | -| ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Called when initialization is performed during ability startup.| +| Name | Type | Description | +| ------- | ------------------------------------------------------------ | -------------------------- | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | **Context** object of AbilityStage.| diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md index a3f97be529cfef048393d37907a257fddf10b0bf..591f5ec77a34ef2eb36979a00b9553241b33ddb3 100644 --- a/en/application-dev/reference/apis/js-apis-application-appManager.md +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -1,4 +1,4 @@ -# @ohos.application.appManager +# @ohos.application.appManager (appManager) The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. @@ -9,7 +9,7 @@ The **appManager** module implements application management. You can use the API ## Modules to Import ```ts -import app from '@ohos.application.appManager'; +import appManager from '@ohos.application.appManager'; ``` ## appManager.isRunningInStabilityTest8+ @@ -29,9 +29,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Example** ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest((err, flag) => { - console.log('startAbility result:' + JSON.stringify(err)); + appManager.isRunningInStabilityTest((err, flag) => { + console.log('error:' + JSON.stringfy(err)); + console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); }) ``` @@ -53,11 +53,10 @@ Checks whether this application is undergoing a stability test. This API uses a **Example** ```ts - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest().then((flag) => { - console.log('success:' + JSON.stringify(flag)); + appManager.isRunningInStabilityTest().then((flag) => { + console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -79,10 +78,10 @@ Checks whether this application is running on a RAM constrained device. This API **Example** ```ts - app.isRamConstrainedDevice().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.isRamConstrainedDevice().then((data) => { + console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -103,9 +102,9 @@ Checks whether this application is running on a RAM constrained device. This API **Example** ```ts - app.isRamConstrainedDevice((err, data) => { - console.log('startAbility result failed:' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.isRamConstrainedDevice((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); }) ``` @@ -126,10 +125,10 @@ Obtains the memory size of this application. This API uses a promise to return t **Example** ```ts - app.getAppMemorySize().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.getAppMemorySize().then((data) => { + console.log('The size of app memory is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -150,9 +149,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Example** ```ts - app.getAppMemorySize((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.getAppMemorySize((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The size of app memory is:' + JSON.stringify(data)); }) ``` ## appManager.getProcessRunningInfos(deprecated) @@ -171,15 +170,15 @@ Obtains information about the running processes. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the process information.| +| Promise\> | Promise used to return the process information.| **Example** ```ts - app.getProcessRunningInfos().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.getProcessRunningInfos().then((data) => { + console.log('The process running infos is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -199,14 +198,14 @@ Obtains information about the running processes. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| +| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| **Example** ```ts - app.getProcessRunningInfos((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.getProcessRunningInfos((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The process running infos is:' + JSON.stringify(data)); }) ``` @@ -229,10 +228,10 @@ Obtains information about the running processes. This API uses a promise to retu **Example** ```ts - app.getProcessRunningInformation().then((data) => { - console.log('success:' + JSON.stringify(data)); + appManager.getProcessRunningInformation().then((data) => { + console.log('The process running info is:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('error:' + JSON.stringify(error)); }); ``` @@ -255,9 +254,9 @@ Obtains information about the running processes. This API uses an asynchronous c **Example** ```ts - app.getProcessRunningInformation((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); + appManager.getProcessRunningInformation((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The process running info is:' + JSON.stringify(data)); }) ``` @@ -299,7 +298,7 @@ Registers an observer to listen for the state changes of all applications. console.log('------------ onProcessStateChanged -----------', processData); } } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); console.log('-------- observerCode: ---------', observerCode); ``` @@ -343,7 +342,7 @@ Registers an observer to listen for the state changes of a specified application } } var bundleNameList = ['bundleName1', 'bundleName2']; - const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList); console.log('-------- observerCode: ---------', observerCode); ``` ## appManager.unregisterApplicationStateObserver8+ @@ -359,7 +358,7 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | Yes| Numeric code of the observer.| @@ -375,7 +374,7 @@ Deregisters the application state observer. This API uses an asynchronous callba console.log('------------ unregisterApplicationStateObserverCallback ------------', err); } } - app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); + appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); ``` ## appManager.unregisterApplicationStateObserver8+ @@ -407,7 +406,7 @@ Deregisters the application state observer. This API uses a promise to return th ```ts var observerId = 100; - app.unregisterApplicationStateObserver(observerId) + appManager.unregisterApplicationStateObserver(observerId) .then((data) => { console.log('----------- unregisterApplicationStateObserver success ----------', data); }) @@ -420,8 +419,8 @@ Deregisters the application state observer. This API uses a promise to return th getForegroundApplications(callback: AsyncCallback\>): void; -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. - +Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -432,7 +431,7 @@ Obtains applications that are running in the foreground. This API uses an asynch | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | Yes| Callback used to return the application state data.| +| callback | AsyncCallback\> | Yes| Callback used to return the application information.| **Example** @@ -444,14 +443,14 @@ Obtains applications that are running in the foreground. This API uses an asynch console.log('--------- getForegroundApplicationsCallback success ---------', data) } } - app.getForegroundApplications(getForegroundApplicationsCallback); + appManager.getForegroundApplications(getForegroundApplicationsCallback); ``` ## appManager.getForegroundApplications8+ getForegroundApplications(): Promise\>; -Obtains applications that are running in the foreground. This API uses a promise to return the result. +Obtains information about the applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -463,12 +462,12 @@ Obtains applications that are running in the foreground. This API uses a promise | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the application state data.| +| Promise\> | Promise used to return the application information.| **Example** ```ts - app.getForegroundApplications() + appManager.getForegroundApplications() .then((data) => { console.log('--------- getForegroundApplications success -------', data); }) @@ -483,7 +482,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\ Kills a process by bundle name and account ID. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -491,17 +490,17 @@ Kills a process by bundle name and account ID. This API uses a promise to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Example** ```ts var bundleName = 'bundleName'; var accountId = 0; -app.killProcessWithAccount(bundleName, accountId) +appManager.killProcessWithAccount(bundleName, accountId) .then((data) => { console.log('------------ killProcessWithAccount success ------------', data); }) @@ -521,15 +520,15 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **System API**: This is a system API and cannot be called by third-party applications. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -543,7 +542,7 @@ function killProcessWithAccountCallback(err, data) { console.log('------------- killProcessWithAccountCallback success, data: --------------', data); } } -app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); ``` ## appManager.killProcessesByBundleName8+ @@ -562,7 +561,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -576,7 +575,7 @@ Kills a process by bundle name. This API uses an asynchronous callback to return console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); } } - app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); + appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); ``` ## appManager.killProcessesByBundleName8+ @@ -595,7 +594,7 @@ Kills a process by bundle name. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** @@ -604,10 +603,10 @@ Kills a process by bundle name. This API uses a promise to return the result. | Promise\ | Promise used to return the result.| **Example** - + ```ts - var bundleName = 'bundleName'; - app.killProcessesByBundleName(bundleName) + var bundleName = 'com.example.myapplication'; + appManager.killProcessesByBundleName(bundleName) .then((data) => { console.log('------------ killProcessesByBundleName success ------------', data); }) @@ -632,7 +631,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -646,7 +645,7 @@ Clears application data by bundle name. This API uses an asynchronous callback t console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); } } - app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); + appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); ``` ## appManager.clearUpApplicationData8+ @@ -665,7 +664,7 @@ Clears application data by bundle name. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Bundle name of an application.| +| bundleName | string | Yes| Bundle name.| **Return value** @@ -677,7 +676,7 @@ Clears application data by bundle name. This API uses a promise to return the re ```ts var bundleName = 'bundleName'; - app.clearUpApplicationData(bundleName) + appManager.clearUpApplicationData(bundleName) .then((data) => { console.log('------------ clearUpApplicationData success ------------', data); }) 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 9c374059dc89f8ebdc719597df0afb7c12247d66..81870036a845c61f852f671616f63c12f92851b8 100644 --- a/en/application-dev/reference/apis/js-apis-application-configuration.md +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -1,4 +1,4 @@ -# @ohos.application.Configuration +# @ohos.application.Configuration (Configuration) The **Configuration** module defines environment change information. @@ -16,7 +16,7 @@ import Configuration from '@ohos.application.Configuration' | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| language8+ | string | Yes| Yes| Language of the application.| +| 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).| @@ -29,10 +29,10 @@ For details about the fields, see the **ohos.application.Configuration.d.ts** fi ```ts import hilog from '@ohos.hilog'; -import Ability from '@ohos.application.Ability' -import Window from '@ohos.window' +import UIAbility from '@ohos.app.ability.UIAbility'; +import Window from '@ohos.window'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { } 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 863848066791fd23c5811bcc2af027552d8e5991..dabe32b2f9d166dbce68b94c204b82f78b0090de 100644 --- a/en/application-dev/reference/apis/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -1,4 +1,4 @@ -# @ohos.application.ConfigurationConstant +# @ohos.application.ConfigurationConstant (ConfigurationConstant) The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index 88a5c84c617f675c93ea2f43de62625294025ca6..d42e522c14266de6ca53fff7370c68de14c34d36 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,4 +1,4 @@ -# @ohos.application.context +# @ohos.application.context (Context) The **Context** module provides all level-2 module APIs for developers to export. diff --git a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md similarity index 81% rename from en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md rename to en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index 7798cdee3d2f71f54e7cc6937816cbb4c253a833..9ecffc326e125b6e7dbe0ecd3cf03bfc3d2fa7dd 100644 --- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -1,6 +1,6 @@ -# Data Share Extension Ability +# @ohos.application.DataShareExtensionAbility -The **DataShareExtensionAbility** module provides Extension abilities for data share services. +The **DataShareExtensionAbility** module provides data share services based on the Extension ability. >**NOTE** > @@ -17,13 +17,34 @@ The **DataShareExtensionAbility** module provides Extension abilities for data s import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** + +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ExtensionContext](js-apis-extension-context.md) | Yes| No|Context of the DataShare Extension ability.| +| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| ## onCreate @@ -37,13 +58,13 @@ Called by the server to initialize service logic when the DataShare client conne | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| want | [Want](js-apis-application-Want.md#want) | Yes | **Want** information, including the ability name and bundle name.| +| want | [Want](js-apis-application-want.md#want) | Yes | **Want** information, including the ability name and bundle name.| | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -56,7 +77,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { onCreate(want, callback) { rdb.getRdbStore(this.context, { name: DB_NAME - }, 1, function (err, data) { + }, function (err, data) { console.log('getRdbStore done, data : ' + data); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { @@ -83,13 +104,13 @@ Inserts data into the database. This API can be overridden as required. | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri |string | Yes | URI of the data to insert.| -| valueBucket |[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| Data to insert.| +| valueBucket |[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes| Data to insert.| | callback |AsyncCallback<number> | Yes| Callback invoked to return the index of the data inserted.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -127,14 +148,14 @@ Updates data in the database. This API can be overridden as required. | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri | string | Yes | URI of the data to update.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.| -| valueBucket | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| New data.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.| +| valueBucket | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes| New data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of updated data records.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -170,13 +191,13 @@ Deletes data from the database. This API can be overridden as required. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ---------------------------------- | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of data records deleted.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -212,14 +233,14 @@ Queries data from the database. This API can be overridden as required. | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri | string | Yes | URI of the data to query.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| | columns | Array<string> | Yes| Columns to query. If this parameter is empty, all columns will be queried.| | callback | AsyncCallback<Object> | Yes| Callback invoked to return the result set.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -255,16 +276,16 @@ Batch inserts data into the database. This API is called by the server and can b **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | -------------------------------- | | uri | string | Yes | URI of the data to insert. | -| valueBuckets | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| valueBuckets | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of inserted data records.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; 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 e1d2033c652d413ddac9933e32c3c53c1372f443..d4c25269235da3b95e4f230c084d92c1df047269 100644 --- a/en/application-dev/reference/apis/js-apis-application-environmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-environmentCallback.md @@ -1,10 +1,10 @@ -# @ohos.application.EnvironmentCallback +# @ohos.application.EnvironmentCallback (EnvironmentCallback) -The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. +The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdated** and **onMemoryLevel**, for the application context to listen for system environment changes. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.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 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.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. @@ -25,18 +25,32 @@ Called when the system environment changes. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| -**Example** +## EnvironmentCallback.onMemoryLevel + +onMemoryLevel(level: number): void; + +Called when the system memory level changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| + +**Example** ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var callbackId; -export default class MyAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate() { console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); @@ -44,6 +58,9 @@ export default class MyAbility extends Ability { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); }, + onMemoryLevel(level){ + console.log("onMemoryLevel level:" + level); + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md index 5326b582120b6dcbf23a88bedb1ff4dcbe6192ae..c1eaa2d35e90966795e4b98f4b75cffc0570e855 100644 --- a/en/application-dev/reference/apis/js-apis-application-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -1,10 +1,10 @@ -# @ohos.application.errorManager +# @ohos.application.errorManager (ErrorManager) The **ErrorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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 diff --git a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md index 055980e455acb5fd56ece9d4a1a582c7868b1646..f18b293edd8d7a4f65684bc38df4fe48498fa11b 100644 --- a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md @@ -1,6 +1,6 @@ -# @ohos.application.ExtensionAbility +# @ohos.application.ExtensionAbility (ExtensionAbility) -The **ExtensionAbility** module manages the Extension ability lifecycle and context, such as creating and destroying an Extension ability, and dumping client information. +The **ExtensionAbility** module manages the ExtensionAbility lifecycle and context, such as creating and destroying an ExtensionAbility, and dumping client information. > **NOTE** > 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 f0cdf74799a4373cfe61446191166a1e2ca0a014..5fbc52c95dc9e573947fb9820f00100a76a06f22 100644 --- a/en/application-dev/reference/apis/js-apis-application-formBindingData.md +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -1,4 +1,4 @@ -# @ohos.application.formBindingData +# @ohos.application.formBindingData (formBindingData) The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. @@ -48,16 +48,17 @@ Creates a **FormBindingData** object. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility'; -import fileio from '@ohos.fileio'; -let context=featureAbility.getContext(); -context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); +import formBindingData from @ohos.application.formBindingData; +import fs from '@ohos.file.fs'; + +try { + let fd = fs.openSync('/path/to/form.png') let obj = { "temperature": "21°", - "formImages": {"image": fd} + "formImages": { "image": fd } }; - let formBindingDataObj = formBindingData.createFormBindingData(obj); -}) + formBindingData.createFormBindingData(obj); +} catch (error.code) { + console.log('catch error, error:' + JSON.stringify(error)); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formError.md b/en/application-dev/reference/apis/js-apis-application-formError.md index 7a9a6618cd4906b2a4894f8cdfd8c796beefc905..4ca6eecb8cfae8ddbad623262b8a1c7c9ff515ff 100644 --- a/en/application-dev/reference/apis/js-apis-application-formError.md +++ b/en/application-dev/reference/apis/js-apis-application-formError.md @@ -1,6 +1,6 @@ -# @ohos.application.formError +# @ohos.application.formError (formError) -The **FormError** module provides error codes for widgets. +The **formError** module provides error codes for widgets. > **NOTE** > @@ -50,5 +50,3 @@ SystemCapability.Ability.Form | ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | | ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | | ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
**System API**: This is a system API. | - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-formExtension.md b/en/application-dev/reference/apis/js-apis-application-formExtension.md index a01e08710907030edfc7f0b1d04927282f5bc387..fcde831bc20ca03c224b977271f40b69f1ad0569 100644 --- a/en/application-dev/reference/apis/js-apis-application-formExtension.md +++ b/en/application-dev/reference/apis/js-apis-application-formExtension.md @@ -1,4 +1,4 @@ -# @ohos.application.FormExtension +# @ohos.application.FormExtension (FormExtension) The **FormExtension** module provides APIs related to Form Extension abilities. 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 8b44dbf345b717b3cf1433392fd82907b6caab5f..11da810effa714b8aaf37e35d3c0566556281ebf 100644 --- a/en/application-dev/reference/apis/js-apis-application-formHost.md +++ b/en/application-dev/reference/apis/js-apis-application-formHost.md @@ -1,11 +1,11 @@ -# @ohos.application.formHost +# @ohos.application.formHost (formHost) -The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. +The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. > **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 [FormHost](js-apis-app-form-formHost.md) instead. +> This module is deprecated since API version 9. You are advised to use [formHost](js-apis-app-form-formHost.md) instead. > The APIs provided by this module are system APIs. ## Modules to Import @@ -34,10 +34,12 @@ Deletes a widget. After this API is called, the application can no longer use th **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.deleteForm(formId, (error, data) => { if (error.code) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.error('formHost deleteForm, error:' + JSON.stringify(error)); } }); ``` @@ -67,11 +69,13 @@ Deletes a widget. After this API is called, the application can no longer use th **Parameters** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.error('formHost deleteForm, error:' + JSON.stringify(error)); }); ``` @@ -95,10 +99,14 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.releaseForm(formId, (error, data) => { if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost releaseForm success'); } }); ``` @@ -124,10 +132,14 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.releaseForm(formId, true, (error, data) => { if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost releaseForm success'); } }); ``` @@ -158,11 +170,13 @@ Releases a widget. After this API is called, the application can no longer use t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.error('formHost releaseForm, error:' + JSON.stringify(error)); }); ``` @@ -186,10 +200,12 @@ Requests a widget update. This API uses an asynchronous callback to return the r **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.requestForm(formId, (error, data) => { if (error.code) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.error('formHost requestForm, error:' + JSON.stringify(error)); } }); ``` @@ -219,11 +235,13 @@ Requests a widget update. This API uses a promise to return the result. **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.error('formHost requestForm, error:' + JSON.stringify(error)); }); ``` @@ -242,15 +260,17 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.castTempForm(formId, (error, data) => { if (error.code) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.error('formHost castTempForm, error:' + JSON.stringify(error)); } }); ``` @@ -280,11 +300,13 @@ Converts a temporary widget to a normal one. This API uses a promise to return t **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.castTempForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.error('formHost castTempForm, error:' + JSON.stringify(error)); }); ``` @@ -303,15 +325,17 @@ Instructs the widget framework to make a widget visible. After this API is calle | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId, (error, data) => { if (error.code) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); } }); ``` @@ -341,11 +365,13 @@ Instructs the widget framework to make a widget visible. After this API is calle **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); }); ``` @@ -364,15 +390,17 @@ Instructs the widget framework to make a widget invisible. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId, (error, data) => { if (error.code) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); } }); ``` @@ -402,11 +430,13 @@ Instructs the widget framework to make a widget invisible. After this API is cal **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); }); ``` @@ -425,15 +455,17 @@ Instructs the widget framework to make a widget updatable. After this API is cal | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId, (error, data) => { if (error.code) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); } }); ``` @@ -463,11 +495,13 @@ Instructs the widget framework to make a widget updatable. After this API is cal **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); }); ``` @@ -486,15 +520,17 @@ Instructs the widget framework to make a widget not updatable. After this API is | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId, (error, data) => { if (error.code) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); } }); ``` @@ -524,11 +560,13 @@ Instructs the widget framework to make a widget not updatable. After this API is **Example** ```ts -var formId = ["12400633174999288"]; +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); }); ``` @@ -544,15 +582,17 @@ Checks whether the system is ready. This API uses an asynchronous callback to re | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.isSystemReady((error, data) => { if (error.code) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.error('formHost isSystemReady, error:' + JSON.stringify(error)); } }); ``` @@ -574,11 +614,13 @@ Checks whether the system is ready. This API uses a promise to return the result **Example** ```ts -var formId = "12400633174999288"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.error('formHost isSystemReady, error:' + JSON.stringify(error)); }); ``` @@ -596,14 +638,16 @@ Obtains the widget information provided by all applications on the device. This | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + formHost.getAllFormsInfo((error, data) => { if (error.code) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } @@ -624,15 +668,17 @@ Obtains the widget information provided by all applications on the device. This | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts + 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.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); }); ``` @@ -650,15 +696,17 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } @@ -679,18 +727,20 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | Yes| Module name.| -| callback | AsyncCallback<Array<[FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **err** is undefined and **data** is the information obtained; otherwise, **err** is an error object.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| **Example** ```ts +import formHost from '@ohos.application.formHost'; + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { if (error.code) { - console.log('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)); } }); ``` @@ -709,22 +759,24 @@ Obtains the widget information provided by a given application on the device. Th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| bundleName | string | Yes| Bundle name of the application.| +| bundleName | string | Yes| Bundle name of the application.| | moduleName | string | No| Module name.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| +| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| **Example** ```ts + import formHost from '@ohos.application.formHost'; + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); }); ``` @@ -743,15 +795,17 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of valid widget IDs.| -| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **err** is undefined and **data** is the number of widgets deleted; otherwise, **err** is an error object.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds, (error, data) => { if (error.code) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); } else { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); } @@ -783,11 +837,13 @@ Deletes invalid widgets from the list. This API uses a promise to return the res **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); }); ``` @@ -805,13 +861,15 @@ Obtains the widget state. This API uses an asynchronous callback to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| -| callback | AsyncCallback<[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **err** is undefined and **data** is the widget state obtained; otherwise, **err** is an error object.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| **Example** ```ts -var want = { +import formHost from '@ohos.application.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -823,7 +881,7 @@ var want = { }; formHost.acquireFormState(want, (error, data) => { if (error.code) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.error('formHost acquireFormState, error:' + JSON.stringify(error)); } else { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); } @@ -855,7 +913,9 @@ Obtains the widget state. This API uses a promise to return the result. **Example** ```ts -var want = { +import formHost from '@ohos.application.formHost'; + +let want = { "deviceId": "", "bundleName": "ohos.samples.FormApplication", "abilityName": "FormAbility", @@ -868,7 +928,7 @@ var want = { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.error('formHost acquireFormState, error:' + JSON.stringify(error)); }); ``` @@ -890,6 +950,8 @@ Subscribes to widget uninstall events. This API uses an asynchronous callback to **Example** ```ts +import formHost from '@ohos.application.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -909,11 +971,13 @@ 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.| +| 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** ```ts +import formHost from '@ohos.application.formHost'; + let callback = function(formId) { console.log('formHost on formUninstall, formId:' + formId); } @@ -936,15 +1000,17 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isVisible | boolean | Yes | Whether to make the widgets visible.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsVisible(formIds, true, (error, data) => { if (error.code) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); } }); ``` @@ -975,11 +1041,13 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); }); ``` @@ -999,15 +1067,17 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou | ------ | ------ | ---- | ------- | | formIds | Array<string> | Yes | List of widget IDs.| | isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **err** is undefined; otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { if (error.code) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); } }); ``` @@ -1038,11 +1108,13 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r **Example** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); }); ``` ## shareForm9+ @@ -1051,7 +1123,7 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback<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 +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Ability.Form @@ -1061,16 +1133,18 @@ Shares a specified widget with a remote device. This API uses an asynchronous ca | ------ | ------ | ---- | ------- | | 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, **err** is undefined; otherwise, **err** is an error object.| +| 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 -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; formHost.shareForm(formId, deviceId, (error, data) => { if (error.code) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.error('formHost shareForm, error:' + JSON.stringify(error)); } }); ``` @@ -1101,18 +1175,22 @@ Shares a specified widget with a remote device. This API uses a promise to retur **Parameters** ```ts -var formId = "12400633174999288"; -var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +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.log('formHost shareForm, error:' + JSON.stringify(error)); + console.error('formHost shareForm, error:' + JSON.stringify(error)); }); ``` ## notifyFormsPrivacyProtected9+ -notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void +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 @@ -1126,10 +1204,51 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb | deviceId | string | Yes | Remote device ID.| ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +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.log('formHost shareForm, error:' + JSON.stringify(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 de5bd8f6b24e7bd1f6e3fe66b4f4122c9a570d16..df591cea222b9bdbc98c4d108a4151a8aa1c69cb 100644 --- a/en/application-dev/reference/apis/js-apis-application-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-application-formInfo.md @@ -1,11 +1,11 @@ -# @ohos.application.formInfo +# @ohos.application.formInfo (formInfo) -The **FormInfo** module provides widget information and state. +The **formInfo** module provides types and enums related to the widget information and state. > **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 [FormInfo](js-apis-app-form-formInfo.md) instead. +> This module is deprecated since API version 9. You are advised to use [formInfo](js-apis-app-form-formInfo.md) instead. ## Modules to Import @@ -21,9 +21,9 @@ Describes widget information. | Name | Type | Readable | Writable | Description | | ----------- | -------- |-------- | -------------------- | ------------------------------------------------------------ | -| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | | moduleName | string | Yes | No | Name of the module to which the widget belongs. | -| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | +| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | | name | string | Yes | No | Widget name. | | description | string | Yes | No | Description of the widget. | | type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| @@ -31,11 +31,11 @@ Describes widget information. | colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | | isDefault | boolean | Yes | No | Whether the widget is the default one. | | updateEnabled | boolean | Yes | No | Whether the widget is updatable. | -| formVisibleNotify | string | 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. | +| 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. | -| updateDuration | string | Yes | No | Update period of the widget.| +| updateDuration | number | Yes | No | Update period of the widget.| | defaultDimension | number | Yes | No | Default dimension of the widget. | | supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. | | customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | @@ -102,7 +102,7 @@ Enumerates the widget parameters. | 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.
**System API**: This is a system API. | +| 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+ @@ -117,18 +117,7 @@ Enumerates the widget dimensions. | 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. | - -## VisibilityType - -Enumerates the visibility types of the widget. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| FORM_VISIBLE9+ | 1 | The card is visible. | -| FORM_INVISIBLE9+ | 2 | The card is invisible.| +| Dimension_2_1 9+ | 5 | 2 x 1. | ## FormInfoFilter9+ @@ -138,7 +127,7 @@ Defines the widget information filter. Only the widget information that meets th | Name | Description | | ----------- | ------------ | -| moduleName9+ | Only the information about the widget whose **moduleName** is the same as the provided value is returned.| +| 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+ 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 05318bda39a220c15a328368fd5bf54c29f0ad05..4d604ff7295eb9903d450bc96f9c00fde253ee11 100644 --- a/en/application-dev/reference/apis/js-apis-application-formProvider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -1,10 +1,10 @@ -# @ohos.application.formProvider +# @ohos.application.formProvider (formProvider) The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. > **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 [FormProvider](js-apis-app-form-formProvider.md) instead. +> This module is deprecated since API version 9. You are advised to use [formProvider](js-apis-app-form-formProvider.md) instead. ## Modules to Import @@ -31,11 +31,13 @@ Sets the next refresh time for a widget. This API uses an asynchronous callback **Example** ```ts - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { - if (error.code) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); - } + if (error.code) { + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + } }); ``` @@ -63,11 +65,13 @@ Sets the next refresh time for a widget. This API uses a promise to return the r **Example** ```ts - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); }); ``` @@ -84,19 +88,21 @@ Updates a widget. This API uses an asynchronous callback to return the result. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```ts import formBindingData from '@ohos.application.formBindingData'; - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + 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)); - } + if (error.code) { + console.log('formProvider updateForm, error:' + JSON.stringify(error)); + } }); ``` @@ -113,7 +119,7 @@ Updates a widget. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdat) | Yes | Data to be used for the update. | + | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | **Return value** @@ -125,12 +131,14 @@ Updates a widget. This API uses a promise to return the result. ```ts import formBindingData from '@ohos.application.formBindingData'; - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj).then(() => { - console.log('formProvider updateForm success'); + console.log('formProvider updateForm success'); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log('formProvider updateForm, error:' + JSON.stringify(error)); }); ``` @@ -146,17 +154,19 @@ Obtains the application's widget information on the device. This API uses an asy | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| +| 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)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` ## getFormsInfo9+ @@ -172,22 +182,24 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| +| 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" + // 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)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` @@ -209,20 +221,22 @@ Obtains the application's widget information on the device. This API uses a prom | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| +| 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" + // get info of forms belong to module entry. + moduleName : "entry" }; 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('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); }); ``` @@ -241,28 +255,29 @@ 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" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| 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'; - var 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" - } + 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)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } }); ``` @@ -286,20 +301,22 @@ Requests to publish a widget to the widget host. This API uses an asynchronous c **Example** ```ts - var 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" - } + 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)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } }); ``` @@ -318,7 +335,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" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | +| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| **Return value** @@ -329,18 +346,20 @@ Requests to publish a widget to the widget host. This API uses a promise to retu **Example** ```ts - var 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" - } + 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)); + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); }); ``` @@ -368,13 +387,13 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); } else { if (isSupported) { - var 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 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) { @@ -409,13 +428,13 @@ Checks whether a widget can be published to the widget host. This API uses a pro ```ts formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { + 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)); 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 c30dda422ded7148e35ebab1cc26804290bc1ea6..17de66e19334dce9663017c3df9c18b575e14bd7 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -1,10 +1,10 @@ -# @ohos.application.missionManager +# @ohos.application.missionManager (missionManager) The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. > **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 of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -32,13 +32,13 @@ Registers a listener to observe the mission status. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Listener to register.| + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.| **Return value** | Type| Description| | -------- | -------- | - | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + | number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** @@ -73,7 +73,7 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -113,7 +113,7 @@ Deregisters a mission status listener. This API uses a promise to return the res | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.| **Return value** @@ -169,7 +169,12 @@ Obtains the information about a given mission. This API uses an asynchronous cal var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { - console.log("getMissionInfo is called, error.code = " + error.code) + if (error.code) { + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("mission.missionId = " + mission.missionId); console.log("mission.runningState = " + mission.runningState); console.log("mission.lockedState = " + mission.lockedState); @@ -242,7 +247,11 @@ Obtains information about all missions. This API uses an asynchronous callback t import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); }) @@ -311,14 +320,22 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); + if (error.code) { + console.log("getMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("bundleName = " + snapshot.ability.bundleName); }) }) ``` @@ -393,14 +410,22 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { - console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); + if (error.code) { + console.log("getLowResolutionMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("bundleName = " + snapshot.ability.bundleName); }) }) ``` @@ -475,7 +500,11 @@ Locks a given mission. This API uses an asynchronous callback to return the resu import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -554,7 +583,11 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -637,7 +670,11 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -768,7 +805,11 @@ Switches a given mission to the foreground. This API uses an asynchronous callba import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -806,7 +847,11 @@ Switches a given mission to the foreground, with the startup parameters for the import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; diff --git a/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md index ba59d9a6ea78434939ee99a6e25b3c2945874532..beb8c007b0fa58bdae058ac554c96425bdf93bd5 100644 --- a/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md @@ -1,10 +1,13 @@ -# @ohos.application.ServiceExtensionAbility +# @ohos.application.ServiceExtensionAbility (ServiceExtensionAbility) The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. +> +> Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -23,9 +26,9 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate @@ -40,9 +43,9 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -88,10 +91,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -116,15 +119,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| **Example** @@ -158,9 +161,9 @@ Called when this Service Extension ability is disconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -184,9 +187,9 @@ Called when this Service Extension ability is reconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -210,9 +213,9 @@ Called when the configuration of this Service Extension ability is updated. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| **Example** @@ -236,9 +239,9 @@ Dumps the client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-startOptions.md b/en/application-dev/reference/apis/js-apis-application-startOptions.md index 40ad2a516377faf476cfe688914afe3cd3eccb6c..7634b276495d98e18bc7ec966f3483e526dd3ba3 100644 --- a/en/application-dev/reference/apis/js-apis-application-startOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-startOptions.md @@ -1,10 +1,10 @@ -# @ohos.application.StartOptions +# @ohos.application.StartOptions (StartOptions) The **StartOptions** module implements ability startup options. > **NOTE** > -> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. ## Modules to Import 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 b9086a6ce6cbd42c53730baa1531255c0d383ba9..5fc9b0999940310b10bf7b4e7227d5651153eb50 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -1,10 +1,11 @@ -# @ohos.application.StaticSubscriberExtensionAbility +# @ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility) The **StaticSubscriberExtensionAbility** module provides Extension abilities for static subscribers. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -26,9 +27,10 @@ Callback of the common event of a static subscriber. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.| +| event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.| -**Example** +**Example** + ```ts var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") { 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 688774a0d4b840e19e398624be41ac85c07c8f37..d2146524c0c5249374e21c95762438d35dc48c35 100644 --- a/en/application-dev/reference/apis/js-apis-application-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-application-testRunner.md @@ -1,4 +1,4 @@ -# @ohos.application.testRunner +# @ohos.application.testRunner (TestRunner) The **TestRunner** module provides a test framework. You can use the APIs of this module to prepare the unit test environment and run test cases. 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 620885945b572e8129e4f8c61b156ef658a6805d..44cc01a00c5057488b45a5a6a38cc02adbf1cbc2 100644 --- a/en/application-dev/reference/apis/js-apis-application-want.md +++ b/en/application-dev/reference/apis/js-apis-application-want.md @@ -1,10 +1,10 @@ -# @ohos.application.Want +# @ohos.application.Want (Want) -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a 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. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility()** to specify a 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. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the 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 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. ## Modules to Import @@ -18,26 +18,26 @@ import Want from '@ohos.application.Want'; | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. | -| bundleName | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| 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. | | 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. | +| 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. | -| 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. | +| 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.| **Example** -- Basic usage +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). ```ts - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", "moduleName": "entry" // moduleName is optional. }; this.context.startAbility(want, (error) => { @@ -46,13 +46,13 @@ import Want from '@ohos.application.Want'; }) ``` -- Data is transferred through user-defined fields. The following data types are supported: +- 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): * String ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForString: "str", }, @@ -61,8 +61,8 @@ import Want from '@ohos.application.Want'; * Number ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForInt: 100, keyForDouble: 99.99, @@ -72,8 +72,8 @@ import Want from '@ohos.application.Want'; * Boolean ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForBool: true, }, @@ -82,8 +82,8 @@ import Want from '@ohos.application.Want'; * Object ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForObject: { keyForObjectString: "str", @@ -97,8 +97,8 @@ import Want from '@ohos.application.Want'; * Array ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForArrayString: ["str1", "str2", "str3"], keyForArrayInt: [100, 200, 300, 400], @@ -110,16 +110,16 @@ import Want from '@ohos.application.Want'; * File descriptor (FD) ```ts import fileio from '@ohos.fileio'; - var fd; + let fd; try { fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); } catch(e) { console.log("openSync fail:" + JSON.stringify(e)); } - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", "moduleName": "entry", // moduleName is optional. "parameters": { "keyFd":{"type":"FD", "value":fd} @@ -131,4 +131,6 @@ import Want from '@ohos.application.Want'; }) ``` +- 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 882578cc316716db9f2f8a3c1d355e6a07b292db..bd6d74bbcbbdb4b0d29ccad209b012a11f44c9af 100644 --- a/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-windowExtensionAbility.md @@ -1,4 +1,5 @@ -# Window Extension Ability +# @ohos.application.WindowExtensionAbility (WindowExtensionAbility) + **WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index f6334ff328c76de2d9be97b9ad430065819e53c9..ebf538d3b5508c1ee26aa77d4db01aa995239c3b 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -1,7 +1,6 @@ # @ohos.util.ArrayList (Linear Container ArrayList) > **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. **ArrayList** is a linear data structure that is implemented based on arrays. **ArrayList** can dynamically adjust the capacity based on project requirements. It increases the capacity by 50% each time. @@ -42,7 +41,7 @@ A constructor used to create an **ArrayList** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -77,7 +76,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -113,12 +112,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -151,7 +150,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -188,7 +187,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -230,7 +229,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -272,12 +271,12 @@ Removes an element with the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -313,7 +312,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -347,12 +346,12 @@ Removes from this container all of the elements within a range, including the el **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByRange method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -391,7 +390,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -426,7 +425,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.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -439,7 +438,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -481,7 +480,7 @@ comparator **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -523,12 +522,12 @@ Obtains elements within a range in this container, including the element at the **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The subArrayList method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -553,7 +552,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -587,7 +586,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -620,7 +619,7 @@ Obtains the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -653,7 +652,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -686,7 +685,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -719,7 +718,7 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -747,7 +746,7 @@ Trims the capacity of this container to its current length. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -780,7 +779,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 48be07fbffdadd82f34eb41b6906f4a87a679e89..a992de969d6b6e673b89eff8f14f28f5328ce017 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -2356,10 +2356,6 @@ audioVolumeManager.on('volumeChange', (volumeEvent) => { Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - ### setVolume9+ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 14e4656758b6ef17f98345767a07d7759a691eda..5552792aadadd04fca72d4fe88ffdfc8219b3ec9 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -1,14 +1,16 @@ -# AVSession Management +# @ohos.multimedia.avsession (AVSession Management) The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller. This module provides the following common features related to media sessions: -- [AVSession](#section652893): used to set session metadata, playback state information, and more. -- [AVSessionController](#section974602): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. +- [AVSession](#avsession): used to set session metadata, playback state information, and more. +- [AVSessionController](#avsessioncontroller): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> All the APIs provided by this module are system APIs. ## Modules to Import @@ -28,7 +30,7 @@ Creates a media session. This API uses a promise to return the result. An abilit | Name| Type | Mandatory| Description | | ------ | ------------------------------- | ---- | ------------------------------ | -| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information.| +| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information.| | tag | string | Yes | Custom session name. | | type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video.| @@ -39,13 +41,13 @@ Creates a media session. This API uses a promise to return the result. An abilit | --------------------------------- | ------------------------------------------------------------ | | Promise<[AVSession](#avsession)\> | Promise used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| -**Error codes** +**Error codes** For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -76,18 +78,17 @@ Creates a media session. This API uses an asynchronous callback to return the re | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information. | +| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information. | | tag | string | Yes | Custom session name. | | type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video. | | callback | AsyncCallback<[AVSession](#avsession)\> | Yes | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -127,12 +128,11 @@ Obtains the descriptors of all sessions. This API uses a promise to return the r | Promise\\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -168,12 +168,11 @@ Obtains the descriptors of all sessions. This API uses an asynchronous callback | callback | AsyncCallback\>\> | Yes | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 |Session service exception | +| 6600101 |Session service exception. | **Example** @@ -217,13 +216,12 @@ Creates a session controller based on the session ID. Multiple session controlle | Promise<[AVSessionController](#avsessioncontroller)\> | Promise used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -270,13 +268,12 @@ Creates a session controller based on the session ID. Multiple session controlle | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -333,14 +330,13 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | Promise | Promise used to return the result. If the cast is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600104 | The remote session connection failed | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600104 | The remote session connection failed. | **Example** @@ -386,14 +382,13 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | callback | AsyncCallback | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600104 | The remote session connection failed | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600104 | The remote session connection failed. | **Example** @@ -438,12 +433,11 @@ Subscribes to session creation, session destruction, and top session change even | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes | Callback used to report the session descriptor. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -487,12 +481,11 @@ Unsubscribes from session creation, session destruction, and top session change | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **session** parameter in the callback describes a media session. The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -518,12 +511,11 @@ Subscribes to session service death events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -549,12 +541,11 @@ Unsubscribes from session service death events. | callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -587,13 +578,12 @@ Sends a system key event to the top session. This API uses a promise to return t | Promise | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | **Example** @@ -630,13 +620,12 @@ Sends a system key event to the top session. This API uses an asynchronous callb | callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | **Example** @@ -678,14 +667,13 @@ Sends a system control command to the top session. This API uses a promise to re | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** @@ -733,14 +721,13 @@ Sends a system control command to the top session. This API uses an asynchronous | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** @@ -770,7 +757,7 @@ avSession.sendSystemControlCommand(avcommand, function (err) { }); ``` -## AVSession +## AVSession An **AVSession** object is created by calling [avSession.createAVSession](#avsessioncreateavsession). The object enables you to obtain the session ID and set the metadata and playback state. @@ -810,13 +797,12 @@ Sets session metadata. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -860,13 +846,12 @@ Sets session metadata. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -917,13 +902,12 @@ Sets information related to the session playback state. This API uses a promise | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -959,13 +943,12 @@ Sets information related to the session playback state. This API uses an asynchr | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -997,9 +980,9 @@ Sets a launcher ability. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| **Return value** @@ -1008,13 +991,12 @@ Sets a launcher ability. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1026,8 +1008,8 @@ let wantAgentInfo = { wants: [ { deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", action: "action1", entities: ["entity1"], type: "MIMETYPE", @@ -1068,19 +1050,18 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1092,8 +1073,8 @@ let wantAgentInfo = { wants: [ { deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", action: "action1", entities: ["entity1"], type: "MIMETYPE", @@ -1141,13 +1122,12 @@ Obtains the controller corresponding to this session. This API uses a promise to | Promise<[AVSessionController](#avsessioncontroller)> | Promise used to return the session controller.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1176,13 +1156,12 @@ Obtains the controller corresponding to this session. This API uses an asynchron | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1213,13 +1192,12 @@ Obtains information about the output device for this session. This API uses a pr | Promise<[OutputDeviceInfo](#outputdeviceinfo)> | Promise used to return the output device information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1246,13 +1224,12 @@ Obtains information about the output device for this session. This API uses an a | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1281,13 +1258,12 @@ Activates this session. A session can be used only after being activated. This A | Promise | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1314,13 +1290,12 @@ Activates this session. A session can be used only after being activated. This A | callback | AsyncCallback | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1349,13 +1324,12 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | Promise | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1384,13 +1358,12 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | callback | AsyncCallback | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1419,13 +1392,12 @@ Destroys this session. This API uses a promise to return the result. | Promise | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1453,13 +1425,12 @@ Destroys this session. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1489,13 +1460,12 @@ Subscribes to playback command events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1539,13 +1509,12 @@ Subscribes to the seek event. | callback | (time: number) => void | Yes | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** The session does not exist @@ -1571,13 +1540,12 @@ Subscribes to the event for setting the playback speed. | callback | (speed: number) => void | Yes | Callback used for subscription. The **speed** parameter in the callback indicates the playback speed. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1603,13 +1571,12 @@ Subscribes to the event for setting the loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | Yes | Callback used for subscription. The **mode** parameter in the callback indicates the loop mode. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1635,13 +1602,12 @@ Subscribes to the event for favoriting a media asset. | callback | (assetId: string) => void | Yes | Callback used for subscription. The **assetId** parameter in the callback indicates the media asset ID. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1667,13 +1633,12 @@ Subscribes to the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | Yes | Callback used for subscription. The **event** parameter in the callback indicates the key event. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1699,13 +1664,12 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1731,13 +1695,12 @@ Unsubscribes from playback command events. | callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1767,13 +1730,12 @@ Unsubscribes from the seek event. | callback | (time: number) => void | No | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1797,13 +1759,12 @@ Unsubscribes from the event for setting the playback speed. | callback | (speed: number) => void | No | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1827,13 +1788,12 @@ Unsubscribes from the event for setting loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | No | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1857,13 +1817,12 @@ Unsubscribes from the event for favoriting a media asset. | callback | (assetId: string) => void | No | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1887,13 +1846,12 @@ Unsubscribes from the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1917,13 +1875,12 @@ Unsubscribes from playback device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1933,7 +1890,7 @@ session.off('outputDeviceChange'); -## AVSessionController +## AVSessionController An AV session controller is created by calling [avSession.createController](#avsessioncreatecontroller). Through the AV session controller, you can query the session ID, send commands and events to a session, and obtain session metadata and playback state information. @@ -1972,14 +1929,13 @@ Obtains the information related to the playback state. This API uses a promise t | Promise<[AVPlaybackState](#avplaybackstate)\> | Promise used to return the **AVPlaybackState** object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2005,14 +1961,13 @@ Obtains the information related to the playback state. This API uses an asynchro | callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | Yes | Callback used to return the **AVPlaybackState** object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2040,14 +1995,13 @@ Obtains the session metadata. This API uses a promise to return the result. | Promise<[AVMetadata](#avmetadata)\> | Promise used to return the metadata obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2073,14 +2027,13 @@ Obtains the session metadata. This API uses an asynchronous callback to return t | callback | AsyncCallback<[AVMetadata](#avmetadata)\> | Yes | Callback used to return the metadata obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2108,13 +2061,12 @@ Obtains the output device information. This API uses a promise to return the res | Promise<[OutputDeviceInfo](#outputdeviceinfo)\> | Promise used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2140,13 +2092,12 @@ Obtains the output device information. This API uses an asynchronous callback to | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2175,16 +2126,15 @@ Sends a key event to the session corresponding to this controller. This API uses | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | **Return value** @@ -2218,19 +2168,18 @@ Sends a key event to the session corresponding to this controller. This API uses | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------- | | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | **Example** @@ -2257,19 +2206,18 @@ Obtains the **WantAgent** object saved by the application in the session. This A **Return value** -| Type | Description | -| ------------------------------------------- | ------------------------------------------------------------ | -| Promise<[WantAgent](js-apis-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| +| Type | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2293,19 +2241,18 @@ Obtains the **WantAgent** object saved by the application in the session. This A **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[WantAgent](js-apis-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2336,13 +2283,12 @@ Obtains the playback position. | number | Playback position, in milliseconds.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2365,14 +2311,13 @@ Checks whether the session is activated. This API uses a promise to return the r | Promise | Promise used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2399,14 +2344,13 @@ Checks whether the session is activated. This API uses an asynchronous callback | callback | AsyncCallback | Yes | Callback used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2435,13 +2379,12 @@ Destroys this controller. A controller can no longer be used after being destroy | Promise | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2468,13 +2411,12 @@ Destroys this controller. A controller can no longer be used after being destroy | callback | AsyncCallback | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2503,14 +2445,13 @@ Obtains valid commands supported by the session. This API uses a promise to retu | Promise\> | Promise used to return a set of valid commands.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2537,14 +2478,13 @@ Obtains valid commands supported by the session. This API uses an asynchronous c | callback | AsyncCallback\\> | Yes | Callback used to return a set of valid commands.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2579,17 +2519,16 @@ Sends a control command to the session through the controller. This API uses a p | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | **Example** @@ -2628,17 +2567,16 @@ Sends a control command to the session through the controller. This API uses an | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | **Example** @@ -2680,13 +2618,12 @@ Subscribes to the metadata change event. | callback | (data: [AVMetadata](#avmetadata)) => void | Yes | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2718,13 +2655,12 @@ Subscribes to the playback state change event. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | Yes | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2755,13 +2691,12 @@ Subscribes to the session destruction event. | callback | () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2787,13 +2722,12 @@ Subscribes to the session activation state change event. | callback | (isActive: boolean) => void | Yes | Callback used for subscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the service is activated, and **false** means the opposite. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ----------------------------- | -| 6600101 | Session service exception | -| 6600103 |The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 |The session controller does not exist. | **Example** @@ -2819,13 +2753,12 @@ Subscribes to valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | Yes | Callback used for subscription. The **commands** parameter in the callback is a set of valid commands. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2852,13 +2785,12 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ----------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2884,12 +2816,11 @@ Unsubscribes from metadata changes. | callback | (data: [AVMetadata](#avmetadata)) => void | No | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2913,12 +2844,11 @@ Unsubscribes from playback state changes. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | No | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2942,12 +2872,11 @@ Unsubscribes from the session destruction event. | callback | () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2971,12 +2900,11 @@ Unsubscribes from session activation state changes. | callback | (isActive: boolean) => void | No | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3000,12 +2928,11 @@ Unsubscribes from valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | No | Callback used for unsubscription. The **commands** parameter in the command is a set of valid commands.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message | | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3029,12 +2956,11 @@ Unsubscribes from output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID | Error Message | | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3132,7 +3058,7 @@ Describes the media metadata. | album | string | No | Album name. | | writer | string | No | Writer. | | composer | string | No | composer. | -| duration | string | No | Media duration, in ms. | +| duration | number | No | Media duration, in ms. | | mediaImage | image.PixelMap | string | No | Pixel map or image path (local path or network path) of the image. | | publishDate | Date | No | Release date. | | subtitle | string | No | Subtitle. | @@ -3217,10 +3143,10 @@ Enumerates the error codes used in the media session. | Name | Value | Description | | ------------------------------ | ------- | ------------------------------- | -| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception | -| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist | -| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist | -| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed | -| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command | -| ERR_CODE_SESSION_INACTIVE | 6600106 | The session not active | -| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Command or event overload | +| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception. | +| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist. | +| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist. | +| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed. | +| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command. | +| ERR_CODE_SESSION_INACTIVE | 6600106 | The session is not activated. | +| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Too many commands or events. | diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 49032dcbd7b58a404bd779635fc109a5f2336c38..6080d2c9bc52e30b6fa987f9cb65ea9b42a28024 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -159,12 +159,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| 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).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -187,7 +187,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -205,7 +205,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; @@ -217,13 +217,13 @@ function callback(err, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -251,11 +251,11 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| 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).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** @@ -276,7 +276,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -297,17 +297,17 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -365,7 +365,7 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callbac Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; function callback(err, data) { @@ -376,7 +376,7 @@ function callback(err, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { backgroundTaskManager.stopBackgroundRunning(this.context, callback); } @@ -422,10 +422,10 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { console.info("Operation stopBackgroundRunning succeeded"); diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 197e25cfce48edc49798b438745adc13c35ab9d5..41d13ba5741ecf4324b1f4c859fb2a0a4bdf1d19 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,11 +1,10 @@ -# Battery Info +# @ohos.batteryInfo (Battery Information) -The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. +The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status. -> **NOTE** +> **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. - ## Modules to Import ```js diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md index 917bc81d2f3eecef3f25d609db686b0d9dae44a2..2bb3159fc3912a6a1fe272451ce31aa812052432 100644 --- a/en/application-dev/reference/apis/js-apis-batteryStatistics.md +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -1,6 +1,6 @@ -# Battery Statistics +# @ohos.batteryStatistics (Battery Statistics) -This module provides APIs for querying software and hardware power consumption statistics. +The **batteryStatistics** module provides APIs for querying software and hardware power consumption statistics. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index df783bbda132f5da29e152e146cc6cb56316f083..bd003733a485c1601ac251697461e78b863976a8 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,6 +1,6 @@ -# Screen Brightness +# @ohos.brightness (Screen Brightness) -The Brightness module provides an API for setting the screen brightness. +The **brightness** module provides an API for setting the screen brightness. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index b5c914e7725c878305ff0235a33d8d98d6c6d6e4..72e65e53e63380ef4ea0aa9b33796e236bc7ee84 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -1,11 +1,12 @@ -# Buffer +# @ohos.buffer (Buffer) -> **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. +A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data. -A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data. +You can use the APIs provided by the Buffer module to process images and a large amount of binary data, and receive or upload files. -You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload files. +> **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 @@ -21,55 +22,23 @@ Enumerates the supported encoding formats of strings. | Encoding Format | Description | | ------- | -------------------- | -| ascii | ASCII format. | -| utf8 | UTF-8 | -| utf-8 | UTF-8 format.| -| utf16le | UTF-16LE format.| -| ucs2 | UTF-16LE format.| -| ucs-2 | UTF-16LE format.| -| base64 | Base64 format.| -| base64url | Base64 format.| -| latin1 | ASCII format.| -| binary | Binary format.| -| hex | Hexadecimal format.| - -## Buffer - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Length of the buffer, in bytes.| -| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| -| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.| - -**Error codes** - -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). - -| ID| Error Message| -| -------- | -------- | -| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | - -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.from("1236"); -console.log(JSON.stringify(buf.length)); -let arrayBuffer = buf.buffer; -console.log(JSON.stringify(new Uint8Array(arrayBuffer))); -console.log(JSON.stringify(buf.byteOffset)); -``` - -### alloc +| 'ascii' | ASCII format, which is case insensitive.| +| 'utf8' | UTF-8 format, which is case insensitive.| +| 'utf-8' | UTF-8 format, which is case insensitive.| +| 'utf16le' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs2' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs-2' | UTF-16 little-endian format, which is case insensitive.| +| 'base64' | Base64 format, which is case insensitive.| +| 'base64url' | Base64 format, which is case insensitive.| +| 'latin1' | ASCII format, which is case insensitive.| +| 'binary' | Binary format, which is case insensitive.| +| 'hex' | Hexadecimal format, which is case insensitive.| + +## buffer.alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer -Allocates and initializes a **Buffer** instance of the specified size. +Creates and initializes a **Buffer** instance of the specified length. **System capability**: SystemCapability.Utils.Lang @@ -77,8 +46,8 @@ Allocates and initializes a **Buffer** instance of the specified size. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| -| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| +| fill | string \| Buffer \| number | No| Value to be filled in the buffer. The default value is **0**.| | encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| **Return value** @@ -97,12 +66,12 @@ let buf2 = buffer.alloc(5, 'a'); let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); ``` -### allocUninitializedFromPool +## buffer.allocUninitializedFromPool allocUninitializedFromPool(size: number): Buffer -Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. -To initialize the **Buffer** instance, call **fill()**. +Creates a **Buffer** instance of the specified size from the buffer pool, without initializing it. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -110,7 +79,7 @@ To initialize the **Buffer** instance, call **fill()**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -127,11 +96,12 @@ let buf = buffer.allocUninitializedFromPool(10); buf.fill(0); ``` -### allocUninitialized +## buffer.allocUninitialized allocUninitialized(size: number): Buffer -Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +Creates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -139,7 +109,7 @@ Allocates a **Buffer** instance of the specified size, without initializing it. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes|Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -156,7 +126,7 @@ let buf = buffer.allocUninitialized(10); buf.fill(0); ``` -### byteLength +## buffer.byteLength byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number @@ -169,7 +139,7 @@ Obtains the number of bytes of a string based on the encoding format. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| -| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format of the string. The default value is **utf-8**.| **Return value** @@ -187,7 +157,7 @@ console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8') // Print: ½ + ¼ = ¾: 9 characters, 12 bytes ``` -### compare +## buffer.compare compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 @@ -221,11 +191,11 @@ let res = buf1.compare(buf2); console.log(Number(res).toString()); // Print 1. ``` -### concat +## buffer.concat concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer -Concatenates an array of **Buffer** instances into a new instance of the specified length. +Concatenates an array of **Buffer** instances of the specified length into a new instance. **System capability**: SystemCapability.Utils.Lang @@ -234,7 +204,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| -| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.| +| totalLength | number | No| Total length of bytes to be copied.| **Return value** @@ -244,7 +214,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -261,7 +231,7 @@ let buf = buffer.concat([buf1, buf2]); console.log(buf.toString('hex')); // 3132333461626364 ``` -### from +## buffer.from from(array: number[]): Buffer; @@ -290,11 +260,11 @@ let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); console.log(buf.toString('hex')); // 627566666572 ``` -### from +## buffer.from from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer -Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances. +Creates a **Buffer** instance of the specified length that shares memory with **arrayBuffer**. **System capability**: SystemCapability.Utils.Lang @@ -314,7 +284,7 @@ Creates a **Buffer** instance that shares memory with the specified array of **B **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -329,7 +299,7 @@ let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); ``` -### from +## buffer.from from(buffer: Buffer | Uint8Array): Buffer @@ -341,7 +311,7 @@ Creates a **Buffer** instance with the copy of another instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy. | +| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy.| **Return value** @@ -358,7 +328,7 @@ let buf1 = buffer.from('buffer'); let buf2 = buffer.from(buf1); ``` -### from +## buffer.from from(object: Object, offsetOrEncoding: number | string, length: number): Buffer @@ -385,10 +355,10 @@ Creates a **Buffer** instance based on the specified object. ```ts import buffer from '@ohos.buffer'; -let buf = buffer.from(new String('this is a test')); +let buf = buffer.from(new String('this is a test'), 'utf8', 14); ``` -### from +## buffer.from from(string: String, encoding?: BufferEncoding): Buffer @@ -418,11 +388,11 @@ let buf1 = buffer.from('this is a test'); let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); console.log (buf1.toString()); // Print: this is a test -console.log(buf2.toString()); +console.log (buf2.toString()); // print: this is a test ``` -### isBuffer +## buffer.isBuffer isBuffer(obj: Object): boolean @@ -454,7 +424,7 @@ buffer.isBuffer([]); // false buffer.isBuffer(new Uint8Array(1024)); // false ``` -### isEncoding +## buffer.isEncoding isEncoding(encoding: string): boolean @@ -485,6 +455,70 @@ console.log(buffer.isEncoding('utf/8').toString()); // Print: false console.log(buffer.isEncoding('').toString()); // Print: false ``` +## buffer.transcode + +transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer + +Transcodes the given **Buffer** or **Uint8Array** object from one encoding format to another. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | Yes| Instance to encode.| +| fromEnc | string | Yes| Current encoding format.| +| toEnc | string | Yes| Target encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | New **Buffer** instance in the target encoding format.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Buffer + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Length of the **Buffer** instance, in bytes.| +| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| +| byteOffset | number | Yes| No| Offset of the **Buffer** instance in the memory pool.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from("1236"); +console.log(JSON.stringify(buf.length)); +let arrayBuffer = buf.buffer; +console.log(JSON.stringify(new Uint8Array(arrayBuffer))); +console.log(JSON.stringify(buf.byteOffset)); +``` + ### compare compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 @@ -507,7 +541,15 @@ Compares this **Buffer** instance with another instance. | Type| Description| | -------- | -------- | -| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted. | +| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[targetStart/targetEnd/sourceStart/sourceEnd]" is out of range. | **Example** @@ -547,7 +589,7 @@ Copies data at the specified position in this **Buffer** instance to the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -578,6 +620,13 @@ Creates and returns an iterator that contains key-value pairs of this **Buffer** **System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Key of the iterator.| +| number | Value of the iterator.| + **Example** ```ts @@ -647,7 +696,7 @@ Fills this **Buffer** instance at the specified position. By default, data is fi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -739,7 +788,7 @@ Creates and returns an iterator that contains the keys of this **Buffer** instan | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator.| +| IterableIterator<number> | Iterator created.| **Example** @@ -789,7 +838,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // Print: 17 readBigInt64BE(offset?: number): bigint -Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset. +Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -807,7 +856,7 @@ Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at t **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -848,7 +897,7 @@ Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance a **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -889,7 +938,7 @@ Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance a **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -930,7 +979,7 @@ Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instanc **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -971,7 +1020,7 @@ Reads a big-endian double-precision floating-point number from this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1011,7 +1060,7 @@ Reads a little-endian double-precision floating-point number from this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1051,7 +1100,7 @@ Reads a big-endian single-precision floating-point number from this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1091,7 +1140,7 @@ Reads a little-endian single-precision floating-point number from this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1131,7 +1180,7 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1172,7 +1221,7 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1212,7 +1261,7 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1252,7 +1301,7 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1292,7 +1341,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1334,7 +1383,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1378,7 +1427,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1419,7 +1468,7 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1461,7 +1510,7 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1503,7 +1552,7 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1545,7 +1594,7 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1586,7 +1635,7 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1628,7 +1677,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1670,7 +1719,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1741,7 +1790,7 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1776,7 +1825,7 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1811,7 +1860,7 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1901,7 +1950,7 @@ Creates and returns an iterator that contains the values of this **Buffer** inst | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator created.| +| IterableIterator<number> | Iterator.| **Example** @@ -1940,7 +1989,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -1984,7 +2033,7 @@ Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at th **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2023,7 +2072,7 @@ Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2062,7 +2111,7 @@ Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2101,7 +2150,7 @@ Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2140,7 +2189,7 @@ Writes a big-endian double-precision floating-point number to this **Buffer** in **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2179,7 +2228,7 @@ Writes a little-endian double-precision floating-point number to this **Buffer** **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2218,7 +2267,7 @@ Writes a big-endian single-precision floating-point number to this **Buffer** in **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2258,7 +2307,7 @@ Writes a little-endian single-precision floating-point number to this **Buffer** **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2297,7 +2346,7 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2338,7 +2387,7 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2378,7 +2427,7 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2417,7 +2466,7 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2457,7 +2506,7 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2497,7 +2546,7 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2538,7 +2587,7 @@ Writes a little-endian signed value of the specified length to this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2577,7 +2626,7 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2619,7 +2668,7 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2659,7 +2708,7 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2699,7 +2748,7 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2738,7 +2787,7 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2778,7 +2827,7 @@ Writes an unsigned big-endian value of the specified length to this **Buffer** i **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2818,7 +2867,7 @@ Writes an unsigned little-endian value of the specified length to this **Buffer* **Error codes** -For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -2833,38 +2882,6 @@ let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntLE(0x1234567890ab, 0, 6); ``` -### transcode - -transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer - -Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| source | Buffer \| Uint8Array | Yes| Instance to transcode. | -| fromEnc | string | Yes| Current encoding format.| -| toEnc | string | Yes| Target encoding format.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Buffer | New **Buffer** instance in the target encoding format.| - -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.alloc(50); -let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); -console.log(newBuf.toString('ascii')); -``` - ## Blob ### Attributes @@ -2941,7 +2958,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc **Return value** | Type| Description| | -------- | -------- | -| Blob | **Blob** instance created. | +| Blob | New **Blob** instance created.| **Example** ```ts @@ -2954,7 +2971,7 @@ let blob3 = blob.slice(0, 2, "MIME"); text(): Promise<string> -Returns text in UTF-8 format. +Returns text in UTF-8 format. This API uses a promise to return the result. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 315e7c0f045ba3b26520ed2a69f41f242872b8e6..cc6e202d2d30e486563f3ed1f1f842f5d15a5a90 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated). > **NOTE** > @@ -12,32 +12,32 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| name | string | Yes | No | Ability name. | -| label | string | Yes | No | Ability name visible to users. | -| description | string | Yes | No | Ability description. | -| icon | string | Yes | No | Index of the ability icon resource file. | -| descriptionId | number | Yes | No | Ability description ID. | -| iconId | number | Yes | No | Ability icon ID. | -| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | -| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| -| backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| -| type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | -| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | -| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| -| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | -| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | -| readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| -| writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing [GET_ABILITY_INFO_WITH_APPLICATION](js-apis-Bundle.md).| -| uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| -| labelId | number | Yes | No | Ability label ID. | -| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| -| metadata8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| -| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | +| Name | Type | Readable| Writable| Description | +| --------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | No | Bundle name. | +| name | string | Yes | No | Ability name. | +| label | string | Yes | No | Ability name visible to users. | +| description | string | Yes | No | Ability description. | +| icon | string | Yes | No | Index of the ability icon resource file. | +| descriptionId | number | Yes | No | ID of the ability description. | +| iconId | number | Yes | No | ID of the ability icon. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | +| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used. | +| targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| +| backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| +| type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | +| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | +| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing in GET_ABILITY_INFO_WITH_PERMISSION to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| +| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | +| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | +| readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model. | +| writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model. | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing in GET_ABILITY_INFO_WITH_APPLICATION to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| +| uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| +| labelId | number | Yes | No | ID of the ability label. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| +| metadata8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing in GET_ABILITY_INFO_WITH_METADATA to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| +| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index c1667a66eb011d24a1b7ce79061eab0f454604a3..89444bc41bf2f3d55bf71c18b4c59c497dc37c20 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated). > **NOTE** > @@ -16,21 +16,21 @@ The **ApplicationInfo** module provides application information. Unless otherwis |----------------------------|------------------------------------------------------------------------|-----|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | name | string | Yes | No | Application name. | | description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | +| descriptionId | number | Yes | No | ID of the application description. | | systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | +| labelId | string | Yes | No | ID of the application label. | | icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | +| iconId | string | 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. | -| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units. | +| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to telematics devices. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_PERMISSION](js-apis-Bundle.md). | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing in GET_APPLICATION_INFO_WITH_PERMISSION to [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated). | | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | | entryDir | string | Yes | No | Path for storing application files. | | codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_METADATA](js-apis-Bundle.md). | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing in GET_APPLICATION_INFO_WITH_METADATA to [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated). | | removable8+ | boolean | Yes | No | Whether the application is removable. | | accessTokenId8+ | number | Yes | No | Access token ID of the application. | | uid8+ | number | Yes | No | UID of the application. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index c14419e736e1c2142fb47157826c42fb0d5cff34..16e4d3105d118613d1720dd2d0a8e4545e5c0344 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,6 +1,6 @@ # BundleInfo -The **BundleInfo** module provides bundle information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **BundleInfo** module defines the bundle information, which can be obtained through [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated). > **NOTE** > @@ -10,33 +10,33 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie > This API is deprecated since API version 9. You are advised to use [bundleManager-BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. -**System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type | Readable| Writable| Description | -| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | -| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| -| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | +| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing in GET_BUNDLE_WITH_ABILITIES to [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated).| +| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing in GET_BUNDLE_WITH_REQUESTED_PERMISSION to [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated).| +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing in GET_BUNDLE_WITH_REQUESTED_PERMISSION to [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated).| +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 0570453b5cb9c1bfa6a1e0f0acb9dda16562005e..7523cde56562a53a6129d810dff30ba95a718a64 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -8,7 +8,7 @@ The **BundleInstaller** module provides APIs for you to install, uninstall, and ## BundleInstaller.install(deprecated) -> This API is deprecated since API version 9. You are advised to use [install](js-apis-installer.md) instead. +> This API is deprecated since API version 9. You are advised to use [@ohos.bundle.installer.install](js-apis-installer.md) instead. install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -26,10 +26,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| -| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | | callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status. | **Example** @@ -43,7 +43,7 @@ let installParam = { installFlag: 1, }; -bundle.getBundleInstaller().then(installer=>{ +bundle.getBundleInstaller().then(installer => { installer.install(hapFilePaths, installParam, err => { if (err) { console.error('install failed:' + JSON.stringify(err)); @@ -76,10 +76,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | -| bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | | callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status.| **Example** @@ -93,7 +93,7 @@ let installParam = { installFlag: 1, }; -bundle.getBundleInstaller().then(installer=>{ +bundle.getBundleInstaller().then(installer => { installer.uninstall(bundleName, installParam, err => { if (err) { console.error('uninstall failed:' + JSON.stringify(err)); @@ -125,10 +125,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | -| bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | | callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the recovery status.| **Example** @@ -143,7 +143,7 @@ let installParam = { installFlag: 1, }; -bundle.getBundleInstaller().then(installer=>{ +bundle.getBundleInstaller().then(installer => { installer.recover(bundleName, installParam, err => { if (err) { console.error('recover failed:' + JSON.stringify(err)); @@ -166,9 +166,9 @@ Describes the parameters required for bundle installation, recovery, or uninstal | Name | Type | Readable| Writable| Description | | ----------- | ------- | ---- | ---- | ------------------ | -| userId | number | Yes | No | User ID. | -| installFlag | number | Yes | No | Installation flag. | -| isKeepData | boolean | Yes | No | Whether data is kept.| +| userId | number | Yes | Yes | User ID. The default value is the user ID of the caller.| +| installFlag | number | Yes | Yes | Installation flag.
**1** (default): overwrite installation.
**16**: installation-free.| +| isKeepData | boolean | Yes | Yes | Whether data is kept. The default value is **false**.| ## InstallStatus(deprecated) @@ -180,17 +180,17 @@ Describes the bundle installation or uninstall status. | Name | Type | Readable| Writable| Description | | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | -| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | -| statusMessage | string | Yes | No | Installation or uninstall status message.| +| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. The value must be defined in [InstallErrorCode](js-apis-Bundle.md#installerrorcode). | +| statusMessage | string | Yes | No | Installation or uninstall status message.
**SUCCESS**: install_succeed
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstallation failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstallation conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstallation permission. | ## Obtaining the Sandbox Path -For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the sage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. +For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the stage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. **Example** ``` ts // Stage model -import Ability from '@ohos.application.Ability'; -class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; +export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let context = this.context; let pathDir = context.filesDir; diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index b20de58d074a83dea5cb0992e21087ae64b990bb..96bdaca69234ba8f22a69eb0dbbde6824f991b4d 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -17,7 +17,7 @@ Describes the element name information, which identifies the basic information a | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | | deviceId | string | Yes | Yes | Device ID. | -| bundleName | string | Yes | Yes | Bundle name of the application. | -| abilityName | string | Yes | Yes | Name of the ability. | +| bundleName | string | Yes | Yes | Bundle name. | +| abilityName | string | Yes | Yes | Ability name. | | uri | string | Yes | Yes | Resource ID. | | shortName | string | Yes | Yes | Short name of the ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 5540aa2bc56b9f8e34fda11d11048b8177816b95..2b3f7eede2c099cd94f2a08bbba8bbc50d67e782 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -1,6 +1,6 @@ # HapModuleInfo -The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). +The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [bundle.getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfodeprecated). > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md index 7df2416aa44dd60847a918fb982807cfc27fd058..2ba6d913831b33b67834fa24aa1c4307259019d7 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -8,7 +8,7 @@ The **LauncherAbilityInfo** module provides information about the launcher abili ## LauncherAbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -18,7 +18,7 @@ The **LauncherAbilityInfo** module provides information about the launcher abili | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. | -| labelId | number | Yes | No | Label ID of the launcher ability. | -| iconId | number | Yes | No | Icon ID of the launcher ability. | -| userId | number | Yes | No | User ID of the launcher ability. | +| labelId | number | Yes | No | ID of the launcher ability label. | +| iconId | number | Yes | No | ID of the launcher ability icon. | +| userId | number | Yes | No | ID of the launcher ability user. | | installTime | number | Yes | No | Time when the launcher ability is installed. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 18707feeb05902b5740b00544b3a23a43c09acce..be4782ca7915986bbf60cce82edd41fa924b3bbd 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -10,6 +10,7 @@ The **ModuleInfo** module provides module information of an application. > This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework + | Name | Type | Readable| Writable| Description | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | Yes | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index ded02c772794179d9e8276292ab1be939a208d8f..b99bd49d939b65315f9cc8e983e5ffe4641fe1a3 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -18,5 +18,5 @@ The **PermissionDef** module provides permission details defined in the configur | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | | grantMode | number | Yes | No | Grant mode of the permission. The value **0** means that the system automatically grants the permission after the application installation, and **1** means that the application needs to dynamically request the permission from the user.| -| labelId | number | Yes | No | Label ID of the permission. | -| descriptionId | number | Yes | No | Description ID of the permission. | +| labelId | number | Yes | No | ID of the permission label. | +| descriptionId | number | Yes | No | ID of the permission description. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index 1a603da33b3403dafbac79e1bfcd31c5dde9896c..2cec8a9859984bb26d38e809b8bc0c8dbae8ff74 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -10,9 +10,9 @@ The **shortcutInfo** module defines shortcut information configured in the confi > This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework - **System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. | Name | Type | Readable| Writable| Description | | ------------------------- | ------ | ---- | ---- | -------------------- | @@ -23,13 +23,12 @@ The **shortcutInfo** module defines shortcut information configured in the confi > This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. - - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | | id | string | Yes | No | ID of the application to which the shortcut belongs. | -| bundleName | string | Yes | No | Name of the bundle that contains the shortcut. | +| bundleName | string | Yes | No | Name of the bundle that contains the shortcut.| | hostAbility | string | Yes | No | Local ability information of the shortcut. | | icon | string | Yes | No | Icon of the shortcut. | | iconId8+ | number | Yes | No | Icon ID of the shortcut. | @@ -40,5 +39,3 @@ The **shortcutInfo** module defines shortcut information configured in the confi | isStatic | boolean | Yes | No | Whether the shortcut is static. | | isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| | isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index f95125fb1c7228f9eade37f423b624c3289c0e34..47646ca01faf5e6915e3d4ecc42e6596697f79bf 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -19,3 +19,4 @@ The **RemoteAbilityInfo** module provides information about a remote ability. | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name information of the ability. | | label | string | Yes | No | Ability name. | | icon | string | Yes | No | Icon of the ability.| + 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 71f2ee6483c12ab65106208f58c902d0d04fa630..cacab28b20157441ee4f64bc69261c7f37f0809f 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_ABILITY_INFO_DEFAULT](js-apis-bundleManager.md). +The **AbilityInfo** module defines the ability information. A system application can obtain the ability information through [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo). The input parameter [abilityFlags](js-apis-bundleManager.md#abilityflag) specifies the information to be contained in the returned [AbilityInfo](js-apis-bundleManager-abilityInfo.md) object. > **NOTE** > @@ -8,31 +8,31 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi ## AbilityInfo - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | -| --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | +| --------------------- | -------------------------------------------------------- | ---- | ---- | ------------------------------------------ | +| bundleName | string | Yes | No | Bundle name. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | | name | string | Yes | No | Ability name. | | label | string | Yes | No | Ability name visible to users. | -| labelId | number | Yes | No | ID of the ability label. | +| labelId | number | Yes | No | ID of the ability label. | | description | string | Yes | No | Ability description. | | descriptionId | number | Yes | No | ID of the ability description. | | 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. | -| type | [AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type.
This attribute can be used only in the FA model. | +| 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. | -| permissions | Array\ | Yes | No | Permissions required for other bundles to call the ability. The information is obtained by using **GET_ABILITY_INFO_WITH_PERMISSION**.| +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability. The permissions can be obtained by passing in **GET_ABILITY_INFO_WITH_PERMISSION** to the **abilityFlags** parameter of [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo).| | readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| | writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| | uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | -| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information is obtained by using **GET_ABILITY_INFO_WITH_APPLICATION**.| -| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. The information is obtained by using **GET_ABILITY_INFO_WITH_METADATA**.| +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information can be obtained by passing in **GET_ABILITY_INFO_WITH_APPLICATION** to the **abilityFlags** parameter of [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo).| +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. The information can be obtained by passing in **GET_ABILITY_INFO_WITH_METADATA** to the **abilityFlags** parameter of [bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo).| | enabled | boolean | Yes | No | Whether the ability is enabled. | | supportWindowModes | Array\<[SupportWindowMode](js-apis-bundleManager.md#supportwindowmode)> | Yes | No | Window modes supported by the ability. | | windowSize|[WindowSize](#windowsize) | Yes | No | Window size.| @@ -41,7 +41,7 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi Describes the window size. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | -------------------| ------- | ---- | ---- | ---------------------------------- | @@ -50,4 +50,4 @@ Describes the window size. | maxWindowWidth | number | Yes | No | Maximum width of the window in free window mode. The unit is vp.| | minWindowWidth | number | Yes | No | Minimum width of the window in free window mode. The unit is vp.| | maxWindowHeight | number | Yes | No | Maximum height of the window in free window mode. The unit is vp.| -| minWindowHeight | number | Yes | No | Maximum height of the window in free window mode. The unit is vp.| +| minWindowHeight | number | Yes | No | Minimum height of the window in free window mode. The unit is vp.| 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 d4c0b4f4c2bc803e04ee8d88416aed8351c5c86d..2537274b8d5bd50d6c47258be2770bd5d51a9733 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides information about an application. Unless otherwise specified, the information is obtained through [GET_APPLICATION_INFO_DEFAULT](js-apis-bundleManager.md). +The **ApplicationInfo** module defines the application information. A system application can obtain its own or others' application information through [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo). The input parameter [appFlags](js-apis-bundleManager.md#applicationflag) specifies the information to be contained in the returned [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) object. > **NOTE** > @@ -9,21 +9,21 @@ The **ApplicationInfo** module provides information about an application. Unless ## ApplicationInfo **System capability**: SystemCapability.BundleManager.BundleFramework.Core + | Name | Type | Readable| Writable| Description | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Application name. | | description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | ID of the application 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. | -| labelId | number | Yes | No | ID of the application label. | +| labelId | number | Yes | No | ID of the application label. | | icon | string | Yes | No | Application icon. | -| iconId | number | Yes | No | ID of the application 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 information is obtained by using **GET_APPLICATION_INFO_WITH_PERMISSION**.| -| entryDir | string | Yes | No | Path for storing application files. | +| 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).| | codePath | string | Yes | No | Installation directory of the application. | -| metadata | Map\> | Yes | No | Metadata of the application. The information is obtained by using **GET_APPLICATION_INFO_WITH_METADATA**.| +| metadata | Map\> | Yes | No | Metadata of the application. The information can be obtained by passing in **GET_APPLICATION_INFO_WITH_METADATA** to the **appFlags** parameter of [bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo).| | 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. | @@ -32,3 +32,4 @@ The **ApplicationInfo** module provides information about an application. Unless | descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | Yes| No| Description resource of the application. | | 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-bundleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md index 0f54e790c363ff484005ea27424180227a49a5a0..8e6821b79eb36a6bd93dd9aed2b9016a3029dad2 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md @@ -1,28 +1,30 @@ # BundleInfo -The **BundleInfo** module provides information about a bundle. Unless otherwise specified, the information is obtained through [GET_BUNDLE_INFO_DEFAULT](js-apis-bundle-bundleManager). +The **BundleInfo** module defines the bundle information. A system application can obtain its own or others' bundle information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own bundle information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). The input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) specifies the information to be contained in the returned [BundleInfo](js-apis-bundleManager-bundleInfo.md) object. > **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. + + ## BundleInfo - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Bundle name. | | vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | | versionName | string | Yes | No | Version description of the bundle. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | | targetVersion | number | Yes | No | Target API version required for running the bundle. | -| appInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information is obtained by using **GET_BUNDLE_INFO_WITH_APPLICATION**. | -| hapModulesInfo | Array\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | No | Module configuration information. The information is obtained by using **GET_BUNDLE_INFO_WITH_HAP_MODULE**. | -| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system. The information is obtained by using **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION**.| -| permissionGrantStates | Array\<[PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate)> | Yes | No | Permission grant state. The information is obtained by using **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION**. | -| signatureInfo | [SignatureInfo](#signatureinfo) | Yes | No | Signature information of the bundle. The information is obtained by using **GET_BUNDLE_INFO_WITH_SIGNATURE_INFO**. | +| appInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_APPLICATION** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | +| hapModulesInfo | Array\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | No | Module configuration information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo).| +| permissionGrantStates | Array\<[PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate)> | Yes | No | Permission grant state. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | +| signatureInfo | [SignatureInfo](#signatureinfo) | Yes | No | Signature information of the bundle. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_SIGNATURE_INFO** to the **bundleFlags** parameter of [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). | | installTime | number | Yes | No | Time when the bundle was installed. | | updateTime | number | Yes | No | Time when the bundle was updated. | @@ -31,12 +33,12 @@ The **BundleInfo** module provides information about a bundle. Unless otherwise Provides the detailed information of the permissions to request from the system. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------------------- | ----------------------- | ---- | ---- | ---------------------| | name | string | Yes | Yes | Name of the permission to request. | -| reason | string | Yes | Yes | Reason for requesting the permission. | +| reason | string | Yes | Yes | Reason for requesting the permission. | | reasonId | number | Yes | Yes | ID of the reason for requesting the permission.| | usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| @@ -46,7 +48,7 @@ Provides the detailed information of the permissions to request from the system. Describes the application scenario and timing for using the permission. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------- | -------------- | ---- | ---- | --------------------------- | @@ -57,7 +59,7 @@ Describes the application scenario and timing for using the permission. Describes the signature information of the bundle. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | --------- | -------------- | ---- | ---- | --------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md index 662f0e37640287de5e10273a45d8db327a4551da..9bed479551e9b4f6c9b198f83fd9ed0114d7f1f5 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -2,7 +2,6 @@ The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.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. @@ -14,7 +13,7 @@ The **ElementName** module provides element name information, which can be obtai | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | | deviceId | string | Yes | Yes | Device ID. | -| bundleName | string | Yes | Yes | Bundle name of the application. | +| bundleName | string | Yes | Yes | Bundle name. | | abilityName | string | Yes | Yes | Name of the ability. | | uri | string | Yes | Yes | Resource ID. | | shortName | string | Yes | Yes | Short name of the ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md index bc1542325379ddd73d4bb123e1e09eb2131b7d20..016b7af13fded843c7c85f05834669aa5e45c2bd 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md @@ -1,6 +1,6 @@ # ExtensionAbilityInfo -The **ExtensionAbilityInfo** module provides information about an Extension ability. Unless otherwise specified, all attributes are obtained through [getBundleInfo](js-apis-bundleManager.md), and flags are obtained through [GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY](js-apis-bundleManager.md#bundleflag). +The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A system application can obtain its own or others' ExtensionAbility information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own ExtensionAbility information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY** must be passed in to the input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) to obtain the information. > **NOTE** > @@ -10,19 +10,19 @@ The **ExtensionAbilityInfo** module provides information about an Extension abil **System capability**: SystemCapability.BundleManager.BundleFramework.Core -| Name | Type | Readable| Writable| Description | -| -------------------- | ----------------------------------------------------------- | ---- | ---- | -------------------------------------------------- | -| bundleName | string | Yes | No | Bundle name. | -| moduleName | string | Yes | No | Name of the HAP file to which the Extension ability belongs. | -| name | string | Yes | No | Name of the Extension ability. | -| labelId | number | Yes | No | Label ID of the Extension ability. | -| descriptionId | number | Yes | No | Description ID of the Extension ability. | -| iconId | number | Yes | No | Icon ID of the Extension ability. | -| isVisible | boolean | Yes | No | Whether the Extension ability can be called by other bundles. | -| extensionAbilityType | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | Type of the Extension ability. | -| permissions | Array\ | Yes | No | Permissions required for other bundles to call the Extension ability.| -| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information of the Extension ability. | -| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the Extension ability. | -| enabled | boolean | Yes | No | Whether the Extension ability is enabled. | -| readPermission | string | Yes | No | Permission required for reading data from the Extension ability. | -| writePermission | string | Yes | No | Permission required for writing data to the Extension ability. | +| Name | Type | Readable| Writable| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ---- | ---------------------------------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| moduleName | string | Yes | No | Name of the HAP file to which the ExtensionAbility belongs. | +| name | string | Yes | No | Name of the ExtensionAbility. | +| labelId | number | Yes | No | ID of the ExtensionAbility label. | +| descriptionId | number | Yes | No | ID of the ExtensionAbility description. | +| iconId | number | Yes | No | ID of the ExtensionAbility icon. | +| isVisible | boolean | Yes | No | Whether the ExtensionAbility can be called by other bundles. | +| extensionAbilityType | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | Type of the ExtensionAbility. | +| permissions | Array\ | Yes | No | Permissions required for other bundles to call the ExtensionAbility.| +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. | +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ExtensionAbility. | +| enabled | boolean | Yes | No | Whether the ExtensionAbility is enabled. | +| readPermission | string | Yes | No | Permission required for reading data from the ExtensionAbility. | +| writePermission | string | Yes | No | Permission required for writing data to the ExtensionAbility. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md index 23e9c8c5e547642d240474fe6cad459b793883c1..8fe0cc4768b4b0ac352fcd98d9cefad9cc2c1553 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md @@ -1,5 +1,7 @@ # HapModuleInfo +The **HapModuleInfo** module defines the HAP module information. A system application can obtain its own or others' HAP module information through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). A third-party application can obtain its own HAP module information through [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **GET_BUNDLE_INFO_WITH_HAP_MODULE** must be passed in to the input parameter [bundleFlags](js-apis-bundleManager.md#bundleflag) to obtain the information. + > **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. @@ -16,12 +18,11 @@ | label | string | Yes | No | Module label. | | labelId | number | Yes | No | ID of the module label. | | description | string | Yes | No | Module description. | -| descriptionId | number | Yes | No | ID of the module mescription. | +| descriptionId | number | Yes | No | ID of the module description. | | mainElementName | string | Yes | No | Name of the main ability. | | abilitiesInfo | Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | No | Ability information. | -| extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.| +| extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Yes | No | ExtensionAbility information.| | metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. | -| deviceTypes | Array\ | Yes | No | Device types supported by the module. | +| deviceTypes | Array\ | Yes | No | Types of devices where the module can run. | | installationFree | boolean | Yes | No | Whether installation-free is supported. | | hashValue | string | Yes | No | Hash value of the module. | -| moduleSourceDir | string | Yes | No | Module path.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md index c1919df283304c5a7e64c12b919b3e8c337e11e4..95326049595c17027a48552e04fab2d5a57816bb 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md @@ -1,7 +1,11 @@ # LauncherAbilityInfo + +The **LauncherAbilityInfo** module defines the ability information of the home screen application. The information can be obtained through [bundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfo9). + > **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. + ## LauncherAbilityInfo **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher @@ -12,7 +16,7 @@ | --------------- | ----------------------------------------------------------- | ---- | ---- | ------------------------------------ | | applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information of the launcher ability.| | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | No | Element name of the launcher ability. | -| labelId | number | Yes | No | Label ID of the launcher ability. | -| iconId | number | Yes | No | Icon ID of the launcher ability. | -| userId | number | Yes | No | User ID of the launcher ability. | +| labelId | number | Yes | No | ID of the launcher ability label. | +| iconId | number | Yes | No | ID of the launcher ability icon. | +| userId | number | Yes | No | ID of the launcher ability user. | | installTime | number | Yes | No | Time when the launcher ability was installed. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md b/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md index 203c5328b680e6c534e16b1a39d0943c3e31ab28..1f1c28b64a5263d5e7ff6e92f1c2711d948a7d46 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-metadata.md @@ -1,13 +1,16 @@ # Metadata -The **metadata** module provides the configuration about the module, ability, and Extension ability. The value is of the array type. The configuration is valid only for the current module, ability, or Extension ability. +The **Metadata** module provides a metadata object, which can be obtained through [bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo). This object is contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md), [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md), [AbilityInfo](js-apis-bundleManager-abilityInfo.md), and [ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.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 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 **Metadata** module provides the configuration about the module, UIAbility, and ExtensionAbility. The value is of the array type. The configuration is valid only for the current module, UIAbility, or ExtensionAbility. + ## Metadata -**System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Readable| Writable| Description | | -------- | ------ | ---- | ---- | ---------- | | name | string | Yes | Yes | Metadata name.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md index 4a0e43c1932a029ed7367d5b597528260a146bb0..a9e4c359659c55169acdbf0e3bc8f583b67febe9 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-packInfo.md @@ -2,7 +2,6 @@ The **PackInfo** module provides information in the **pack.info** file. The information can be obtained using [freeInstall.getBundlePackInfo](js-apis-freeInstall.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. @@ -49,10 +48,10 @@ The **PackInfo** module provides information in the **pack.info** file. The info **System capability**: SystemCapability.BundleManager.BundleFrameWork.FreeInstall -| Name | Type | Readable| Writable| Description | -| ---------- | ------------------- | ---- | ---- | ---------------------------------- | -| bundleName | string | Yes | No | Bundle name. It uniquely identifies the application.| -| version | [Version](#version) | Yes | No | Bundle version. | +| Name | Type | Readable| Writable| Description | +| ---------- | ------------------- | ---- | ---- | -------------------------------------- | +| bundleName | string | Yes | No | Bundle name. It uniquely identifies an application.| +| version | [Version](#version) | Yes | No | Bundle version. | ## ModuleConfigInfo @@ -67,7 +66,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info | deviceType | Array\ | Yes | No | Device types supported by the module. | | distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. | | abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. | -| extensionAbilities | Array\<[ExtensionAbilities](#extensionability)> | Yes | No | Extension ability information of the module.| +| extensionAbilities | Array\<[ExtensionAbilities](#extensionability)> | Yes | No | ExtensionAbility information of the module.| ## ModuleDistroInfo @@ -103,7 +102,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info | Name | Type | Readable| Writable| Description | | ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes| No| Name of the Extension ability.| +| name | string | Yes| No| Name of the ExtensionAbility.| | forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information.| ## AbilityFormInfo @@ -132,7 +131,7 @@ The **PackInfo** module provides information in the **pack.info** file. The info | ----------- | ------ | ---- | ---- | -------------------- | | releaseType | string | Yes | No | Name of the API version. | | compatible | number | Yes | No | Minimum API version.| -| target | number | Yes | No | Target API version. | +| target | number | Yes | No | Target API version. | ## Version diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md b/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md index aa3d41a76fd67da1a9a59d405d054e01db889754..b94f1e738890d0b30f74ab0ccde7ef43232a607e 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md @@ -1,6 +1,6 @@ # PermissionDef -The **PermissionDef** module provides permission details defined in the configuration file. The information can be obtained using [bundleManager.getPermissionDef](js-apis-bundleManager.md). +The **PermissionDef** module provides permission details defined in the configuration file. The information can be obtained using [bundleManager.getPermissionDef](js-apis-bundleManager.md). > **NOTE** > @@ -16,5 +16,5 @@ The **PermissionDef** module provides permission details defined in the configur | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | | grantMode | number | Yes | No | Grant mode of the permission.| -| labelId | number | Yes | No | Label ID of the permission. | -| descriptionId | number | Yes | No | Description ID of the permission. | +| labelId | number | Yes | No | ID of the permission label. | +| descriptionId | number | Yes | No | ID of the permission description. | diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 2c06d138b5bfda6383fabc14e28d3fb008af0bf0..875c2ac9ce239430d86cf43d02071b327604184f 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -17,7 +17,7 @@ The **ShortcutInfo** module defines shortcut information configured in the confi | Name | Type | Readable| Writable| Description | | ------------------------- | ------ | ---- | ---- | -------------------- | | targetBundle | string | Yes | No | Target bundle name of the shortcut.| -| targetModule | string | Yes | No | Target module name of the shortcut. | +| targetModule | string | Yes | No | Target module name of the shortcut. | | targetAbility | string | Yes | No | Target ability name of the shortcut.| ## ShortcutInfo @@ -28,14 +28,14 @@ The **ShortcutInfo** module defines shortcut information configured in the confi | Name | Type | Readable| Writable| Description | | ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | -| id | string | Yes | No | ID of the application to which the shortcut belongs. | -| bundleName | string | Yes | No | Name of the bundle that contains the shortcut. | -| moduleName | string | Yes | No | Module name of the shortcut. | -| hostAbility | string | Yes | No | Local ability name of the shortcut. | -| icon | string | Yes | No | Icon of the shortcut. | -| iconId | number | Yes | No | Icon ID of the shortcut. | -| label | string | Yes | No | Label of the shortcut. | -| labelId | number | Yes | No | Label ID of the shortcut. | -| wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | - - \ No newline at end of file +| id | string | Yes | No | ID of the application to which the shortcut belongs. | +| bundleName | string | Yes | No | Name of the bundle that contains the shortcut.| +| moduleName | string | Yes | No | Module name of the shortcut. | +| hostAbility | string | Yes | No | Local ability name of the shortcut. | +| icon | string | Yes | No | Icon of the shortcut. | +| iconId | number | Yes | No | ID of the shortcut icon. | +| label | string | Yes | No | Label of the shortcut. | +| labelId | number | Yes | No | ID of the shortcut label. | +| wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | + + diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index 525f882052397b5d59e5d4a22c79dc013c847e6a..38e42db4dc336dece5467e60c3a390d579fcac98 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -1,18 +1,20 @@ -# @ohos.bundle.bundleManager +# @ohos.bundle.bundleManager (bundleManager) The **bundleManager** module provides APIs for querying information about bundles, applications, abilities, Extension abilities, and more. > **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 bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; ``` + ## Required Permissions -| Required Permissions | Permission Level | Description | +| Permission | Permission Level | Description | | ------------------------------------------ | ------------ | ------------------| | ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles.| @@ -184,7 +186,7 @@ Enumerates the display orientations of the ability. This attribute applies only | AUTO_ROTATION_PORTRAIT_RESTRICTED |11|Switched-determined auto rotation in the vertical direction.| | LOCKED |12|Locked.| -## Methods +## APIs ### bundleManager.getBundleInfoForSelf @@ -209,16 +211,17 @@ Obtains the bundle information of this bundle based on the given bundle flags. T **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { - console.info('getBundleInfoForSelf successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfoForSelf failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfoForSelf failed:' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } ``` @@ -240,19 +243,20 @@ Obtains the bundle information of this bundle based on the given bundle flags. T **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfoForSelf(bundleFlags, (err, data) => { if (err) { - console.error('getBundleInfoForSelf failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } else { - console.info('getBundleInfoForSelf successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfoForSelf failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } ``` @@ -262,6 +266,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, userId: number, callback: Obtains the bundle information based on the given bundle name, bundle flags, and user ID. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -272,7 +278,7 @@ Obtains the bundle information based on the given bundle name, bundle flags, and | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| | userId | number | Yes | User ID. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the bundle information obtained. Otherwise, **err** is an error object.| @@ -291,7 +297,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the ability information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_ABILITY; let userId = 100; @@ -299,19 +306,20 @@ let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` ```ts // Obtain the bundle information with the metadata in the application information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA; let userId = 100; @@ -319,13 +327,13 @@ let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` @@ -335,6 +343,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\< Obtains the bundle information based on the given bundle name and bundle flags. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -345,7 +355,7 @@ Obtains the bundle information based on the given bundle name and bundle flags. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| | callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the bundle information obtained. Otherwise, **err** is an error object.| @@ -363,20 +373,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the Extension ability information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY; try { bundleManager.getBundleInfo(bundleName, bundleFlags, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` @@ -386,6 +397,8 @@ getBundleInfo(bundleName: string, bundleFlags: [number](#bundleflag), userId?: n Obtains the bundle information based on the given bundle name, bundle flags, and user ID. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -420,35 +433,37 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the application and signature information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO; let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId).then((data) => { - console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfo(bundleName, bundleFlags).then((data) => { - console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); } ``` @@ -459,6 +474,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use Obtains the application information based on the given bundle name, application flags, and user ID. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -487,7 +504,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; @@ -495,13 +513,13 @@ let userId = 100; try { bundleManager.getApplicationInfo(bundleName, appFlags, userId, (err, data) => { if (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } else { - console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } ``` @@ -511,6 +529,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), cal Obtains the application information based on the given bundle name and application flags. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -538,20 +558,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; try { bundleManager.getApplicationInfo(bundleName, appFlags, (err, data) => { if (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } else { - console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } ``` @@ -561,6 +582,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use Obtains the application information based on the given bundle name, application flags, and user ID. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -594,19 +617,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; let userId = 100; try { bundleManager.getApplicationInfo(bundleName, appFlags, userId).then((data) => { - console.info('getApplicationInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getApplicationInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getApplicationInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed. Cause: %{public}s', err.message); } ``` @@ -614,7 +638,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), userId: number, callback: AsyncCallback>): void; -Obtains an array of bundle information based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. +Obtains the information about all bundles based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -641,20 +665,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; let userId = 100; try { bundleManager.getAllBundleInfo(bundleFlags, userId, (err, data) => { if (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } else { - console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } ``` @@ -662,7 +687,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), callback: AsyncCallback>): void; -Obtains an array of bundle information based on the given bundle flags. This API uses an asynchronous callback to return the result. +Obtains the information about all bundles based on the given bundle flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -688,19 +713,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getAllBundleInfo(bundleFlags, (err, data) => { if (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } else { - console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } ``` @@ -708,7 +734,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), userId?: number): Promise>; -Obtains an array of bundle information based on the given bundle flags and user ID. This API uses a promise to return the result. +Obtains the information about all bundles based on the given bundle flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -740,17 +766,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getAllBundleInfo(bundleFlags).then((data) => { - console.info('getAllBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAllBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAllBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed. Cause: %{public}s', err.message); } ``` @@ -758,7 +785,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), userId: number, callback: AsyncCallback>): void; -Obtains an array of application information based on the given application flags and user ID. This API uses an asynchronous callback to return the result. +Obtains the information about all applications based on the given application flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -785,20 +812,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; try { bundleManager.getAllApplicationInfo(appFlags, userId, (err, data) => { if (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } else { - console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } ``` @@ -806,7 +834,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), callback: AsyncCallback>): void; -Obtains an array of application information based on the given application flags. This API uses an asynchronous callback to return the result. +Obtains the information about all applications based on the given application flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -832,19 +860,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { bundleManager.getAllApplicationInfo(appFlags, (err, data) => { if (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } else { - console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } ``` @@ -852,7 +881,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), userId?: number): Promise>; -Obtains an array of application information based on the given application flags and user ID. This API uses a promise to return the result. +Obtains the information about all applications based on the given application flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -884,17 +913,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { bundleManager.getAllApplicationInfo(appFlags).then((data) => { - console.info('getAllApplicationInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAllApplicationInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAllApplicationInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed. Cause: %{public}s', err.message); } ``` @@ -915,7 +945,7 @@ Obtains an array of ability information based on the given want, ability flags, | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ------------------------------------------------------- | -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain. | | userId | number | Yes | User ID. | | callback | AsyncCallback> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of ability information obtained. Otherwise, **err** is an error object.| @@ -935,24 +965,25 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId, (err, data) => { if (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } ``` @@ -972,7 +1003,7 @@ Obtains an array of ability information based on the given want and ability flag | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | -------------------------------------------------------| -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain. | | callback | AsyncCallback> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of ability information obtained. Otherwise, **err** is an error object.| @@ -991,23 +1022,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, (err, data) => { if (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } ``` @@ -1027,7 +1059,7 @@ Obtains the ability information based on the given want, ability flags, and user | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ------------------------------------------------------- | -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain.| | userId | number | No | User ID. | @@ -1052,41 +1084,43 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((data) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags).then((data) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }) -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1106,10 +1140,10 @@ Obtains the Extension ability information based on the given want, Extension abi | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want containing the bundle name to query. | -| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | -| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | -| userId | number | Yes | User ID. | +| want | Want | Yes | Want containing the bundle name to query. | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | +| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | +| userId | number | Yes | User ID. | | callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of Extension ability information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -1126,25 +1160,26 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId, (err, data) => { if (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } ``` @@ -1164,9 +1199,9 @@ Obtains the Extension ability information based on the given want, Extension abi | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want containing the bundle name to query. | -| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | -| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | +| want | Want | Yes | Want containing the bundle name to query. | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | +| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | | callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of Extension ability information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -1183,24 +1218,25 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, (err, data) => { if (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } ``` @@ -1218,8 +1254,8 @@ Obtains the Extension ability information based on the given want, Extension abi **Parameters** -| Name | Type | Mandatory| Description | -| --------------------- | --------------------------------------------- | ---- | ------------------------------------------------------- | +| Name | Type | Mandatory| Description | +| --------------------- | --------------------------------------------- | ---- | --------------------------------------------------------- | | want | Want | Yes | Want containing the bundle name to query. | | extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | | extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain.| @@ -1245,44 +1281,46 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId).then((data) => { - console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags).then((data) => { - console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); }) -} catch (error) { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1316,18 +1354,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let uid = 20010005; try { bundleManager.getBundleNameByUid(uid, (err, data) => { if (err) { - console.error('getBundleNameByUid failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed: %{public}s', err.message); } else { - console.info('getBundleNameByUid successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleNameByUid successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleNameByUid failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed: %{public}s', err.message); } ``` @@ -1366,16 +1405,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let uid = 20010005; try { bundleManager.getBundleNameByUid(uid).then((data) => { - console.info('getBundleNameByUid successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleNameByUid failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleNameByUid successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleNameByUid failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed. Cause: %{public}s', err.message); } ``` @@ -1410,20 +1450,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let hapFilePath = "/data/xxx/test.hap"; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { if (err) { - console.error('getBundleArchiveInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } else { - console.info('getBundleArchiveInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleArchiveInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } ``` @@ -1463,18 +1504,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let hapFilePath = "/data/xxx/test.hap"; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags).then((data) => { - console.info('getBundleArchiveInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleArchiveInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleArchiveInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } ``` @@ -1482,7 +1524,7 @@ try { cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void; -Clears cache files of a bundle. This API uses an asynchronous callback to return the result. +Clears the cache files based on the given bundle name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1509,19 +1551,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { bundleManager.cleanBundleCacheFiles(bundleName, err => { if (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } else { - console.info('cleanBundleCacheFiles successfully.'); + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); } }); } catch (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } ``` @@ -1529,7 +1572,7 @@ try { cleanBundleCacheFiles(bundleName: string): Promise\; -Clears cache files of a bundle. This API uses a promise to return the result. +Clears the cache files based on the given bundle name. This API uses a promise to return the result. **System API**: This is a system API. @@ -1547,7 +1590,7 @@ Clears cache files of a bundle. This API uses a promise to return the result. | Type | Description | | -------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| +| Promise\ | Promise that returns no value. If clearing the cache files fails, an error object is thrown.| **Error codes** @@ -1561,17 +1604,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { - bundleManager.cleanBundleCacheFiles(bundleName).then(()=> { - console.info('cleanBundleCacheFiles successfully.'); - }).catch(err=> { - console.error('cleanBundleCacheFiles failed:' + err.message); + bundleManager.cleanBundleCacheFiles(bundleName).then(() => { + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); }); } catch (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } ``` @@ -1606,19 +1650,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { bundleManager.setApplicationEnabled(bundleName, false, err => { if (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } else { - console.info('setApplicationEnabled successfully.'); + hilog.info(0x0000, 'testTag', 'setApplicationEnabled successfully.'); } }); } catch (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1658,17 +1703,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { - bundleManager.setApplicationEnabled(bundleName, false).then(()=> { - console.info('setApplicationEnabled successfully.'); - }).catch(err=> { - console.error('setApplicationEnabled failed:' + err.message); + bundleManager.setApplicationEnabled(bundleName, false).then(() => { + hilog.info(0x0000, "testTag", "setApplicationEnabled successfully."); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); }); } catch (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1689,7 +1735,7 @@ Enables or disables an ability. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means to disable the application.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Error codes** @@ -1704,32 +1750,33 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.setAbilityEnabled(info, false, err => { if (err) { - console.error('setAbilityEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setAbilityEnabled failed: %{public}s', err.message); } else { - console.info('setAbilityEnabled successfully.'); + hilog.info(0x0001, "testTag", "setAbilityEnabled successfully."); } }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1750,7 +1797,7 @@ Enables or disables an ability. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| isEnabled| boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means to disable the application.| +| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| **Return value** @@ -1770,30 +1817,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; - bundleManager.setAbilityEnabled(info, false).then(()=> { - console.info('setAbilityEnabled successfully.'); - }).catch(err=> { - console.error('setAbilityEnabled failed:' + err.message); + bundleManager.setAbilityEnabled(info, false).then(() => { + hilog.info(0x0000, "testTag", "setAbilityEnabled successfully."); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'setAbilityEnabled failed: %{public}s', err.message); }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1825,19 +1873,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.isApplicationEnabled(bundleName, (err, data) => { if (err) { - console.error('isApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed: %{public}s', err.message); } else { - console.info('isApplicationEnabled successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isApplicationEnabled successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('isApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1874,17 +1923,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.isApplicationEnabled(bundleName).then((data) => { - console.info('isApplicationEnabled successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('isApplicationEnabled failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'isApplicationEnabled successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('isApplicationEnabled failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed. Cause: %{public}s', err.message); } ``` @@ -1917,32 +1967,33 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.isAbilityEnabled(info, (err, data) => { if (err) { - console.error('isAbilityEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isAbilityEnabled failed: %{public}s', err.message); } else { - console.info('isAbilityEnabled successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isAbilityEnabled successfully: %{public}s', JSON.stringify(data)); } }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1980,30 +2031,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.isAbilityEnabled(info).then((data) => { - console.info('isAbilityEnabled successfully. Data: ' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isAbilityEnabled successfully. Data: %{public}s', JSON.stringify(data)); }).catch(err => { - console.error('isAbilityEnabled failed. Cause: ' + err.message); + hilog.error(0x0000, 'testTag', 'isAbilityEnabled failed. Cause: %{public}s', err.message); }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -2011,7 +2063,7 @@ try { getLaunchWantForBundle(bundleName: string, userId: number, callback: AsyncCallback\): void; -Obtains the want used to launch the bundle based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. +Obtains the Want used to launch the bundle based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2040,20 +2092,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let userId = 100; try { bundleManager.getLaunchWantForBundle(bundleName, userId, (err, data) => { if (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } else { - console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } ``` @@ -2061,7 +2114,7 @@ try { getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; -Obtains the want used to launch the bundle based on the given bundle name. This API uses an asynchronous callback to return the result. +Obtains the Want used to launch the bundle based on the given bundle name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2089,19 +2142,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.getLaunchWantForBundle(bundleName, (err, data) => { if (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } else { - console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } ``` @@ -2109,7 +2163,7 @@ try { getLaunchWantForBundle(bundleName: string, userId?: number): Promise\; -Obtains the want used to launch the bundle based on the given bundle name and user ID. This API uses a promise to return the result. +Obtains the Want used to launch the bundle based on the given bundle name and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -2143,18 +2197,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let userId = 100; try { bundleManager.getLaunchWantForBundle(bundleName, userId).then((data) => { - console.info('getLaunchWantForBundle successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getLaunchWantForBundle failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getLaunchWantForBundle failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed. Cause: %{public}s', err.message); } ``` @@ -2190,21 +2245,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByAbility(moduleName, abilityName, metadataName, (err, data) => { if (err) { - console.error('getProfileByAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } else { - console.info('getProfileByAbility successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getProfileByAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` @@ -2245,34 +2301,36 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getProfileByAbility(moduleName, abilityName).then((data) => { - console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByAbility(moduleName, abilityName, metadataName).then((data) => { - console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` @@ -2307,7 +2365,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; let extensionAbilityName = 'com.example.myapplication.extension'; let metadataName = 'com.example.myapplication.metadata'; @@ -2315,13 +2374,13 @@ let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName, (err, data) => { if (err) { - console.error('getProfileByExtensionAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed: %{public}s', err.message); } else { - console.info('getProfileByExtensionAbility successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getProfileByExtensionAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed: %{public}s', err.message); } ``` @@ -2361,29 +2420,30 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; let extensionAbilityName = 'com.example.myapplication.extension'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName).then((data) => { - console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); } try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName).then((data) => { - console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); } ``` @@ -2391,7 +2451,7 @@ try { getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void; -Obtains the details of a permission. This API uses an asynchronous callback to return the result. +Obtains the details of a permission in the form of a **PermissionDef** struct. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2417,18 +2477,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let permission = "ohos.permission.GET_BUNDLE_INFO"; try { bundleManager.getPermissionDef(permission, (err, data) => { if (err) { - console.error('getPermissionDef failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getPermissionDef failed: %{public}s', err.message); } else { - console.info('getPermissionDef successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getPermissionDef successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getPermissionDef failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getPermissionDef failed: %{public}s', err.message); } ``` @@ -2436,7 +2497,7 @@ try { getPermissionDef(permissionName: string): Promise\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>; -Obtains the details of a permission. This API uses a promise to return the result. +Obtains the details of a permission in the form of a **PermissionDef** struct. This API uses a promise to return the result. **System API**: This is a system API. @@ -2467,16 +2528,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let permissionName = "ohos.permission.GET_BUNDLE_INFO"; try { bundleManager.getPermissionDef(permissionName).then((data) => { - console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getPermissionDef failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getPermissionDef successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getPermissionDef failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getPermissionDef failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getPermissionDef failed. Cause: %{public}s', err.message); } ``` @@ -2516,21 +2578,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityLabel(bundleName, moduleName, abilityName, (err, data) => { if (err) { - console.error('getAbilityLabel failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed: %{public}s', err.message); } else { - console.info('getAbilityLabel successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAbilityLabel successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAbilityLabel failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed: %{public}s', err.message); } ``` @@ -2575,19 +2638,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityLabel(bundleName, moduleName, abilityName).then((data) => { - console.info('getAbilityLabel successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAbilityLabel failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAbilityLabel successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAbilityLabel failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed. Cause: %{public}s', err.message); } ``` @@ -2627,21 +2691,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityIcon(bundleName, moduleName, abilityName, (err, data) => { if (err) { - console.error('getAbilityIcon failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); } else { - console.info('getAbilityIcon successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAbilityIcon failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); } ``` @@ -2686,19 +2751,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityIcon(bundleName, moduleName, abilityName).then((data) => { - console.info('getAbilityIcon successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAbilityIcon failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAbilityIcon failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); } ``` @@ -2720,7 +2786,7 @@ Synchronously obtains the application information based on the given bundle name | ----------- | ------ | ---- | ----------------------------------------------------------| | bundleName | string | Yes | Bundle name. | | applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. | -| userId | number | Yes | User ID. | +| userId | number | No | User ID. | **Return value** @@ -2741,65 +2807,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; try { let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags, userId); - console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getApplicationInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfoSync failed: %{public}s', err.message); } ``` -### 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 bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags); - console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getApplicationInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfoSync failed: %{public}s', err.message); } ``` @@ -2821,7 +2853,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 | Yes | User ID. | +| userId | number | No | User ID. | **Return value** @@ -2842,66 +2874,29 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; let userId = 100; try { let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags, userId); - console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getBundleInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` -### 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. | -| 17700004 | The specified user ID is not found. | -| 17700026 | The specified bundle is disabled. | - -**Example** - ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; try { let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags); - console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getBundleInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index cf2d7aab46c5d8ea80d49fe66b61ae68e56885a0..11f54832d6556e24f35cd1baedee0d9abfe39079 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -1,4 +1,4 @@ -# @ohos.bundle.bundleMonitor +# @ohos.bundle.bundleMonitor (bundleMonitor) The **Bundle.bundleMonitor** module provides APIs for listens for bundle installation, uninstall, and updates. @@ -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. @@ -47,8 +47,8 @@ Subscribes to bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ------------------ | -| BundleChangedEvent | string | Yes | Type of the event to subscribe to.| -| Callback\ | callback | Yes | Callback used for the subscription.| +| type| BundleChangedEvent| Yes | Type of the event to subscribe to.| +| callback | callback\| Yes | Callback used for the subscription.| **Example** @@ -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. @@ -80,8 +80,8 @@ Unsubscribes from bundle installation, uninstall, and update events. | Name | Type | Mandatory| Description | | ---------------------------- | -------- | ---- | ---------------------------------------------------------- | -| BundleChangedEvent | string | Yes | Type of the event to unsubscribe from. | -| Callback\ | callback | Yes | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| +| type| BundleChangedEvent| Yes | Type of the event to unsubscribe from. | +| callback | callback\| No | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 544a4ba0d27e6c39794e063fc63282ba5455bf5e..89e14f7ad3e4fb3f525ccd9d5aab83b56e8c6521 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -1,4 +1,4 @@ -# Performance Tracing +# @ohos.bytrace (Performance Tracing) > **NOTE** > - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 82741c1432d9d4fd9c5babef17548bb643cf2dd9..0ccd49a5dc2a8b8e3577b7614f8219573de7cf7d 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -1,6 +1,6 @@ -# Call +# @ohos.telephony.call (Call) -The call module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. +The **call** module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange). @@ -1704,7 +1704,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------ | ---- | -------------------------- | | type | string | Yes | Cause of the call disconnection.| -| callback | Callback<[DisconnectedDetails](#disconnecteddetails8)> | Yes | Callback used to return the result. | +| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | Yes | Callback used to return the result. | **Example** @@ -1812,7 +1812,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------------- | ---- | -------------------- | | type | 'callDisconnectedCause' | Yes | Unsubscription from the call disconnection cause when a call ends.| -| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails8)> | No | Callback used to return the result. | +| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. | **Example** @@ -2908,11 +2908,15 @@ This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------- | ---- | ---------------- | -| transferNum | string | Yes | Call transfer number. | -| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | -| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| +| Name | Type | Mandatory| Description | +| ------------------------ | ---------------------------------------------------- | ---- | ---------------- | +| transferNum | string | Yes | Call transfer number. | +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | +| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| +| startHour9+ | number | No | Hour in the start time.| +| startMinute9+ | number | No | Minute in the start time.| +| endHour9+ | number | No | Hour in the end time.| +| endMinute9+ | number | No | Minute in the end time.| ## CallTransferType8+ @@ -3128,10 +3132,14 @@ This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------- | ---- | -------- | -| status | [TransferStatus](#transferstatus8) | Yes | Transfer status.| -| number | string | Yes | Number. | +| Name | Type | Mandatory| Description | +| ------------------------ | ---------------------------------- | ---- | ---------------- | +| status | [TransferStatus](#transferstatus8) | Yes | Call transfer status. | +| number | string | Yes | Call transfer number. | +| startHour9+ | number | Yes | Hour in the start time.| +| startMinute9+ | number | Yes | Minute in the start time.| +| endHour9+ | number | Yes | Hour in the end time.| +| endMinute9+ | number | Yes | Minute in the end time.| ## CallWaitingStatus7+ @@ -3172,7 +3180,20 @@ This is a system API. | TRANSFER_DISABLE | 0 | Call transfer disabled.| | TRANSFER_ENABLE | 1 | Call transfer enabled.| -## DisconnectedDetails8+ +## DisconnectedDetails9+ + +Defines the cause of a call disconnection. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | --------------- | +| reason | [DisconnectedReason](#disconnectedreason8) | Yes | Cause of the call disconnection. | +| message | string | Yes | Message indicating the call disconnection.| + +## DisconnectedReason8+ Enumerates causes of call disconnection. @@ -3180,28 +3201,87 @@ This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Value | Description | -| --------------------------- | ---- | ---------------------- | -| UNASSIGNED_NUMBER | 1 | Unallocated number. | -| NO_ROUTE_TO_DESTINATION | 3 | No route to the destination. | -| CHANNEL_UNACCEPTABLE | 6 | Unacceptable channel. | -| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). | -| NORMAL_CALL_CLEARING | 16 | Normal call clearing. | -| USER_BUSY | 17 | User busy. | -| NO_USER_RESPONDING | 18 | No user response. | -| USER_ALERTING_NO_ANSWER | 19 | Alerting but no answer.| -| CALL_REJECTED | 21 | Call rejected. | -| NUMBER_CHANGED | 22 | Number changed. | -| DESTINATION_OUT_OF_ORDER | 27 | Destination fault. | -| INVALID_NUMBER_FORMAT | 28 | Invalid number format. | -| NETWORK_OUT_OF_ORDER | 38 | Network fault. | -| TEMPORARY_FAILURE | 41 | Temporary fault. | -| INVALID_PARAMETER | 1025 | Invalid parameter. | -| SIM_NOT_EXIT | 1026 | SIM card not exit. | -| SIM_PIN_NEED | 1027 | SIM card PIN required. | -| CALL_NOT_ALLOW | 1029 | Call not allowed. | -| SIM_INVALID | 1045 | Invalid SIM card. | -| UNKNOWN | 1279 | Unknown reason. | +| Name | Value | Description | +| ------------------------------------------------------------ | ---- | --------------------------------------- | +| UNASSIGNED_NUMBER | 1 | Unallocated (unassigned) number. | +| NO_ROUTE_TO_DESTINATION | 3 | No route to destination. | +| CHANNEL_UNACCEPTABLE | 6 | Channel unacceptable. | +| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). | +| CALL_COMPLETED_ELSEWHERE9+ | 13 | Call completed elsewhere. | +| NORMAL_CALL_CLEARING | 16 | Normal call clearing. | +| USER_BUSY | 17 | User busy. | +| NO_USER_RESPONDING | 18 | No user responding. | +| USER_ALERTING_NO_ANSWER | 19 | User alerting, no answer. | +| CALL_REJECTED | 21 | Call rejected. | +| NUMBER_CHANGED | 22 | Number changed. | +| CALL_REJECTED_DUE_TO_FEATURE_AT_THE_DESTINATION9+ | 24 | Call rejected due to feature at the destination.| +| FAILED_PRE_EMPTION9+ | 25 | Failed preemption. | +| NON_SELECTED_USER_CLEARING9+ | 26 | Non-selected user clearing. | +| DESTINATION_OUT_OF_ORDER | 27 | Destination out of order. | +| INVALID_NUMBER_FORMAT | 28 | Invalid number format (incomplete number). | +| FACILITY_REJECTED9+ | 29 | Facility rejected. | +| RESPONSE_TO_STATUS_ENQUIRY9+ | 30 | Response to status enquiry. | +| NORMAL_UNSPECIFIED9+ | 31 | Normal, unspecified. | +| NO_CIRCUIT_CHANNEL_AVAILABLE9+ | 34 | No circuit/channel available. | +| NETWORK_OUT_OF_ORDER | 38 | Network fault. | +| TEMPORARY_FAILURE | 41 | Temporary failure. | +| SWITCHING_EQUIPMENT_CONGESTION9+ | 42 | Switching equipment congestion. | +| ACCESS_INFORMATION_DISCARDED9+ | 43 | Access information discarded. | +| REQUEST_CIRCUIT_CHANNEL_NOT_AVAILABLE9+ | 44 | Requested circuit/channel unavailable | +| RESOURCES_UNAVAILABLE_UNSPECIFIED9+ | 47 | Resources unavailable, unspecified. | +| QUALITY_OF_SERVICE_UNAVAILABLE9+ | 49 | QoS unavailable. | +| REQUESTED_FACILITY_NOT_SUBSCRIBED9+ | 50 | Requested facility not subscribed. | +| INCOMING_CALLS_BARRED_WITHIN_THE_CUG9+ | 55 | Incoming calls barred within the CUG. | +| BEARER_CAPABILITY_NOT_AUTHORIZED9+ | 57 | Bearer capability not authorized. | +| BEARER_CAPABILITY_NOT_PRESENTLY_AVAILABLE9+ | 58 | Bearer capability presently available. | +| SERVICE_OR_OPTION_NOT_AVAILABLE_UNSPECIFIED9+ | 63 | Service or option not available, unspecified. | +| BEARER_SERVICE_NOT_IMPLEMENTED9+ | 65 | Bearer service not implemented. | +| ACM_EQUALTO_OR_GREATER_THAN_THE_MAXIMUM_VALUE9+ | 68 | ACM greater than or equal to the maximum value. | +| REQUESTED_FACILITY_NOT_IMPLEMENTED9+ | 69 | Requested facility not implemented. | +| ONLY_RESTRICTED_DIGITAL_INFO_BEARER_CAPABILITY_IS_AVAILABLE9+ | 70 | Only restricted digital information capability available. | +| SERVICE_OR_OPTION_NOT_IMPLEMENTED_UNSPECIFIED9+ | 79 | Service or option not implemented, unspecified. | +| INVALID_TRANSACTION_IDENTIFIER_VALUE9+ | 81 | Invalid transaction identifier value. | +| USER_NOT_MEMBER_OF_CUG9+ | 87 | User not member of CUG. | +| INCOMPATIBLE_DESTINATION9+ | 88 | Incompatible destination. | +| INVALID_TRANSIT_NETWORK_SELECTION9+ | 91 | Invalid transit network selection. | +| SEMANTICALLY_INCORRECT_MESSAGE9+ | 95 | Semantically incorrect message. | +| INVALID_MANDATORY_INFORMATION9+ | 96 | Invalid mandatory information. | +| MESSAGE_TYPE_NON_EXISTENT_OR_NOT_IMPLEMENTED9+ | 97 | Message type non-existent or not implemented. | +| MESSAGE_TYPE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE9+ | 98 | Message type not compatible with protocol state. | +| INFORMATION_ELEMENT_NON_EXISTENT_OR_NOT_IMPLEMENTED9+ | 99 | IE non-existent or not implemented. | +| CONDITIONAL_IE_ERROR9+ | 100 | Conditional IE error. | +| MESSAGE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE9+ | 101 | Message not compatible with protocol state. | +| RECOVERY_ON_TIMER_EXPIRED9+ | 102 | Recovery on timer expiry. | +| PROTOCOL_ERROR_UNSPECIFIED9+ | 111 | Protocol error, unspecified. | +| INTERWORKING_UNSPECIFIED9+ | 127 | Interworking, unspecified. | +| CALL_BARRED9+ | 240 | Call barred. | +| FDN_BLOCKED9+ | 241 | FDN blocked. | +| IMSI_UNKNOWN_IN_VLR9+ | 242 | IMSI unknown in VLR. | +| IMEI_NOT_ACCEPTED9+ | 243 | IMEI not accepted. | +| DIAL_MODIFIED_TO_USSD9+ | 244 | Dial request modified to USSD request. | +| DIAL_MODIFIED_TO_SS9+ | 245 | Dial request modified to SS request. | +| DIAL_MODIFIED_TO_DIAL9+ | 246 | Dial request modified to dial with different number. | +| RADIO_OFF9+ | 247 | Radio off. | +| OUT_OF_SERVICE9+ | 248 | Out of service. | +| NO_VALID_SIM9+ | 249 | No valid SIM. | +| RADIO_INTERNAL_ERROR9+ | 250 | Radio internal error. | +| NETWORK_RESP_TIMEOUT9+ | 251 | Network response timeout. | +| NETWORK_REJECT9+ | 252 | Request rejected by network. | +| RADIO_ACCESS_FAILURE9+ | 253 | Radio access failure. | +| RADIO_LINK_FAILURE9+ | 254 | Radio link failure. | +| RADIO_LINK_LOST9+ | 255 | Radio link lost. | +| RADIO_UPLINK_FAILURE9+ | 256 | Radio uplink failure. | +| RADIO_SETUP_FAILURE9+ | 257 | Radio setup failure. | +| RADIO_RELEASE_NORMAL9+ | 258 | Radio release normal. | +| RADIO_RELEASE_ABNORMAL9+ | 259 | Radio release abnormal. | +| ACCESS_CLASS_BLOCKED9+ | 260 | Access class blocked. | +| NETWORK_DETACH9+ | 261 | Network detached. | +| INVALID_PARAMETER | 1025 | Invalid parameter. | +| SIM_NOT_EXIT | 1026 | SIM not exit. | +| SIM_PIN_NEED | 1027 | SIM PIN needed. | +| CALL_NOT_ALLOW | 1029 | Call not allowed. | +| SIM_INVALID | 1045 | No valid SIM. | +| UNKNOWN | 1279 | Unknown reason. | ## MmiCodeResults9+ diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index baf10a887589617bee09f1a3220c70dd1b6d6cdb..cb1311397a52d39e41466c33135bdc93164a0807 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -1,4 +1,4 @@ -# Camera Management +# @ohos.multimedia.camera (Camera Management) > **NOTE** > @@ -22,7 +22,7 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ---------------------------- | -| context | [Context](../../ability/context-userguide.md) | Yes | Application context. | +| context | [Context](js-apis-inner-app-context.md) | Yes | Application context. | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.| **Example** @@ -49,7 +49,7 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ------- | ---- | ------------ | -| context | [Context](../../ability/context-userguide.md) | Yes | Application context.| +| context | [Context](js-apis-inner-app-context.md) | Yes | Application context.| **Return value** @@ -757,7 +757,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | --------- | | type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.| -| callback | AsyncCallback | Yes | Callback used to return the camera mute status. | +| callback | AsyncCallback\ | Yes | Callback used to return the camera mute status. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md new file mode 100644 index 0000000000000000000000000000000000000000..dc506245c6feef1b2c22b70613ce3359404162dc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -0,0 +1,2109 @@ +# @ohos.security.cert (Certificate) + +The **certificate** module provides APIs for performing certificate operations. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. + +## Modules to Import + +```javascript +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" +``` + +## CertResult + + Enumerates the error codes. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| --------------------------------------| -------- | -----------------------------| +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | This operation is not supported. | +| ERR_OUT_OF_MEMORY | 19020001 | Memory error. | +| ERR_RUNTIME_ERROR | 19020002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 19030001 | Crypto operation error. | +| ERR_CERT_SIGNATURE_FAILURE | 19030002 | The certificate signature verification failed. | +| ERR_CERT_NOT_YET_VALID | 19030003 | The certificate has not taken effect. | +| ERR_CERT_HAS_EXPIRED | 19030004 | The certificate has expired. | +| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 19030005 | Failed to obtain the certificate issuer. | +| ERR_KEYUSAGE_NO_CERTSIGN | 19030006 | The key cannot be used for signing a certificate. | +| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 19030007 | The key cannot be used for digital signature. | + +## DataBlob +Defines a binary data array. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data. | + +## DataArray + +Defines a list of data arrays. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data list. | + +## EncodingFormat + + Enumerates the certificate encoding formats. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value| Description | +| ---------- | ------ | --------- | +| FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format.| +| FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format.| + + +## EncodingBlob + +Defines a certificate binary array in encoding format. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data.| +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## CertChainData + +Defines the certificate chain data, which is passed in as input parameters during certificate chain verification. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data, in the *length* (2 bytes) + *data* format. For example, **08ABCDEFGH07ABCDEFG**. The first two bytes indicate the length of the first certificate is eight bytes, and the following eight bytes indicate the certificate data. Then, the next two bytes indicate the length of another certificate is seven bytes, and the seven bytes followed indicate the certificate data.| +| count | number | Yes | Yes | Number of certificates contained in the input data. | +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Cert** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cer** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + } +}); +``` + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob) : Promise\ + +Creates an **X509Cert** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.| + +**Return value** + +| Type | Description | +| ------- | ---------------- | +| Promise\ | **X509Cer** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Cert + +Provides APIs for X.509 certificate operations. + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the certificate signature. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the certificate signature. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 certificate data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized X.509 certificate data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + x509Cert.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 certificate data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | ---------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + x509Cert.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getPublicKey + +getPublicKey() : cryptoFramework.PubKey + +Obtains the public key of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| cryptoFramework.PubKey | X.509 certificate public key obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let pubKey = null; + try { + pubKey = x509Cert.getPublicKey(); + } catch (error) { + console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### checkValidityWithDate + +checkValidityWithDate(date: string) : void + +Checks the validity period of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------- | +| date | string | Yes | Date of the certificate to check. | + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let date = "150527000001Z"; + + // Verify the certificate validity period. + try { + x509Cert.checkValidityWithDate(date); + } catch (error) { + console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getVersion + +getVersion() : number + +Obtains the X.509 certificate version. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| number | X.509 certificate version obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let version = x509Cert.getVersion(); + } +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the X.509 certificate serial number. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | X.509 certificate serial number obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let serialNumber = x509Cert.getSerialNumber(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the X.509 certificate issuer. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- | +| [DataBlob](#datablob) | X.509 certificate issuer obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerName = x509Cert.getIssuerName(); + } +}); +``` + +### getSubjectName + +getSubjectName() : DataBlob + +Obtains the subject of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Subject name obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectName = x509Cert.getSubjectName(); + } +}); +``` + +### getNotBeforeTime + +getNotBeforeTime() : string + +Obtains the start time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Start time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notBefore = x509Cert.getNotBeforeTime(); + } +}); +``` + +### getNotAfterTime + +getNotAfterTime() : string + +Obtains the expiration time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Expiration time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notAfter = x509Cert.getNotAfterTime(); + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Signature data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let signature = x509Cert.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | X.509 certificate signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgName = x509Cert.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| string | OID obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgOid = x509Cert.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the signing algorithm parameters of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------ | +| [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgParams = x509Cert.getSignatureAlgParams(); + } +}); +``` + +### getKeyUsage + +getKeyUsage() : DataBlob + +Obtains the key usage of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let keyUsage = x509Cert.getKeyUsage(); + } +}); +``` + +### getExtKeyUsage + +getExtKeyUsage() : DataArray + +Obtains the usage of the extended key of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | Usage of the extended key obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let extKeyUsage = x509Cert.getExtKeyUsage(); + } +}); +``` + +### getBasicConstraints + +getBasicConstraints() : number + +Obtains the basic constraints for obtaining this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | Basic constraints obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let basicConstraints = x509Cert.getBasicConstraints(); + } +}); +``` + +### getSubjectAltNames + +getSubjectAltNames() : DataArray + +Obtains the Subject Alternative Names (SANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | SANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectAltNames = x509Cert.getSubjectAltNames(); + } +}); +``` + +### getIssuerAltNames + +getIssuerAltNames() : DataArray + +Obtains the Issuer Alternative Names (IANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | -------------------------- | +| [DataArray](#dataarray) | IANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerAltNames = x509Cert.getIssuerAltNames(); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Crl** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob) : Promise\ + +Creates an **X509Crl** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized CRL data.| + +**Return value** + +| Type | Description | +| ----------------- | -------------------- | +| Promise\ | Promise used to return the **X509Crl** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Crl + +Provides APIs for X.509 certificate CRL operations. + +### isRevoked + +isRevoked(cert : X509Cert) : boolean + +Checks whether an X.509 certificate is revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| cert | X509Cert | Yes | X.509 certificate to check.| + +**Return value** + +| Type | Description | +| --------- | --------------------------------------------- | +| boolean | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let revokedFlag = x509Crl.isRevoked(x509Cert); + } catch (error) { + console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getType + +getType() : string + +Obtains the CRL type. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | CRL type obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let type = x509Crl.getType(); + } +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback invoked to return the serialized X.509 CRL data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 CRL data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------- | +| Promise\ | Promise used to return the serialized X.509 CRL data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the signature of the X.509 CRL. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type| Description | +| ---- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getVersion + +getVersion() : number + +Obtains the version of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| number | Version of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let version = x509Crl.getVersion(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the issuer of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let issuerName = x509Crl.getIssuerName(); + } +}); +``` + +### getLastUpdate + +getLastUpdate() : string + +Obtains the date when the X.509 CRL was last updated. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Last update date of the X.509 CRL.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let lastUpdate = x509Crl.getLastUpdate(); + } +}); +``` + +### getNextUpdate + +getNextUpdate() : string + +Obtains the date when the CRL will be updated the next time. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Next update date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let nextUpdate = x509Crl.getNextUpdate(); + } +}); +``` + +### getRevokedCert + +getRevokedCert(serialNumber : number) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | -------------- | +| serialNumber | number | Yes | Serial number of the certificate.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Set the serial number of the corresponding certificate. + let serialNumber = 1000; + try { + let entry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCertWithCert + +getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.| + +**Return value** + +| Type | Description | +| ------------ | -------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let entry = x509Crl.getRevokedCertWithCert(x509Cert); + } catch (error) { + console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCerts + +getRevokedCerts(callback : AsyncCallback>) : void + +Obtains all the revoked X.509 certificates. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts(function (error, array) { + if (error != null) { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getRevokedCerts success"); + } + }); + } +}); +``` + +### getRevokedCerts + +getRevokedCerts() : Promise> + +Obtains all the revoked X.509 certificates. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------------- | ---------------------- | +| Promise> | Promise used to return a list of revoked X.509 certificates.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts().then(array => { + console.log("getRevokedCerts success"); + }, error => { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getTbsInfo + +getTbsInfo() : DataBlob + +Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| [DataBlob](#datablob) | Promise used to return the **tbsCertList** information obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + try { + let tbsInfo = x509Crl.getTbsInfo(); + } catch (error) { + console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let signature = x509Crl.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| string | Signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgName = x509Crl.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------------------- | +| string | OID of the X.509 CRL signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgOid = x509Crl.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the parameters of the X.509 CRL signing algorithm. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------- | +| [DataBlob](#datablob) | Algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgParams = x509Crl.getSignatureAlgParams(); + } +}); +``` + +## cryptoCert.createCertChainValidator + +createCertChainValidator(algorithm :string) : CertChainValidator + +Creates a **CertChainValidator** object. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------ | +| algorithm | string | Yes | Certificate chain validator algorithm. Currently, only **PKIX** is supported.| + +**Return value** + +| Type | Description | +| ------------------ | -------------------- | +| CertChainValidator | **CertChainValidator** object created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +``` + +## CertChainValidator + +Provides APIs for certificate chain validator operations. + + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------- | +| algorithm | string | Yes | No | Algorithm used by the X509 certificate chain validator.| + + +### validate + +validate(certChain : CertChainData, callback : AsyncCallback\) : void + +Validates the X.509 certificate chain. This API uses an asynchronous callback to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData, function (error, data) { + if (error != null) { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("validate success"); + } +}); +``` + +### validate + +validate(certChain : CertChainData) : Promise\ + +Validates the X.509 certificate chain. This API uses a promise to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | -------------------------- | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData).then(result => { + console.log("validate success"); +}, error => { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### algorithm + +algorithm : string + +Obtains the algorithm of the X.509 certificate chain validator. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | Algorithm of the X.509 certificate chain validator obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +let algorithm = validator.algorithm; +``` + +## X509CrlEntry + +Provides APIs for operating the revoked certificates. + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized data of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized data of the revoked certificate obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized data of this revoked certificate. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded().then(result => { + console.log("getEncoded success"); +}, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the serial number of this revoked certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Serial number of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +let serialNumber = x509CrlEntry.getSerialNumber(); +``` + +### getCertIssuer + +getCertIssuer() : DataBlob + +Obtains the issuer of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- - | +| [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let issuer = x509CrlEntry.getCertIssuer(); +} catch (error) { + console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` + +### getRevocationDate + +getRevocationDate() : string + +Obtains the date when the certificate was revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Promise used to return the certificate revocation date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let date = x509CrlEntry.getRevocationDate(); +} catch (error) { + console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md index 044fab3c6456d47e9a342b78770f10dc8f58c87d..706838181628f3e95cf2a35660d78e2f9389d73c 100644 --- a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md +++ b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md @@ -1,4 +1,4 @@ -# Color Space Management +# @ohos.graphics.colorSpaceManager (Color Space Management) The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes. diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 12fc260b45b0364ae5a4fc1218f45f6f2ed9df44..35a696a15b0569a7370fd8ec7938e92e2d13fe0d 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,181 +1,30 @@ -# @ohos.commonEvent +# @ohos.commonEvent (Common Event) The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. > **NOTE** +> > - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.commonEventManager](js-apis-commonEventManager.md). +> > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```js +```ts import CommonEvent from '@ohos.commonEvent'; ``` ## Support -The table below lists the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Value | Subscriber Permission | Description | -| ------------ | ------------------ | ---------------------- | -------------------- | -| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | -| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | -| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | Indicates the common event that the device is being shut down and the final shutdown will proceed. | -| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | Indicates the common event that the charging state, level, and other information about the battery have changed. | -| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | Indicates the common event that the battery level is low. | -| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | Indicates the common event that the battery exits the low state. | -| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | Indicates the common event that the device is connected to an external power supply. | -| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | -| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | -| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | -| COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | -| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | -| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | -| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | -| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | Indicates the common event that the system time has changed. | -| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | Indicates the common event that the system time zone has changed. | -| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | -| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | -| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | -| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. -| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | -| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | -| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | -| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | Indicates the common event that an application package has been changed (for example, a component in the package has been enabled or disabled). | -| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | Indicates the common event that the user has restarted the application package and killed all its processes. | -| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | Indicates the common event that the user has cleared the application package data. | -| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | - | Indicates the common event that the user clears the application package cache. | -| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | Indicates the common event that application packages have been suspended. | -| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | Indicates the common event that application packages have not been suspended. | -| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | Indicates the common event that an application package has been suspended. | -| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | -| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | Indicates the common event that a user ID has been removed from the system. | -| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | Indicates the common event that an installed application is started for the first time. | -| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | Indicates the common event that an application requires system verification. | -| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | Indicates the common event that an application has been verified by the system. | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | Indicates the common event that applications installed on the external storage become available for the system. | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | Indicates the common event that applications installed on the external storage become unavailable for the system. | -| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | Indicates the common event that the device state (for example, orientation and locale) has changed. | -| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | Indicates the common event that the device locale has changed. | -| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | Indicates the common event that the device storage is insufficient. | -| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | Indicates the common event that the system is in driving mode. | -| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | Indicates the common event that the system is in home mode. | -| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | Indicates the common event that the system is in office mode. | -| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | -| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | -| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | -| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that user switching is happening. | -| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be started. | -| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | -| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be stopped. | -| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | -| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | -| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | -| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | -| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | -| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | -| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | -| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | -| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | -| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | -| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P state, such as enabled and disabled. | -| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of Wi-Fi P2P peer devices. | -| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P discovery status change. | -| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of the Wi-Fi P2P local device. | -| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi P2P group information has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth handsfree communication. | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected to the Bluetooth handsfree is active. | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth A2DP. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected using Bluetooth A2DP is active. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the AVRCP connection state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio codec state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | Indicates the common event that a remote Bluetooth device is discovered. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth class of a remote Bluetooth device has changed. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been established with a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been disconnected from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | Indicates the common event about the connection request from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | Indicates the common event about the response to the connection request from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | Indicates the common event that the connection to a remote Bluetooth device has been canceled. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | Indicates the common event that the connection state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | -| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | -| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the enabled state. | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | -| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | -| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | -| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | -| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | -| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been added to the system. | -| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been removed from the system. | -| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | -| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | -| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | -| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | -| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | -| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | -| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | Indicates the common event that a third-party application is instructed to pause the current work. | -| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | Indicates the common event that a third-party application is instructed to save its last mode. | -| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | Indicates the common event that the voltage of the vehicle's power system is abnormal. | -| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is high. | -| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is extremely high. | -| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | Indicates the common event that the IVI system has an extreme temperature. | -| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | Indicates the common event that the voltage of the vehicle's power system is restored to normal. | -| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | Indicates the common event that the temperature of the IVI system is restored to normal. | -| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | Indicates the common event that the battery service is active. | -|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates the common event that the USB device status has changed. | -|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the common event that the USB port status of the user device has changed. | -| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | -| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | -| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | -| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | -| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | -| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | -| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | -| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | -| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | -| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. | -| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | -| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | -| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | +A system common event is an event that is published by a system service or system application and requires specific permissions to subscribe to. To publish or subscribe to this type of event, you must follow the event-specific definitions. +For details about the definitions of all system common events, see [System Common Events](./commonEvent-definitions.md). ## CommonEvent.publish -publish(event: string, callback: AsyncCallback\): void +```ts +publish(event: string, callback: AsyncCallback): void +``` Publishes a common event. This API uses an asynchronous callback to return the result. @@ -190,9 +39,9 @@ Publishes a common event. This API uses an asynchronous callback to return the r **Example** -```js +```ts // Callback for common event publication -function publishCallBack(err) { +function publishCB(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -201,14 +50,14 @@ function publishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", publishCallBack); +CommonEvent.publish("event", publishCB); ``` - - ## CommonEvent.publish -publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void +```ts +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback): void +``` Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. @@ -225,16 +74,16 @@ Publishes a common event with given attributes. This API uses an asynchronous ca **Example** -```js +```ts // Attributes of a common event. let options = { - code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event. + code: 0, // Initial code of the common event. + data: "initial data";// Initial data of the common event. isOrdered: true // The common event is an ordered one. } // Callback for common event publication -function publishCallBack(err) { +function publishCB(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -243,14 +92,14 @@ function publishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", options, publishCallBack); +CommonEvent.publish("event", options, publishCB); ``` - - ## CommonEvent.publishAsUser8+ -publishAsUser(event: string, userId: number, callback: AsyncCallback\): void +```ts +publishAsUser(event: string, userId: number, callback: AsyncCallback): void +``` Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. @@ -268,9 +117,9 @@ Publishes a common event to a specific user. This API uses an asynchronous callb **Example** -```js +```ts // Callback for common event publication -function publishAsUserCallBack(err) { +function publishCB(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -282,14 +131,14 @@ function publishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, publishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, publishCB); ``` - - ## CommonEvent.publishAsUser8+ -publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void +```ts +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback): void +``` Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. @@ -309,15 +158,15 @@ Publishes a common event with given attributes to a specific user. This API uses **Example** -```js +```ts // Attributes of a common event. let options = { - code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event. + code: 0, // Initial code of the common event. + data: "initial data";// Initial data of the common event. } // Callback for common event publication -function publishAsUserCallBack(err) { +function publishCB(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -329,14 +178,14 @@ function publishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, options, publishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, options, publishCB); ``` - - ## CommonEvent.createSubscriber -createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void +```ts +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback): void +``` Creates a subscriber. This API uses an asynchronous callback to return the result. @@ -352,7 +201,7 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul **Example** -```js +```ts let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. @@ -361,7 +210,7 @@ let subscribeInfo = { }; // Callback for subscriber creation. -function createSubscriberCallBack(err, commonEventSubscriber) { +function createCB(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { @@ -371,14 +220,14 @@ function createSubscriberCallBack(err, commonEventSubscriber) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createCB); ``` - - ## CommonEvent.createSubscriber -createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ +```ts +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise +``` Creates a subscriber. This API uses a promise to return the result. @@ -397,7 +246,7 @@ Creates a subscriber. This API uses a promise to return the result. **Example** -```js +```ts let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. @@ -414,11 +263,11 @@ CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { }); ``` - - ## CommonEvent.subscribe -subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void +```ts +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback): void +``` Subscribes to common events. This API uses an asynchronous callback to return the result. @@ -433,7 +282,7 @@ Subscribes to common events. This API uses an asynchronous callback to return th **Example** -```js +```ts let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. @@ -442,7 +291,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function subscribeCallBack(err, data) { +function subscribeCB(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); } else { @@ -451,26 +300,25 @@ function subscribeCallBack(err, data) { } // Callback for subscriber creation. -function createSubscriberCallBack(err, commonEventSubscriber) { +function createCB(err, subscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); - subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, subscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCB); } } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createCB); ``` - - ## CommonEvent.unsubscribe -unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void +```ts +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback): void +``` Unsubscribes from common events. This API uses an asynchronous callback to return the result. @@ -485,7 +333,7 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur **Example** -```js +```ts let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. @@ -494,7 +342,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function subscribeCallBack(err, data) { +function subscribeCB(err, data) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); } else { @@ -503,19 +351,19 @@ function subscribeCallBack(err, data) { } // Callback for subscriber creation. -function createSubscriberCallBack(err, commonEventSubscriber) { +function createCB(err, commonEventSubscriber) { if (err.code) { console.info("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, subscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCB); } } // Callback for common event unsubscription. -function unsubscribeCallBack(err) { +function unsubscribeCB(err) { if (err.code) { console.info("unsubscribe failed " + JSON.stringify(err)); } else { @@ -524,19 +372,21 @@ function unsubscribeCallBack(err) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createCB); // Unsubscribe from the common event. -CommonEvent.unsubscribe(subscriber, unsubscribeCallBack); +CommonEvent.unsubscribe(subscriber, unsubscribeCB); ``` ## CommonEventSubscriber ### getCode -getCode(callback: AsyncCallback\): void +```ts +getCode(callback: AsyncCallback): void +``` -Obtains the result code of this common event. This API uses an asynchronous callback to return the result. +Obtains the code of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -544,29 +394,31 @@ Obtains the result code of this common event. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result code.| +| callback | AsyncCallback\ | Yes | Common event code.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for result code obtaining of an ordered common event. -function getCodeCallback(err, Code) { +function getCodeCB(err, Code) { if (err.code) { console.error("getCode failed " + JSON.stringify(err)); } else { console.info("getCode " + JSON.stringify(Code)); } } -subscriber.getCode(getCodeCallback); +subscriber.getCode(getCodeCB); ``` ### getCode -getCode(): Promise\ +```ts +getCode(): Promise +``` -Obtains the result code of this common event. This API uses a promise to return the result. +Obtains the code of this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -574,15 +426,15 @@ Obtains the result code of this common event. This API uses a promise to return | Type | Description | | ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Common event code.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. -subscriber.getCode().then((Code) => { - console.info("getCode " + JSON.stringify(Code)); +subscriber.getCode().then((code) => { + console.info("getCode " + JSON.stringify(code)); }).catch((err) => { console.error("getCode failed " + JSON.stringify(err)); }); @@ -590,9 +442,11 @@ subscriber.getCode().then((Code) => { ### setCode -setCode(code: number, callback: AsyncCallback\): void +```ts +setCode(code: number, callback: AsyncCallback): void +``` -Sets the result code for this common event. This API uses an asynchronous callback to return the result. +Sets the code for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -600,30 +454,32 @@ Sets the result code for this common event. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Result code of the common event. | +| code | number | Yes | Common event code. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for result code setting of an ordered common event. -function setCodeCallback(err) { +function setCodeCB(err) { if (err.code) { console.error("setCode failed " + JSON.stringify(err)); } else { console.info("setCode"); } } -subscriber.setCode(1, setCodeCallback); +subscriber.setCode(1, setCodeCB); ``` ### setCode -setCode(code: number): Promise\ +```ts +setCode(code: number): Promise +``` -Sets the result code for this common event. This API uses a promise to return the result. +Sets the code for this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -631,7 +487,7 @@ Sets the result code for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | Yes | Result code of the common event.| +| code | number | Yes | Common event code.| **Return value** @@ -641,7 +497,7 @@ Sets the result code for this common event. This API uses a promise to return th **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { @@ -653,9 +509,11 @@ subscriber.setCode(1).then(() => { ### getData -getData(callback: AsyncCallback\): void +```ts +getData(callback: AsyncCallback): void +``` -Obtains the result data of this common event. This API uses an asynchronous callback to return the result. +Obtains the data of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -663,29 +521,32 @@ Obtains the result data of this common event. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Result data of the common event.| +| callback | AsyncCallback\ | Yes | Common event data.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for result data obtaining of an ordered common event. -function getDataCallback(err, Data) { +function getDataCB(err, data) { if (err.code) { console.error("getData failed " + JSON.stringify(err)); } else { - console.info("getData " + JSON.stringify(Data)); + console.info("getData " + JSON.stringify(data)); } } -subscriber.getData(getDataCallback); + +subscriber.getData(getDataCB); ``` ### getData -getData(): Promise\ +```ts +getData(): Promise +``` -Obtains the result data of this common event. This API uses a promise to return the result. +Obtains the data of this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -693,15 +554,15 @@ Obtains the result data of this common event. This API uses a promise to return | Type | Description | | ---------------- | ------------------ | -| Promise\ | Result data of the common event.| +| Promise\ | Common event data.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. -subscriber.getData().then((Data) => { - console.info("getData " + JSON.stringify(Data)); +subscriber.getData().then((data) => { + console.info("getData " + JSON.stringify(data)); }).catch((err) => { console.error("getData failed " + JSON.stringify(err)); }); @@ -709,9 +570,11 @@ subscriber.getData().then((Data) => { ### setData -setData(data: string, callback: AsyncCallback\): void +```ts +setData(data: string, callback: AsyncCallback): void +``` -Sets the result data for this common event. This API uses an asynchronous callback to return the result. +Sets the data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -719,30 +582,32 @@ Sets the result data for this common event. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------------- | -| data | string | Yes | Result data of the common event. | +| data | string | Yes | Common event data. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event -function setDataCallback(err) { +function setDataCB(err) { if (err.code) { console.error("setData failed " + JSON.stringify(err)); } else { console.info("setData"); } } -subscriber.setData("publish_data_changed", setDataCallback); +subscriber.setData("publish_data_changed", setDataCB); ``` ### setData -setData(data: string): Promise\ +```ts +setData(data: string): Promise +``` -Sets the result data for this common event. This API uses a promise to return the result. +Sets the data for this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -750,7 +615,7 @@ Sets the result data for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| data | string | Yes | Result data of the common event.| +| data | string | Yes | Common event data.| **Return value** @@ -760,7 +625,7 @@ Sets the result data for this common event. This API uses a promise to return th **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { @@ -772,9 +637,11 @@ subscriber.setData("publish_data_changed").then(() => { ### setCodeAndData -setCodeAndData(code: number, data: string, callback:AsyncCallback\): void +```ts +setCodeAndData(code: number, data: string, callback:AsyncCallback): void +``` -Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. +Sets the code and data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -782,31 +649,34 @@ Sets the result code and result data for this common event. This API uses an asy | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Result code of the common event. | -| data | string | Yes | Result data of the common event. | +| code | number | Yes | Common event code. | +| data | string | Yes | Common event data. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for result code and result data setting of an ordered common event. -function setCodeDataCallback(err) { +function setCodeDataCB(err) { if (err.code) { console.error("setCodeAndData failed " + JSON.stringify(err)); } else { console.info("setCodeDataCallback"); } } -subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); + +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); ``` ### setCodeAndData -setCodeAndData(code: number, data: string): Promise\ +```ts +setCodeAndData(code: number, data: string): Promise +``` -Sets the result code and result data for this common event. This API uses a promise to return the result. +Sets the code and data for this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -814,8 +684,8 @@ Sets the result code and result data for this common event. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| code | number | Yes | Result code of the common event.| -| data | string | Yes | Result data of the common event.| +| code | number | Yes | Common event code.| +| data | string | Yes | Common event data.| **Return value** @@ -825,7 +695,7 @@ Sets the result code and result data for this common event. This API uses a prom **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { @@ -837,11 +707,12 @@ subscriber.setCodeAndData(1, "publish_data_changed").then(() => { ### isOrderedCommonEvent -isOrderedCommonEvent(callback: AsyncCallback\): void +```ts +isOrderedCommonEvent(callback: AsyncCallback): void +``` Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. - **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -852,27 +723,28 @@ Checks whether this common event is an ordered one. This API uses an asynchronou **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. -function isOrderedCallback(err, isOrdered) { +function isOrderedCB(err, isOrdered) { if (err.code) { console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); } else { console.info("isOrdered " + JSON.stringify(isOrdered)); } } -subscriber.isOrderedCommonEvent(isOrderedCallback); +subscriber.isOrderedCommonEvent(isOrderedCB); ``` ### isOrderedCommonEvent -isOrderedCommonEvent(): Promise\ +```ts +isOrderedCommonEvent(): Promise +``` Checks whether this common event is an ordered one. This API uses a promise to return the result. - **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -883,7 +755,7 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { @@ -895,11 +767,12 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { ### isStickyCommonEvent -isStickyCommonEvent(callback: AsyncCallback\): void +```ts +isStickyCommonEvent(callback: AsyncCallback): void +``` Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. - **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -910,27 +783,28 @@ Checks whether this common event is a sticky one. This API uses an asynchronous **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. -function isStickyCallback(err, isSticky) { +function isStickyCB(err, isSticky) { if (err.code) { console.error("isStickyCommonEvent failed " + JSON.stringify(err)); } else { console.info("isSticky " + JSON.stringify(isSticky)); } } -subscriber.isStickyCommonEvent(isStickyCallback); +subscriber.isStickyCommonEvent(isStickyCB); ``` ### isStickyCommonEvent -isStickyCommonEvent(): Promise\ +```ts +isStickyCommonEvent(): Promise +``` Checks whether this common event is a sticky one. This API uses a promise to return the result. - **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -941,7 +815,7 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { @@ -953,7 +827,9 @@ subscriber.isStickyCommonEvent().then((isSticky) => { ### abortCommonEvent -abortCommonEvent(callback: AsyncCallback\): void +```ts +abortCommonEvent(callback: AsyncCallback): void +``` Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -967,23 +843,26 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for common event aborting. -function abortCallback(err) { +function abortCB(err) { if (err.code) { console.error("abortCommonEvent failed " + JSON.stringify(err)); } else { console.info("abortCommonEvent"); } } -subscriber.abortCommonEvent(abortCallback); + +subscriber.abortCommonEvent(abortCB); ``` ### abortCommonEvent -abortCommonEvent(): Promise\ +```ts +abortCommonEvent(): Promise +``` Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -997,7 +876,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { @@ -1009,7 +888,9 @@ subscriber.abortCommonEvent().then(() => { ### clearAbortCommonEvent -clearAbortCommonEvent(callback: AsyncCallback\): void +```ts +clearAbortCommonEvent(callback: AsyncCallback): void +``` Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -1023,23 +904,26 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. -function clearAbortCallback(err) { +function clearAbortCB(err) { if (err.code) { console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); } else { console.info("clearAbortCommonEvent"); } } -subscriber.clearAbortCommonEvent(clearAbortCallback); + +subscriber.clearAbortCommonEvent(clearAbortCB); ``` ### clearAbortCommonEvent -clearAbortCommonEvent(): Promise\ +```ts +clearAbortCommonEvent(): Promise +``` Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1053,7 +937,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { @@ -1065,7 +949,9 @@ subscriber.clearAbortCommonEvent().then(() => { ### getAbortCommonEvent -getAbortCommonEvent(callback: AsyncCallback\): void +```ts +getAbortCommonEvent(callback: AsyncCallback): void +``` Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -1079,23 +965,26 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. -function getAbortCallback(err, AbortCommonEvent) { +function getAbortCB(err, abortEvent) { if (err.code) { console.error("getAbortCommonEvent failed " + JSON.stringify(err)); } else { - console.info("AbortCommonEvent " + AbortCommonEvent) + console.info("abortEvent " + abortEvent) } } -subscriber.getAbortCommonEvent(getAbortCallback); + +subscriber.getAbortCommonEvent(getAbortCB); ``` ### getAbortCommonEvent -getAbortCommonEvent(): Promise\ +```ts +getAbortCommonEvent(): Promise +``` Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1109,11 +998,11 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** -```js +```ts let subscriber; // Subscriber object successfully created. -subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { - console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +subscriber.getAbortCommonEvent().then((abortCommonEvent) => { + console.info("abortCommonEvent " + JSON.stringify(abortCommonEvent)); }).catch((err) => { console.error("getAbortCommonEvent failed " + JSON.stringify(err)); }); @@ -1121,7 +1010,9 @@ subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { ### getSubscribeInfo -getSubscribeInfo(callback: AsyncCallback\): void +```ts +getSubscribeInfo(callback: AsyncCallback): void +``` Obtains the subscriber information. This API uses an asynchronous callback to return the result. @@ -1135,23 +1026,26 @@ Obtains the subscriber information. This API uses an asynchronous callback to re **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. -function getSubscribeInfoCallback(err, SubscribeInfo) { +function getCB(err, subscribeInfo) { if (err.code) { console.error("getSubscribeInfo failed " + JSON.stringify(err)); } else { - console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + console.info("SubscribeInfo " + JSON.stringify(subscribeInfo)); } } -subscriber.getSubscribeInfo(getSubscribeInfoCallback); + +subscriber.getSubscribeInfo(getCB); ``` ### getSubscribeInfo -getSubscribeInfo(): Promise\ +```ts +getSubscribeInfo(): Promise +``` Obtains the subscriber information. This API uses a promise to return the result. @@ -1165,11 +1059,11 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** -```js +```ts let subscriber; // Subscriber object successfully created. -subscriber.getSubscribeInfo().then((SubscribeInfo) => { - console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +subscriber.getSubscribeInfo().then((subscribeInfo) => { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); }).catch((err) => { console.error("getSubscribeInfo failed " + JSON.stringify(err)); }); @@ -1177,9 +1071,11 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { ### finishCommonEvent9+ -finishCommonEvent(callback: AsyncCallback\): void +```ts +finishCommonEvent(callback: AsyncCallback): void +``` -Finishes this ordered common event. This API uses an asynchronous callback to return the result. +Finishes this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1191,25 +1087,28 @@ Finishes this ordered common event. This API uses an asynchronous callback to re **Example** -```js +```ts let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. -function finishCommonEventCallback(err) { - if (err.code) { - console.error("finishCommonEvent failed " + JSON.stringify(err)); -} else { - console.info("FinishCommonEvent"); -} +function finishCB(err) { + if (err.code) { + console.error("finishCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("FinishCommonEvent"); + } } -subscriber.finishCommonEvent(finishCommonEventCallback); + +subscriber.finishCommonEvent(finishCB); ``` ### finishCommonEvent9+ -finishCommonEvent(): Promise\ +```ts +finishCommonEvent(): Promise +``` -Finishes this ordered common event. This API uses a promise to return the result. +Finishes this common event. This API takes effect only for ordered common events. It uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1221,7 +1120,7 @@ Finishes this ordered common event. This API uses a promise to return the result **Example** -```js +```ts let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { @@ -1240,7 +1139,7 @@ Describes the common event data body. | Name | Type | Readable| Writable| Description | | ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | | event | string | Yes | No | Name of the common event that is being received. | -| bundleName | string | Yes | No | Bundle name. | +| bundleName | string | Yes | No | Bundle name. | | code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | | data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| | parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | @@ -1254,10 +1153,10 @@ Describes the data body published by a common event, including the common event | Name | Type | Readable| Writable| Description | | --------------------- | -------------------- | ---- | ---- | ---------------------------- | -| bundleName | string | Yes | No | Bundle name. | +| bundleName | string | Yes | No | Bundle name. | | code | number | Yes | No | Result code of the common event. | | data | string | Yes | No | Custom result data of the common event.| -| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | | isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | | isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| | parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | @@ -1270,7 +1169,7 @@ Provides the subscriber information. | Name | Type | Readable| Writable| Description | | ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| events | Array\ | Yes | No | Name of the common event to publish. | +| events | Array\ | Yes | No | Name of the common event to publish. | | publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | | publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | | userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md index 502603da539a71e465fcfbffb8e69ba696d4e6ea..982f0d103e100d14712db5b16e0ae98552869e6e 100644 --- a/en/application-dev/reference/apis/js-apis-commonEventManager.md +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -1,6 +1,6 @@ -# @ohos.commonEventManager +# @ohos.commonEventManager (Common Event) -The **CommonEventManager** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. +The **CommonEventManager** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events. > **NOTE** > @@ -14,174 +14,17 @@ import CommonEventManager from '@ohos.commonEventManager'; ## Support -The table below lists the event types supported by the **CommonEventManager** module. The name and value indicate the macro and name of a common event, respectively. - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Value | Subscriber Permission | Description | -| ------------ | ------------------ | ---------------------- | -------------------- | -| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | -| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | -| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | Indicates the common event that the device is being shut down and the final shutdown will proceed. | -| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | Indicates the common event that the charging state, level, and other information about the battery have changed. | -| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | Indicates the common event that the battery level is low. | -| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | Indicates the common event that the battery exits the low state. | -| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | Indicates the common event that the device is connected to an external power supply. | -| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | -| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | -| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | -| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | -| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | -| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | -| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | -| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | Indicates the common event that the system time has changed. | -| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | Indicates the common event that the system time zone has changed. | -| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | -| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | -| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | -| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. -| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | -| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | -| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | -| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | Indicates the common event that an application package has been changed (for example, a component in the package has been enabled or disabled). | -| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | Indicates the common event that the user has restarted the application package and killed all its processes. | -| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | Indicates the common event that the user has cleared the application package data. | -| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | - | Indicates the common event that the user has cleared the application package data. | -| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | Indicates the common event that application packages have been suspended. | -| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | -| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | Indicates the common event that an application package has been suspended. | -| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | -| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | Indicates the common event that a user ID has been removed from the system. | -| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | Indicates the common event that an installed application is started for the first time. | -| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | Indicates the common event that an application requires system verification. | -| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | Indicates the common event that an application has been verified by the system. | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | Indicates the common event that applications installed on the external storage become available for the system. | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | Indicates the common event that applications installed on the external storage become unavailable for the system. | -| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | Indicates the common event that the device state (for example, orientation and locale) has changed. | -| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | Indicates the common event that the device locale has changed. | -| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | Indicates the common event that the device storage is insufficient. | -| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | Indicates the common event that the system is in driving mode. | -| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | Indicates the common event that the system is in home mode. | -| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | Indicates the common event that the system is in office mode. | -| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | -| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | -| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | -| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that user switching is happening. | -| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be started. | -| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | -| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be stopped. | -| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | -| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN | usual.event.DISTRIBUTED_ACCOUNT_LOGIN | - | Indicates the action of successful login using a distributed account. | -| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT | usual.event.DISTRIBUTED_ACCOUNT_LOGOUT | - | Indicates the action of successful logout of a distributed account. | -| COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID | usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID | - | Indicates the action when the token of a distributed account is invalid. | -| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF | usual.event.DISTRIBUTED_ACCOUNT_LOGOFF | - | Indicates the action of deregistering a distributed account. | -| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | -| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | -| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | -| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | -| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | -| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | -| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | -| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | -| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | -| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P state, such as enabled and disabled. | -| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of Wi-Fi P2P peer devices. | -| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P discovery status change. | -| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of the Wi-Fi P2P local device. | -| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi P2P group information has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth handsfree communication. | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected to the Bluetooth handsfree is active. | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth A2DP. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected using Bluetooth A2DP is active. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the AVRCP connection state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio codec state of Bluetooth A2DP has changed. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | Indicates the common event that a remote Bluetooth device is discovered. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth class of a remote Bluetooth device has changed. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been established with a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been disconnected from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | Indicates the common event about the connection request from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | Indicates the common event about the response to the connection request from a remote Bluetooth device. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | Indicates the common event that the connection to a remote Bluetooth device has been canceled. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | Indicates the common event that the connection state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | -| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | -| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the action of a common event that the NFC RF field is detected to be in the enabled state. | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | -| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | -| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | -| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | -| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | -| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been added to the system. | -| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been removed from the system. | -| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | -| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | -| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | -| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | -| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | -| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | -| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | Indicates the common event that a third-party application is instructed to pause the current work. | -| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | Indicates the common event that a third-party application is instructed to save its last mode. | -| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | Indicates the common event that the voltage of the vehicle's power system is abnormal. | -| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is high. | -| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is extremely high. | -| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | Indicates the common event that the IVI system has an extreme temperature. | -| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | Indicates the common event that the voltage of the vehicle's power system is restored to normal. | -| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | Indicates the common event that the temperature of the IVI system is restored to normal. | -| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | Indicates the common event that the battery service is active. | -|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates a common event indicating that the USB device status changes. | -|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the public event that the USB port status of the user device changes. | -| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | -| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | -| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | -| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | -| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | -| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | -| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | -| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | -| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | -| COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | -| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | -| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | -| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | +A system common event is an event that is published by a system service or system application and requires specific permissions to subscribe to. To publish or subscribe to this type of event, you must follow the event-specific definitions. +For details about the definitions of all system common events, see [System Common Events](./commonEventManager-definitions.md). ## CommonEventManager.publish -publish(event: string, callback: AsyncCallback\): void +```ts +publish(event: string, callback: AsyncCallback): void +``` -Publishes a common event. This API uses an asynchronous callback to return the result. +Publishes a common event and executes an asynchronous callback after the event is published. **System capability**: SystemCapability.Notification.CommonEvent @@ -190,23 +33,17 @@ Publishes a common event. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------- | | event | string | Yes | Name of the common event to publish.| -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback to execute after the event is published.| **Error codes** -For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). -|ID |Error Message | -|-----------|--------------------| -|1500004 |not System services or System app| -|1500007 |message send error| -|1500008 |CEMS error| -|1500009 |system error| +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). **Example** ```ts // Callback for common event publication -function publishCallBack(err) { +function publishCB(err) { if (err) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -216,7 +53,7 @@ function publishCallBack(err) { // Publish a common event. try { - CommonEventManager.publish("event", publishCallBack); + CommonEventManager.publish("event", publishCB); } catch(err) { console.error('publish failed, catch error' + JSON.stringify(err)); } @@ -224,7 +61,9 @@ try { ## CommonEventManager.publish -publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void +```ts +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback): void +``` Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. @@ -239,27 +78,21 @@ Publishes a common event with given attributes. This API uses an asynchronous ca | callback | syncCallback\ | Yes | Callback used to return the result. | **Error codes** -|ID |Error Message | -|-----------|--------------------| -|1500004 |not System services or System app| -|1500007 |message send error| -|1500008 |CEMS error| -|1500009 |system error| +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). **Example** - ```ts // Attributes of a common event. -var options = { - code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event. +let options = { + code: 0, // Initial code of the common event. + data: "initial data";// Initial data of the common event. isOrdered: true // The common event is an ordered one. } // Callback for common event publication -function publishCallBack(err) { +function publishCB(err) { if (err) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -269,17 +102,17 @@ function publishCallBack(err) { // Publish a common event. try { - CommonEventManager.publish("event", options, publishCallBack); + CommonEventManager.publish("event", options, publishCB); } catch (err) { console.error('publish failed, catch error' + JSON.stringify(err)); } ``` - - ## CommonEventManager.publishAsUser -publishAsUser(event: string, userId: number, callback: AsyncCallback\): void +```ts +publishAsUser(event: string, userId: number, callback: AsyncCallback): void +``` Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. @@ -296,18 +129,14 @@ Publishes a common event to a specific user. This API uses an asynchronous callb | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** -|ID |Error Message | -|-----------|--------------------| -|1500004 |not System services or System app| -|1500007 |message send error| -|1500008 |CEMS error| -|1500009 |system error| + +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). **Example** ```ts // Callback for common event publication -function publishAsUserCallBack(err) { +function publishCB(err) { if (err) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -316,21 +145,21 @@ function publishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. try { - CommonEventManager.publishAsUser("event", userId, publishAsUserCallBack); + CommonEventManager.publishAsUser("event", userId, publishCB); } catch (err) { console.error('publishAsUser failed, catch error' + JSON.stringify(err)); } ``` - - ## CommonEventManager.publishAsUser -publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void +```ts +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback): void +``` Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. @@ -348,25 +177,21 @@ Publishes a common event with given attributes to a specific user. This API uses | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** -|ID |Error Message | -|-----------|--------------------| -|1500004 |not System services or System app| -|1500007 |message send error| -|1500008 |CEMS error| -|1500009 |system error| + +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). **Example** ```ts // Attributes of a common event. -var options = { - code: 0, // Result code of the common event. - data: "initial data";// Result data of the common event. +let options = { + code: 0, // Initial code of the common event. + data: "initial data";// Initial data of the common event. } -// Callback for common event publication -function publishAsUserCallBack(err) { +// Callback for common event publication. +function publishCB(err) { if (err) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -375,21 +200,21 @@ function publishAsUserCallBack(err) { } // Specify the user to whom the common event will be published. -var userId = 100; +let userId = 100; // Publish a common event. try { - CommonEventManager.publishAsUser("event", userId, options, publishAsUserCallBack); + CommonEventManager.publishAsUser("event", userId, options, publishCB); } catch (err) { console.error('publishAsUser failed, catch error' + JSON.stringify(err)); } ``` - - ## CommonEventManager.createSubscriber -createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void +```ts +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback): void +``` Creates a subscriber. This API uses an asynchronous callback to return the result. @@ -406,15 +231,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul ```ts -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; // Callback for subscriber creation. -function createSubscriberCallBack(err, commonEventSubscriber) { +function createCB(err, commonEventSubscriber) { if(!err) { console.info("createSubscriber"); subscriber = commonEventSubscriber; @@ -425,17 +250,17 @@ function createSubscriberCallBack(err, commonEventSubscriber) { // Create a subscriber. try { - CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); + CommonEventManager.createSubscriber(subscribeInfo, createCB); } catch (err) { console.error('createSubscriber failed, catch error' + JSON.stringify(err)); } ``` - - ## CommonEventManager.createSubscriber -createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ +```ts +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise +``` Creates a subscriber. This API uses a promise to return the result. @@ -455,32 +280,28 @@ Creates a subscriber. This API uses a promise to return the result. **Example** ```ts -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; // Create a subscriber. -try { - CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { +CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { console.info("createSubscriber"); subscriber = commonEventSubscriber; }).catch((err) => { console.error("createSubscriber failed " + JSON.stringify(err)); }); -} catch(err) { - console.error('createSubscriber failed, catch error' + JSON.stringify(err)); -} ``` - - ## CommonEventManager.subscribe -subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void +```ts +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback): void +``` Subscribes to common events. This API uses an asynchronous callback to return the result. @@ -497,15 +318,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th ```ts // Subscriber information. -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function SubscribeCB(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); } else { @@ -514,13 +335,12 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function createSubscriberCallBack(err, commonEventSubscriber) { +function createCB(err, subscriber) { if(!err) { console.info("createSubscriber"); - subscriber = commonEventSubscriber; // Subscribe to a common event. try { - CommonEventManager.subscribe(subscriber, SubscribeCallBack); + CommonEventManager.subscribe(subscriber, SubscribeCB); } catch (err) { console.error("createSubscriber failed " + JSON.stringify(err)); } @@ -531,17 +351,17 @@ function createSubscriberCallBack(err, commonEventSubscriber) { // Create a subscriber. try { - CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); + CommonEventManager.createSubscriber(subscribeInfo, createCB); } catch (err) { console.error('createSubscriber failed, catch error' + JSON.stringify(err)); } ``` - - ## CommonEventManager.unsubscribe -unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void +```ts +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback): void +``` Unsubscribes from common events. This API uses an asynchronous callback to return the result. @@ -557,13 +377,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur **Example** ```ts -var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information. -var subscribeInfo = { +let subscribeInfo = { events: ["event"] }; // Callback for common event subscription. -function subscribeCallBack(err, data) { +function subscribeCB(err, data) { if (err) { console.info("subscribe failed " + JSON.stringify(err)); } else { @@ -571,22 +391,21 @@ function subscribeCallBack(err, data) { } } // Callback for subscriber creation. -function createSubscriberCallBack(err, commonEventSubscriber) { +function createCB(err, subscriber) { if (err) { console.info("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); - subscriber = commonEventSubscriber; // Subscribe to a common event. try { - CommonEventManager.subscribe(subscriber, subscribeCallBack); + CommonEventManager.subscribe(subscriber, subscribeCB); } catch(err) { console.info("subscribe failed " + JSON.stringify(err)); } } } // Callback for common event unsubscription. -function unsubscribeCallBack(err) { +function unsubscribeCB(err) { if (err) { console.info("unsubscribe failed " + JSON.stringify(err)); } else { @@ -595,14 +414,14 @@ function unsubscribeCallBack(err) { } // Create a subscriber. try { - CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); + CommonEventManager.createSubscriber(subscribeInfo, createCB); } catch (err) { console.info("createSubscriber failed " + JSON.stringify(err)); } // Unsubscribe from the common event. try { - CommonEventManager.unsubscribe(subscriber, unsubscribeCallBack); + CommonEventManager.unsubscribe(subscriber, unsubscribeCB); } catch (err) { console.info("unsubscribe failed " + JSON.stringify(err)); } @@ -612,9 +431,11 @@ try { ### getCode -getCode(callback: AsyncCallback\): void +```ts +getCode(callback: AsyncCallback): void +``` -Obtains the result code of this common event. This API uses an asynchronous callback to return the result. +Obtains the code of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -622,29 +443,31 @@ Obtains the result code of this common event. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Common event code.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -// Callback for result code obtaining of an ordered common event. -function getCodeCallback(err, Code) { +// Callback for code obtaining of an ordered common event. +function getCodeCB(err, code) { if (err.code) { console.error("getCode failed " + JSON.stringify(err)); } else { - console.info("getCode " + JSON.stringify(Code)); + console.info("getCode " + JSON.stringify(code)); } } -subscriber.getCode(getCodeCallback); +subscriber.getCode(getCodeCB); ``` ### getCode -getCode(): Promise\ +```ts +getCode(): Promise +``` -Obtains the result code of this common event. This API uses a promise to return the result. +Obtains the code of this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -652,15 +475,15 @@ Obtains the result code of this common event. This API uses a promise to return | Type | Description | | ---------------- | -------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Common event code.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -subscriber.getCode().then((Code) => { - console.info("getCode " + JSON.stringify(Code)); +subscriber.getCode().then((code) => { + console.info("getCode " + JSON.stringify(code)); }).catch((err) => { console.error("getCode failed " + JSON.stringify(err)); }); @@ -668,9 +491,11 @@ subscriber.getCode().then((Code) => { ### setCode -setCode(code: number, callback: AsyncCallback\): void +```ts +setCode(code: number, callback: AsyncCallback): void +``` -Sets the result code for this common event. This API uses an asynchronous callback to return the result. +Sets the code for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -678,30 +503,32 @@ Sets the result code for this common event. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Result code of the common event. | +| code | number | Yes | Common event code. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -// Callback for result code setting of an ordered common event. -function setCodeCallback(err) { +// Callback for code setting of an ordered common event. +function setCodeCB(err) { if (err.code) { console.error("setCode failed " + JSON.stringify(err)); } else { console.info("setCode"); } } -subscriber.setCode(1, setCodeCallback); +subscriber.setCode(1, setCodeCB); ``` ### setCode -setCode(code: number): Promise\ +```ts +setCode(code: number): Promise +``` -Sets the result code for this common event. This API uses a promise to return the result. +Sets the code for this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -709,7 +536,7 @@ Sets the result code for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | Yes | Result code of the common event.| +| code | number | Yes | Common event code.| **Return value** @@ -720,7 +547,7 @@ Sets the result code for this common event. This API uses a promise to return th **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCode(1).then(() => { console.info("setCode"); @@ -731,9 +558,11 @@ subscriber.setCode(1).then(() => { ### getData -getData(callback: AsyncCallback\): void +```ts +getData(callback: AsyncCallback): void +``` -Obtains the result data of this common event. This API uses an asynchronous callback to return the result. +Obtains the data of this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -741,29 +570,31 @@ Obtains the result data of this common event. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result data.| +| callback | AsyncCallback\ | Yes | Common event data.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -// Callback for result data obtaining of an ordered common event. -function getDataCallback(err, Data) { +// Callback for data obtaining of an ordered common event. +function getDataCB(err, data) { if (err.code) { console.error("getData failed " + JSON.stringify(err)); } else { - console.info("getData " + JSON.stringify(Data)); + console.info("getData " + JSON.stringify(data)); } } -subscriber.getData(getDataCallback); +subscriber.getData(getDataCB); ``` ### getData -getData(): Promise\ +```ts +getData(): Promise +``` -Obtains the result data of this common event. This API uses a promise to return the result. +Obtains the data of this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -771,15 +602,15 @@ Obtains the result data of this common event. This API uses a promise to return | Type | Description | | ---------------- | ------------------ | -| Promise\ | Promise used to return the result data.| +| Promise\ | Common event data.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -subscriber.getData().then((Data) => { - console.info("getData " + JSON.stringify(Data)); +subscriber.getData().then((data) => { + console.info("getData " + JSON.stringify(data)); }).catch((err) => { console.error("getData failed " + JSON.stringify(err)); }); @@ -789,7 +620,7 @@ subscriber.getData().then((Data) => { setData(data: string, callback: AsyncCallback\): void -Sets the result data for this common event. This API uses an asynchronous callback to return the result. +Sets the data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -797,30 +628,32 @@ Sets the result data for this common event. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------------- | -| data | string | Yes | Result data of the common event. | +| data | string | Yes | Common event data. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for result data setting of an ordered common event -function setDataCallback(err) { +function setDataCB(err) { if (err.code) { console.error("setData failed " + JSON.stringify(err)); } else { console.info("setData"); } } -subscriber.setData("publish_data_changed", setDataCallback); +subscriber.setData("publish_data_changed", setDataCB); ``` ### setData -setData(data: string): Promise\ +```ts +setData(data: string): Promise +``` -Sets the result data for this common event. This API uses a promise to return the result. +Sets the data for this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -828,7 +661,7 @@ Sets the result data for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| data | string | Yes | Result data of the common event.| +| data | string | Yes | Common event data.| **Return value** @@ -839,7 +672,7 @@ Sets the result data for this common event. This API uses a promise to return th **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setData("publish_data_changed").then(() => { console.info("setData"); @@ -850,9 +683,11 @@ subscriber.setData("publish_data_changed").then(() => { ### setCodeAndData -setCodeAndData(code: number, data: string, callback:AsyncCallback\): void +```ts +setCodeAndData(code: number, data: string, callback:AsyncCallback): void +``` -Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. +Sets the code and data for this common event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -860,31 +695,33 @@ Sets the result code and result data for this common event. This API uses an asy | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------- | -| code | number | Yes | Result code of the common event. | -| data | string | Yes | Result data of the common event. | +| code | number | Yes | Common event code. | +| data | string | Yes | Common event data. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -// Callback for result code and result data setting of an ordered common event. -function setCodeDataCallback(err) { +// Callback for code and data setting of an ordered common event. +function setCodeDataCB(err) { if (err.code) { console.error("setCodeAndData failed " + JSON.stringify(err)); } else { console.info("setCodeDataCallback"); } } -subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCB); ``` ### setCodeAndData -setCodeAndData(code: number, data: string): Promise\ +```ts +setCodeAndData(code: number, data: string): Promise +``` -Sets the result code and result data for this common event. This API uses a promise to return the result. +Sets the code and data for this common event. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -892,8 +729,8 @@ Sets the result code and result data for this common event. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| code | number | Yes | Result code of the common event.| -| data | string | Yes | Result data of the common event.| +| code | number | Yes | Common event code.| +| data | string | Yes | Common event data.| **Return value** @@ -904,7 +741,7 @@ Sets the result code and result data for this common event. This API uses a prom **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.setCodeAndData(1, "publish_data_changed").then(() => { console.info("setCodeAndData"); @@ -915,12 +752,12 @@ subscriber.setCodeAndData(1, "publish_data_changed").then(() => { ### isOrderedCommonEvent -isOrderedCommonEvent(callback: AsyncCallback\): void +```ts +isOrderedCommonEvent(callback: AsyncCallback): void +``` Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. - - **System capability**: SystemCapability.Notification.CommonEvent **Parameters** @@ -932,28 +769,28 @@ Checks whether this common event is an ordered one. This API uses an asynchronou **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is an ordered one. -function isOrderedCallback(err, isOrdered) { +function isOrderedCB(err, isOrdered) { if (err.code) { console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); } else { console.info("isOrdered " + JSON.stringify(isOrdered)); } } -subscriber.isOrderedCommonEvent(isOrderedCallback); +subscriber.isOrderedCommonEvent(isOrderedCB); ``` ### isOrderedCommonEvent -isOrderedCommonEvent(): Promise\ +```ts +isOrderedCommonEvent(): Promise +``` Checks whether this common event is an ordered one. This API uses a promise to return the result. - - -**System capability**: SystemCapability.Notification.CommonEvent + **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -964,7 +801,7 @@ Checks whether this common event is an ordered one. This API uses a promise to r **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isOrderedCommonEvent().then((isOrdered) => { console.info("isOrdered " + JSON.stringify(isOrdered)); @@ -975,11 +812,11 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { ### isStickyCommonEvent -isStickyCommonEvent(callback: AsyncCallback\): void - -Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. +```ts +isStickyCommonEvent(callback: AsyncCallback): void +``` - +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -992,27 +829,27 @@ Checks whether this common event is a sticky one. This API uses an asynchronous **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is a sticky one. -function isStickyCallback(err, isSticky) { +function isStickyCB(err, isSticky) { if (err.code) { console.error("isStickyCommonEvent failed " + JSON.stringify(err)); } else { console.info("isSticky " + JSON.stringify(isSticky)); } } -subscriber.isStickyCommonEvent(isStickyCallback); +subscriber.isStickyCommonEvent(isStickyCB); ``` ### isStickyCommonEvent -isStickyCommonEvent(): Promise\ +```ts +isStickyCommonEvent(): Promise +``` Checks whether this common event is a sticky one. This API uses a promise to return the result. - - **System capability**: SystemCapability.Notification.CommonEvent **Return value** @@ -1024,7 +861,7 @@ Checks whether this common event is a sticky one. This API uses a promise to ret **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.isStickyCommonEvent().then((isSticky) => { console.info("isSticky " + JSON.stringify(isSticky)); @@ -1035,7 +872,9 @@ subscriber.isStickyCommonEvent().then((isSticky) => { ### abortCommonEvent -abortCommonEvent(callback: AsyncCallback\): void +```ts +abortCommonEvent(callback: AsyncCallback): void +``` Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -1050,22 +889,24 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for common event aborting. -function abortCallback(err) { +function abortCB(err) { if (err.code) { console.error("abortCommonEvent failed " + JSON.stringify(err)); } else { console.info("abortCommonEvent"); } } -subscriber.abortCommonEvent(abortCallback); +subscriber.abortCommonEvent(abortCB); ``` ### abortCommonEvent -abortCommonEvent(): Promise\ +```ts +abortCommonEvent(): Promise +``` Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1080,7 +921,7 @@ Aborts this common event. After the abort, the common event is not sent to the n **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.abortCommonEvent().then(() => { console.info("abortCommonEvent"); @@ -1091,7 +932,9 @@ subscriber.abortCommonEvent().then(() => { ### clearAbortCommonEvent -clearAbortCommonEvent(callback: AsyncCallback\): void +```ts +clearAbortCommonEvent(callback: AsyncCallback): void +``` Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -1106,22 +949,24 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for clearing the aborted state of the current common event. -function clearAbortCallback(err) { +function clearAbortCB(err) { if (err.code) { console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); } else { console.info("clearAbortCommonEvent"); } } -subscriber.clearAbortCommonEvent(clearAbortCallback); +subscriber.clearAbortCommonEvent(clearAbortCB); ``` ### clearAbortCommonEvent -clearAbortCommonEvent(): Promise\ +```ts +clearAbortCommonEvent(): Promise +``` Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1136,7 +981,7 @@ Clears the aborted state of this common event. This API takes effect only for or **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.clearAbortCommonEvent().then(() => { console.info("clearAbortCommonEvent"); @@ -1147,7 +992,9 @@ subscriber.clearAbortCommonEvent().then(() => { ### getAbortCommonEvent -getAbortCommonEvent(callback: AsyncCallback\): void +```ts +getAbortCommonEvent(callback: AsyncCallback): void +``` Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. @@ -1162,22 +1009,24 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for checking whether the current common event is in the aborted state. -function getAbortCallback(err, AbortCommonEvent) { +function getAbortCB(err, abortEvent) { if (err.code) { console.error("getAbortCommonEvent failed " + JSON.stringify(err)); } else { - console.info("AbortCommonEvent " + AbortCommonEvent) + console.info("abortCommonEvent " + abortEvent) } } -subscriber.getAbortCommonEvent(getAbortCallback); +subscriber.getAbortCommonEvent(getAbortCB); ``` ### getAbortCommonEvent -getAbortCommonEvent(): Promise\ +```ts +getAbortCommonEvent(): Promise +``` Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1192,10 +1041,10 @@ Checks whether this common event is in the aborted state. This API takes effect **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { - console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +subscriber.getAbortCommonEvent().then((abortEvent) => { + console.info("abortCommonEvent " + JSON.stringify(abortEvent)); }).catch((err) => { console.error("getAbortCommonEvent failed " + JSON.stringify(err)); }); @@ -1203,7 +1052,9 @@ subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { ### getSubscribeInfo -getSubscribeInfo(callback: AsyncCallback\): void +```ts +getSubscribeInfo(callback: AsyncCallback): void +``` Obtains the subscriber information. This API uses an asynchronous callback to return the result. @@ -1218,22 +1069,24 @@ Obtains the subscriber information. This API uses an asynchronous callback to re **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for subscriber information obtaining. -function getSubscribeInfoCallback(err, SubscribeInfo) { +function getCB(err, subscribeInfo) { if (err.code) { console.error("getSubscribeInfo failed " + JSON.stringify(err)); } else { - console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); } } -subscriber.getSubscribeInfo(getSubscribeInfoCallback); +subscriber.getSubscribeInfo(getCB); ``` ### getSubscribeInfo -getSubscribeInfo(): Promise\ +```ts +getSubscribeInfo(): Promise +``` Obtains the subscriber information. This API uses a promise to return the result. @@ -1248,10 +1101,10 @@ Obtains the subscriber information. This API uses a promise to return the result **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. -subscriber.getSubscribeInfo().then((SubscribeInfo) => { - console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +subscriber.getSubscribeInfo().then((subscribeInfo) => { + console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); }).catch((err) => { console.error("getSubscribeInfo failed " + JSON.stringify(err)); }); @@ -1259,9 +1112,11 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { ### finishCommonEvent9+ -finishCommonEvent(callback: AsyncCallback\): void +```ts +finishCommonEvent(callback: AsyncCallback): void +``` -Finishes this ordered common event. This API uses an asynchronous callback to return the result. +Finishes this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1274,24 +1129,26 @@ Finishes this ordered common event. This API uses an asynchronous callback to re **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. // Callback for ordered common event finishing. -function finishCommonEventCallback(err) { +function finishCB(err) { if (err.code) { console.error("finishCommonEvent failed " + JSON.stringify(err)); } else { console.info("FinishCommonEvent"); } } -subscriber.finishCommonEvent(finishCommonEventCallback); +subscriber.finishCommonEvent(finishCB); ``` ### finishCommonEvent9+ -finishCommonEvent(): Promise\ +```ts +finishCommonEvent(): Promise +``` -Finishes this ordered common event. This API uses a promise to return the result. +Finishes this common event. This API takes effect only for ordered common events. It uses a promise to return the result. **System capability**: SystemCapability.Notification.CommonEvent @@ -1304,7 +1161,7 @@ Finishes this ordered common event. This API uses a promise to return the result **Example** ```ts -var subscriber; // Subscriber object successfully created. +let subscriber; // Subscriber object successfully created. subscriber.finishCommonEvent().then(() => { console.info("FinishCommonEvent"); @@ -1321,8 +1178,8 @@ subscriber.finishCommonEvent().then(() => { | ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | | event | string | Yes | No | Name of the common event that is being received. | | bundleName | string | Yes | No | Bundle name. | -| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | -| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| code | number | Yes | No | Code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom data of the common event, which is used to transfer data of the string type.| | parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | @@ -1333,8 +1190,8 @@ subscriber.finishCommonEvent().then(() => { | Name | Type | Readable| Writable| Description | | --------------------- | -------------------- | ---- | ---- | ---------------------------- | | bundleName | string | Yes | No | Bundle name. | -| code | number | Yes | No | Result code of the common event. | -| data | string | Yes | No | Custom result data of the common event.| +| code | number | Yes | No | Code of the common event. | +| data | string | Yes | No | Custom data of the common event.| | subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | | isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | | isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| diff --git a/en/application-dev/reference/apis/js-apis-configuration.md b/en/application-dev/reference/apis/js-apis-configuration.md deleted file mode 100644 index 25c57c7d5f0a6b7a1e8073fc9313bb92562b8576..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-configuration.md +++ /dev/null @@ -1,26 +0,0 @@ -# Configuration - -The **Configuration** module provides environment configuration information. - -> **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 - -```js -import Configuration from '@ohos.application.Configuration'; -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityBase - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| Yes| Language of the application.| -| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction9+ | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity9+ | ScreenDensity | 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.| diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index a166781108683f6b6fb53673da4deacd99882b26..2778a143c65125eca650324e67a220ab60f64ead 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -1,4 +1,4 @@ -# Contacts +# @ohos.contact (Contacts) >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md index cfbfb83e3359a4b7d41cf6ab039d0c1f0552c9eb..89ddd643d07a9882e289b27ff9fd0cc6679fd187 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @@ -1,6 +1,6 @@ # ContinuationExtraParams -The **ContinuationExtraParams** module provides the extra parameters required by the device selection module in the continuation management entry. +The **ContinuationExtraParams** module provides the filter parameters required by the device selection module in the continuation management entry. These filter parameters can be used as an input parameter of [startContinuationDeviceManager](js-apis-continuation-continuationManager.md#continuationmanagerstartcontinuationdevicemanager9). > **NOTE** > @@ -15,7 +15,7 @@ Describes the extra parameters required by the device selection module in the co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | deviceType | Array\ | Yes| Yes| Device type.| -| targetBundle | string | Yes| Yes| Target bundle name.| +| targetBundle | string | Yes| Yes| Name of the target bundle.| | description | string | Yes| Yes| Device filtering description.| | filter | any | Yes| Yes| Device filtering parameter.| | continuationMode | [ContinuationMode](js-apis-continuation-continuationManager.md#continuationmode) | Yes| Yes| Continuation mode.| diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 48bf6c24db78efa7b41219c879d994223a5d43ce..05f490c454f7e7133bfc5977d1bdc2d180462a7c 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -1,4 +1,4 @@ -# continuationManager +# @ohos.continuation.continuationManager (continuationManager) The **continuationManager** module provides the continuation management entry. You can use the APIs of this module to connect to and cancel the continuation management service, subscribe to and unsubscribe from device connection events, start the device selection module, and update the device connection state. diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md index bdebb727ff7b5c6b41868f37bf5ecdb0ea333d10..d02b0dd61bffff14504bf77ca225c25ce953539e 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md @@ -1,12 +1,11 @@ # ContinuationResult > **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. ## ContinuationResult -Describes the device information returned by the continuation management entry. +Describes the device information returned by the continuation management entry after [on](js-apis-continuation-continuationManager.md#continuationmanagerstartcontinuationdevicemanager9) is called. **System capability**: SystemCapability.Ability.DistributedAbilityManager diff --git a/en/application-dev/reference/apis/js-apis-cooperate.md b/en/application-dev/reference/apis/js-apis-cooperate.md index 3ed0e77078376df038d327d8edb53f3022ebe7d7..d63729a9dcf6a08133dd28f7cdabc6e63f0a4b6e 100644 --- a/en/application-dev/reference/apis/js-apis-cooperate.md +++ b/en/application-dev/reference/apis/js-apis-cooperate.md @@ -1,11 +1,11 @@ -# Screen Hopping +# @ohos.multimodalInput.inputDeviceCooperate (Screen Hopping) -The Screen Hopping module enables two or more networked devices to share the keyboard and mouse for collaborative operations. +The **inputDeviceCooperate** module enables two or more networked devices to share the keyboard and mouse for collaborative operations. > **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 provided by this module are system APIs. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index 30d79a672420f70d0ab3067857e8726ab8a7ba32..4b6210a18736d99c786a2a305dc5ed534445b488 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -1,9 +1,9 @@ -# Crypto Framework +# @ohos.security.cryptoFramework (Crypto Framework) -The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations. +The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. ## Modules to Import @@ -18,20 +18,23 @@ import cryptoFramework from "@ohos.security.cryptoFramework" **System capability**: SystemCapability.Security.CryptoFramework -| Name | Default Value | Description | -| --------------------------------------| -------- | -------------------------| -| INVALID_PARAMS | 401 | Invalid parameters. | -| NOT_SUPPORT | 801 | This operation is not supported. | -| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | -| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | -| ERR_CRYPTO_OPERATION | 17630001 | Crypto operation error. | +| Name | Value | Description | +| ------------------------------------- | -------- | ---------------------------- | +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | Unsupported operation. | +| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | +| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | ## DataBlob + Defines a binary data array. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------| -| data | Uint8Array | Yes | Yes | Data. | + +| Name| Type | Readable| Writable| Description | +| ---- | ---------- | ---- | ---- | ------ | +| data | Uint8Array | Yes | Yes | Data.| + ## cryptoFramework.createMac @@ -53,6 +56,12 @@ Creates a **Mac** instance for message authentication code (MAC) operations. | ---- | --------------------------------------- | | Mac | [Mac](#mac) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -60,6 +69,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var mac; try { + // Set algName based on the algorithm supported. mac = cryptoFramework.createMac("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -70,7 +80,7 @@ try { Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework @@ -88,10 +98,16 @@ Initializes the MAC computation using a symmetric key. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| key | SymKey | Yes | Shared symmetric key. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------ | +| key | SymKey | Yes | Shared symmetric key.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -118,8 +134,6 @@ symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { }); ``` - - ### init init(key : SymKey) : Promise\; @@ -136,10 +150,16 @@ Initializes the MAC computation using a symmetric key. This API uses a promise t **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -149,9 +169,7 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); - } console.error("Mac algName is: " + mac.algName); @@ -175,10 +193,18 @@ Updates the MAC computation data. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -190,7 +216,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -220,16 +245,26 @@ Updates the MAC computation data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + +**Example** + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -237,14 +272,11 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { @@ -260,8 +292,6 @@ promiseConvertKey.then(symKey => { ``` - - ### doFinal doFinal(callback : AsyncCallback\) : void; @@ -270,10 +300,19 @@ Finalizes the MAC computation. This API uses an asynchronous callback to return **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------- | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -284,7 +323,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -323,10 +361,17 @@ Finalizes the MAC computation. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -339,7 +384,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -375,6 +419,12 @@ Obtains the MAC length, in bytes. | ------ | ------------------------- | | number | MAC length obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -387,7 +437,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -405,7 +454,7 @@ promiseConvertKey.then(symKey => { }).then(macOutput => { console.error("[Promise]: HMAC result: " + macOutput.data); let macLen = mac.getMacLength(); - AlertDialog.show({message: "MAC len: " + macLen}); + console.error("MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -431,6 +480,12 @@ Creates an **Md** instance for message digest operations. | ---- | ------------------------------------- | | Md | [Md](#md) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -438,6 +493,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var md; try { + // Set algName based on the algorithm supported. md = cryptoFramework.createMd("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -448,27 +504,34 @@ try { Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm to use.| +| algName | string | Yes | No | Digest algorithm.| ### update update(input : DataBlob, callback : AsyncCallback\) : void; -Updates the message digest data with the message passed in. This API uses an asynchronous callback to return the result. +Updates the message digest data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------ | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -495,20 +558,26 @@ md.update(blob, (err,) => { update(input : DataBlob) : Promise\; -Updates the message digest data with the message passed in. This API uses a promise to return the result. +Updates the message digest data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -539,10 +608,17 @@ Generates a message digest. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -581,10 +657,17 @@ Generates a message digest. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -622,7 +705,13 @@ Obtains the message digest length, in bytes. | Type | Description | | ------ | ------------------------ | -| number | Message digest length obtained. | +| number | Message digest length obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -645,7 +734,7 @@ promiseMdUpdate.then(() => { }).then(mdOutput => { console.error("[Promise]: MD result: " + mdOutput.data); let mdLen = md.getMdLength(); - AlertDialog.show({message: "MD len: " + mdLen}); + console.error("MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -665,6 +754,12 @@ Creates a **Random** instance for generating random numbers and setting seeds. | ------ | --------------------------------------------- | | Random | [Random](#random) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -679,7 +774,7 @@ try { ## Random -Provides APIs for computing random numbers. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). +Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). ### generateRandom @@ -689,10 +784,19 @@ Generates a random number of the given length. This API uses an asynchronous cal **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | **Example** @@ -722,16 +826,25 @@ Generates a random number of the given length. This API uses a promise to return **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | len | number | Yes | Length of the random number to generate.| **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -754,16 +867,21 @@ promiseGenerateRand.then(randData => { ### setSeed -setSeed(seed : DataBlob, callback : AsyncCallback\) : void; +setSeed(seed : DataBlob) : void; Sets a seed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------ | -| seed | DataBlob | Yes | Seed to set. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| seed | DataBlob | Yes | Seed to set.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------- | +| 17620001 | memory error | **Example** @@ -782,94 +900,70 @@ rand.generateRandom(12, (err, randData) => { console.error("[Callback] err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1, data) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); ``` -### setSeed - -setSeed(seed : DataBlob) : Promise\; - -Sets a seed. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.CryptoFramework - -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| seed | DataBlob | Yes | Seed to set.| - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} - -var promiseGenerateRand = rand.generateRandom(12); -promiseGenerateRand.then(randData => { - console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; -}).then(() => { - console.error("[Promise]: setSeed success"); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` - ## ParamsSpec -Defines the parameters for encryption and decryption. For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). You do not need to construct the child class object if the IV is not required. +Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2). **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters.
Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | ----------------------- | +| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC,|CTR,|OFB, |and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| + +> **NOTE** +> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), while a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you must set **algoName** for the parent class **ParamsSpec** to let the algorithm library know the child class object to pass in in **init()**. ## IvParamsSpec -Defines the parameters for the CBC, CTR, OFB, and CFB modes, which require only an IV for each encryption operation. For the symmetric encryption and decryption that use the CBC, CTR, OFB, or CFB mode, you need to construct **IvParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption.
Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB or CFB mode: 8-byte IV | +| Name| Type | Readable| Writable| Description | +| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, |CTR, |OFB, |or CFB mode: 16-byte IV
- 3DES CBC,|OFB, or |CFB mode: 8-byte IV| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## GcmParamsSpec -Defines the parameters for the GCM mode. For the symmetric encryption and decryption that use the GCM mode, you need to construct **GcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes.| -| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes.| -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) for decryption.| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CcmParamsSpec -Defines the parameters for the CCM mode. For the symmetric encryption and decryption that use the CCM mode, you need to construct **CcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | -------- | ---- | ---- | -------------------------------| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | | iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | | aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) for decryption.| +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CryptoMode @@ -877,22 +971,22 @@ Enumerates the cryptographic operations. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Value | Description | -| ------------ | -------- | -------------------------------- | -| ENCRYPT_MODE | 0 | Encryption. | -| DECRYPT_MODE | 1 | Decryption. | +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| ENCRYPT_MODE | 0 | Encryption.| +| DECRYPT_MODE | 1 | Decryption.| ## Key -Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. Keys can be generated by a key generator. +Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -905,48 +999,50 @@ Obtains the key in hexadecimal format. This API returns the result synchronously **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## SymKey -Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). +Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); -console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. +console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. key.clearMem(); encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s. @@ -954,15 +1050,15 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display a ## PubKey -Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Public keys can be generated by an **AsyKeyGenerator**. +Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Public keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| @@ -976,30 +1072,37 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## PriKey -Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Private keys can be generated by an **AsyKeyGenerator**. +Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Private keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -1012,52 +1115,74 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. key.clearMem(); ``` +## KeyPair + +Defines an asymmetric key pair, which includes a public key and a private key.
Asymmetric key pairs can be generated by the **AsyKeyGenerator**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------ | +| priKey | [PriKey](#prikey) | Yes | No | Private key. | +| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | + + ## cryptoFramework.createSymKeyGenerator createSymKeyGenerator(algName : string) : SymKeyGenerator -Creates a **SymKeyGenerator** instance based on the specified algorithm. For details about the supported symmetric key parameters, see "String for Generating a Key" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ----------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String for Generating a Key" in [Key Generation Specifications] (../../security/cryptoFramework-overview.md#key-generation-specifications).| **Return value** -| Type | Description | +| Type | Description | | ----------------------------------- | -------------------------- | -| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.| +| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| **Example** @@ -1068,29 +1193,35 @@ let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); ## SymKeyGenerator -Provides APIs for using the **symKeyGenerator**. Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------ | | algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| ### generateSymKey generateSymKey(callback : AsyncCallback\) : void -Generates a key randomly. This API uses an asynchronous callback to return the result. +Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ------------------- | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | **Example** @@ -1099,11 +1230,11 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); symKeyGenerator.generateSymKey((err, symKey) => { - if (err) { - console.error('Failed to generate symKey'); - return; - } - console.log('Generate symKey success, algName: ' + symKey.algName); + if (err) { + console.error(`Generate symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Generate symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1111,24 +1242,33 @@ symKeyGenerator.generateSymKey((err, symKey) => { generateSymKey() : Promise\ -Generates a key randomly. This API uses a promise to return the result. +Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | + **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = 'AES128'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); -symKeyGenerator.generateSymKey().then((symKey) => { - console.log('Generate symKey success, algName:' + symKey.algName); +symKeyGenerator.generateSymKey() +.then(symKey => { + console.info(`Generate symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Generate symKey failed, ${error.code}, ${error.message}`); }) ``` @@ -1136,16 +1276,22 @@ symKeyGenerator.generateSymKey().then((symKey) => { convertKey(key : DataBlob, callback : AsyncCallback\) : void -Converts a key. This API uses an asynchronous callback to return the result. +Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ---------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert. | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| key | [DataBlob](#datablob) | Yes | Data to convert. | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------- | +| 17620001 | memory error. | **Example** @@ -1164,12 +1310,12 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { - if (err) { - console.error('Failed to convert symKey'); - return; - } - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { + if (err) { + console.error(`Convert symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Convert symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1177,22 +1323,28 @@ symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { convertKey(key : DataBlob) : Promise\ -Converts a key. This API uses a promise to return the result. +Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| key | [DataBlob](#datablob) | Yes | Data to convert.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------- | +| 17620001 | memory error. | + **Example** ```js @@ -1210,14 +1362,18 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial).then((symKey) => { - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob) +.then(symKey => { + console.info(`Convert symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Convert symKey failed, ${error.code}, ${error.message}`); }) ``` ## cryptoFramework.createAsyKeyGenerator createAsyKeyGenerator(algName : string) : AsyKeyGenerator + Creates an **AsyKeyGenerator** instance based on the specified algorithm. **System capability**: SystemCapability.Security.CryptoFramework @@ -1226,12 +1382,12 @@ Creates an **AsyKeyGenerator** instance based on the specified algorithm. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| **Return value** -| Type | Description | -| --------------- | -------------------------- | +| Type | Description | +| --------------- | ---------------------------- | | asyKeyGenerator | **AsyKeyGenerator** instance created.| **Example** @@ -1250,23 +1406,22 @@ Provides APIs for using the **AsKeyGenerator**. Before using any API of the **As **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------------------------| -| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**. | - - +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------------- | +| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| ### generateKeyPair generateKeyPair(callback : AsyncCallback\) : void; + Generates a key pair randomly. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** @@ -1288,14 +1443,15 @@ asyKeyGenerator.generateKeyPair((err, keyPair) => { ### generateKeyPair generateKeyPair() : Promise\ + Generates a key pair randomly. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1315,23 +1471,25 @@ keyGenPromise.then( keyPair => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void -Converts an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------ | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" - +let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. +let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { if (err) { @@ -1345,21 +1503,22 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ -Converts an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1368,6 +1527,8 @@ Converts an asymmetric key. This API uses a promise to return the result. For de import cryptoFramework from "@ohos.security.cryptoFramework" let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. +let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); keyGenPromise.then( keyPair => { console.info("convertKey success."); @@ -1378,28 +1539,32 @@ keyGenPromise.then( keyPair => { **Key Conversion** -- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 and PKCS #8 formats is returned, respectively. The data can be used for cross-application transfer or persistent storage. +- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. - The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -- In **convertKey()**, **pubKey** and **priKey** are optional. Either **pubKey** or **priKey** can be passed in. As a result, the returned **KeyPair** instance contains only the key converted from the data you passed in. +- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. ## cryptoFramework.createCipher createCipher(transformation : string) : Cipher -Creates a [Cipher](#cipher) instance based on the specified algorithm. -For details about the supported algorithms, see "Algorithm String" in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). + +Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | -------- | ------------------------------------------------------------ | -| transformation | string | Yes | Combination of the algorithm name, encryption mode, and padding algorithm of the **Cipher** instance to create. For example, **RSA1024\|PKCS1** or **RSA1024\|PKCS1_OAEP\|SHA256\|SHA256**.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details about, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | + +> **NOTE** +> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. +> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. **Return value** -| Type | Description | -| ------ | ------------------------ | +| Type | Description | +| ----------------- | ------------------------ | | [Cipher](#cipher) | [Cipher](#cipher) instance created.| **Example** @@ -1414,39 +1579,51 @@ try { console.info(`cipher algName: ${cipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); - return; } ``` ## Cipher -Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. For details about the complete encryption and decryption process, see [Encryption and Decryption Operations](../../security/cryptoFramework-guidelines.md#encryption-and-decryption-operations). +Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). + +A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. + +- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation. +- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable | Writable | Description | -| ------- | ------ | -------- | ----------- | ---------------------------- | -| algName | string | Yes | No | Algorithm to use.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm.| ### init init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void -Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. +Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------ | ------- | ------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1454,13 +1631,14 @@ Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { if (err) { - console.error('Failed to init cipher'); - return; + console.error(`Failed to init cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. } - console.log('Init cipher success'); - // Perform subsequent operations such as update. }) ``` @@ -1468,23 +1646,31 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ -Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. +Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
**init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ---------- | ---- | ---------------------- | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption.| -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. | +| Name | Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| **Return value** -| Type | Description | -| ------------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1492,9 +1678,12 @@ Initializes a [cipher](#cipher) instance. This API uses a promise to return the import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { - console.log('Init cipher success'); +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) +.then(() => { + console.info(`Init cipher success`); // Perform subsequent operations such as update. +}, error => { + console.error(`Failed to init cipher, ${error.code}, ${error.message}`); }) ``` @@ -1502,16 +1691,29 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { update(data : DataBlob, callback : AsyncCallback\) : void -Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1531,11 +1733,14 @@ let cipher; // The process of creating a Cipher instance is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; cipher.update(plainText, (err, output) => { // Example of the encryption process. if (err) { - console.error('Failed to update cipher'); - return; + console.error(`Failed to update cipher`); + } else { + console.info(`Update cipher success`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). } - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. }) ``` @@ -1543,21 +1748,34 @@ cipher.update(plainText, (err, output) => { // Example of the encryption p update(data : DataBlob) : Promise\ -Updates the data to encrypt or decrypt by segment. This API uses a promise to return the result. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output. That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to returns the **DataBlob** (containing the encrypted or decrypted data).| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1575,9 +1793,15 @@ function stringToUint8Array(str) { let cipher; // The process of creating a Cipher instance is omitted here. // The init() process is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(data).then((output) => { - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. +cipher.update(plainText) +.then((output) => { + console.info(`Update cipher success.`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). +}, error => { + console.info(`Update cipher failed.`); }) ``` @@ -1585,23 +1809,33 @@ cipher.update(data).then((output) => { doFinal(data : DataBlob, callback : AsyncCallback\) : void -Finalizes the data encryption or decryption operation. This API uses an asynchronous callback to return the result. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. -- For symmetric encryption and decryption in other modes, the output can be either of the following: - (1) **Update()** returns part of the encryption and decryption result, and **doFinal()** returns the remaining encryption and decryption result. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. + +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.
If data is already passed in by [update()](#update-4), **data** can be **null**. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1613,10 +1847,13 @@ let data; // The process of preparing the data to encrypt or decrypt i // The init() and update() processes are omitted here. cipher.doFinal(data, (err, output) => { if (err) { - console.error('Failed to final cipher'); - return; + console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } } - console.log('Final cipher success'); }) ``` @@ -1624,31 +1861,38 @@ cipher.doFinal(data, (err, output) => { doFinal(data : DataBlob) : Promise\ -Finalizes the data encryption or decryption operation. This API uses a promise to return the result. - -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. - -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -- For symmetric encryption and decryption in other modes, the output includes the following: +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. - (1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. If data is already passed in by [update()](#update-4), **data** can be **null**. | +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1658,22 +1902,37 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let cipher; // The process of creating a Cipher instance is omitted here. let data; // The process of preparing the data to encrypt or decrypt is omitted here. // The init() and update() processes are omitted here. -cipher.doFinal(data).then((output) => { - console.log('Final cipher success'); +cipher.doFinal(data) +.then(output => { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } +}, error => { + console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); }) ``` -**Callback example**: +**RSA encryption example (callback)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); rsaGenerator.generateKeyPair(function (err, keyPair) { let pubKey = keyPair.pubKey; cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { - let input = {data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = {data : stringToUint8Array(plainText) }; cipher.doFinal(input, function (err, data) { AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); }); @@ -1681,11 +1940,19 @@ rsaGenerator.generateKeyPair(function (err, keyPair) { }); ``` -**Promise example**: +**RSA encryption example (promise)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); let keyGenPromise = rsaGenerator.generateKeyPair(); @@ -1693,13 +1960,16 @@ keyGenPromise.then(rsaKeyPair => { let pubKey = rsaKeyPair.pubKey; return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. }).then(() => { - let input = { data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = { data : stringToUint8Array(plainText) }; return cipher.doFinal(input); }).then(dataBlob => { console.info("EncryptOutPut is " + dataBlob.data); }); ``` +> **NOTE** +> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). ## cryptoFramework.createSign @@ -1717,9 +1987,9 @@ Creates a **Sign** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Sign | **Sign** instance created.| +| Type| Description | +| ---- | -------------------------------- | +| Sign | **Sign** instance created.| **Example** @@ -1728,46 +1998,58 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") ``` ## Sign -Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. +Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. +The signing mode is determined in **createSign()**, and the key is set by **init()**. +If the data to be signed is short, you can call **sign()** to pass in the data for signing after **init()**. +If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. +If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to use.| ### init init(priKey : PriKey, callback : AsyncCallback\) : void -Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. +Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init -init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ +init(priKey : PriKey) : Promise\ -Initializes a **Sign** instance using a private key. This API uses a promise to return the result. +Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1780,10 +2062,10 @@ Updates the data to be signed. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1797,12 +2079,12 @@ Updates the data to be signed. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### sign @@ -1815,10 +2097,10 @@ Signs the data. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### sign @@ -1832,53 +2114,92 @@ Signs the data. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -rsaGenerator.generateKeyPair(function (err, keyPair) { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - signer.init(priKey, function (err, data) { - signer.update(input1, function (err, data) { - signer.sign(input2, function (err, data) { - SignMessageBlob = data; - console.info("sign output is " + SignMessageBlob.data); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + rsaGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + signer.init(priKey, function (err, data) { + signer.update(input1, function (err, data) { // Add the first segment of the data. + signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. + SignMessageBlob = data; + AlertDialog.show({message : "res" + SignMessageBlob.data}); + }); }); }); }); -}); +} ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let keyGenPromise = rsaGenerator.generateKeyPair(); -keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - return signer.init(priKey); -}).then(() => { - return signer.update(input1); -}).then(() => { - return signer.sign(input2); -}).then(dataBlob => { - SignMessageBlob = dataBlob; - console.info("sign output is " + SignMessageBlob.data); -}); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessagePromise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + return signer.init(priKey); + }).then(() => { + return signer.update(input1); // Add the first segment of the data. + }).then(() => { + return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. + }).then(dataBlob => { + SignMessageBlob = dataBlob; + console.info("sign output is " + SignMessageBlob.data); + AlertDialog.show({message : "output" + SignMessageBlob.data}); + }); +} ``` ## cryptoFramework.createVerify @@ -1897,9 +2218,9 @@ Creates a **Verify** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Verify | **Verify** instance created.| +| Type | Description | +| ------ | ---------------------------------- | +| Verify | **Verify** instance created.| **Example** @@ -1908,11 +2229,27 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); -let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") ``` + ## Verify Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. +The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. +The signature verification mode is determined in **createVerify()**, and key is set by **init()**. +If the data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. +If the data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. +If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to be used for signature verification.| + + ### init @@ -1924,12 +2261,13 @@ Initializes the **Verify** instance using a public key. This API uses an asynchr **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes| Public key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init + init(pubKey : PubKey) : Promise\ Initializes the **Verify** instance using a public key. This API uses a promise to return the result. @@ -1938,14 +2276,14 @@ Initializes the **Verify** instance using a public key. This API uses a promise **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes|Public key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1958,10 +2296,10 @@ Updates the data for signature verification. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1975,12 +2313,12 @@ Updates the data for signature verification. This API uses a promise to return t | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### verify @@ -1993,11 +2331,11 @@ Verifies the signature. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| signatureData | DataBlob | Yes | Signature data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### verify @@ -2009,25 +2347,30 @@ Verifies the signature. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in.| -| signatureData | DataBlob| Yes| Signature data.| +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| ----------------- | ---------------------------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); verifyer.init(globalKeyPair.pubKey, function (err, data) { verifyer.update(input1, function(err, data) { - verifyer.verify(input2, SignMessageBlob, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { console.info("verify result is " + data); }) }); @@ -2035,19 +2378,25 @@ verifyer.init(globalKeyPair.pubKey, function (err, data) { ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. verifyInitPromise.then(() => { return verifyer.update(input1); }).then(() => { - return verifyer.verify(input2, SignMessageBlob); + return verifyer.verify(input2, signMessageBlob); }).then(res => { console.log("Verify result is " + res); }); ``` + ## cryptoFramework.createKeyAgreement createKeyAgreement(algName : string) : KeyAgreement @@ -2058,15 +2407,15 @@ Creates a **KeyAgreement** instance. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------- | +| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| **Return value** -| Type| Description | -| ---- | ------------------------------ | -| KeyAgreement | **KeyAgreement** instance created.| +| Type | Description | +| ------------ | ---------------------------------------- | +| KeyAgreement | **KeyAgreement** instance created.| **Example** @@ -2079,7 +2428,15 @@ let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); ## KeyAgreement -Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. +Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm used for key agreement.| ### generateSecret @@ -2091,13 +2448,14 @@ Generates a shared secret. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret generated. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret.| ### generateSecret + generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\ Generates a shared secret. This API uses a promise to return the result. @@ -2106,21 +2464,23 @@ Generates a shared secret. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| **Return value** -| Type | Description | -| --------------- | ------------ | -| Promise\ | Promise used to return the shared secret generated. | +| Type | Description | +| ------------------ | -------- | +| Promise\ | Promise used to return the shared secret.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { if (err) { @@ -2132,9 +2492,11 @@ keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); keyAgreementPromise.then((secret) => { diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md index 11b95aa03d0135d811ee21f9e672ad1798d23b5c..cf3067e37fd78e9c9d0f3d701b1fdf30cb79c88f 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -1,6 +1,6 @@ -# Interpolation Calculation +# @ohos.curves (Interpolation Calculation) -The **Curves** module provides APIs for interpolation calculation to construct step, cubic Bezier, and spring curve objects. +The **Curves** module provides APIs for interpolation calculation to create step, cubic Bezier, and spring curves. > **NOTE** > @@ -19,7 +19,7 @@ import Curves from '@ohos.curves' initCurve(curve?: Curve): ICurve -Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. +Implements initialization for the interpolation curve, which is used to create an interpolation curve based on the input parameter. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -33,7 +33,7 @@ Implements initialization for the interpolation curve, which is used to create a | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| +| [ICurve](#icurve) | Interpolation curve.| **Example** @@ -49,7 +49,7 @@ Curves.initCurve(Curve.EaseIn) // Create a default ease-in curve, where the inte stepsCurve(count: number, end: boolean): ICurve -Constructs a step curve object. +Creates a step curve. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -64,7 +64,7 @@ Constructs a step curve object. | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| +| [ICurve](#icurve) | Interpolation curve.| **Example** @@ -80,7 +80,7 @@ Curves.stepsCurve(9, true) // Create a step curve. cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve -Constructs a cubic Bezier curve object. The curve values must be between 0 and 1. +Creates a cubic Bezier curve. The curve values must be between 0 and 1. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -96,7 +96,7 @@ Constructs a cubic Bezier curve object. The curve values must be between 0 and 1 | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve) | Curve object.| +| [ICurve](#icurve) | Interpolation curve.| **Example** @@ -112,7 +112,7 @@ Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve -Constructs a spring curve object. +Creates a spring curve. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -120,7 +120,7 @@ Constructs a spring curve object. | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | | velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| -| mass | number | Yes | Mass. Force object of the elastic system, which will have inertia effect on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| | damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| @@ -129,7 +129,7 @@ Constructs a spring curve object. | Type | Description | | ---------------------------------- | ---------------- | -| [ICurve](#icurve)| Curve object.| +| [ICurve](#icurve)| Interpolation curve.| **Example** @@ -140,6 +140,68 @@ Curves.springCurve(100, 1, 228, 30) // Create a spring curve. ``` +## Curves.springMotion9+ + +springMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve + +Creates a spring animation curve. If multiple spring animations are applied to the same attribute of an object, each animation replaces their predecessor and inherits the velocity. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| response | number | No | Duration of one complete oscillation, in seconds.
Default value: **0.55**| +| dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**| +| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.
Default value: **0**| + + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Curve.
Note: The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.springMotion() // Create a spring animation curve with default settings. +Curves.springMotion(0.5) // Create a spring animation curve with the specified response value. +Curves.springMotion (0.5, 0.6) // Create a spring animation curve with the specified response and dampingFraction values. +Curves.springMotion(0.5, 0.6, 0) // Create a spring animation curve with the specified parameter values. +``` + + +## Curves.responsiveSpringMotion9+ + +responsiveSpringMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve + +Creates a responsive spring animation curve. It is a special case of [springMotion](#curvesspringmotion9), with the only difference in the default values. It can be used together with **springMotion**. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| response | number | No | See **response** in **springMotion**. Default value: **0.15**| +| dampingFraction | number | No | See **dampingFraction** in **springMotion**. Default value: **0.86**| +| overlapDuration | number | No | See **overlapDuration** in **springMotion**. Default value: **0.25**| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.responsiveSpringMotion() // Create a responsive spring animation curve with default settings. +``` + + ## ICurve @@ -194,7 +256,7 @@ Implements initialization to create a curve. This API is deprecated since API ve steps(count: number, end: boolean): string -Constructs a step curve object. This API is deprecated since API version 9. You are advised to use [Curves.stepsCurve](#curvesstepscurve9) instead. +Creates a step curve. This API is deprecated since API version 9. You are advised to use [Curves.stepsCurve](#curvesstepscurve9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -211,7 +273,7 @@ Constructs a step curve object. This API is deprecated since API version 9. You cubicBezier(x1: number, y1: number, x2: number, y2: number): string -Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. You are advised to use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. +Creates a cubic Bezier curve. The curve value must range from 0 to 1. This API is deprecated since API version 9. You are advised to use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -229,7 +291,7 @@ Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. spring(velocity: number, mass: number, stiffness: number, damping: number): string -Constructs a spring curve object. This API is deprecated since API version 9. You are advised to use [Curves.springCurve](#curvesspringcurve9) instead. +Creates a spring curve. This API is deprecated since API version 9. You are advised to use [Curves.springCurve](#curvesspringcurve9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -238,7 +300,7 @@ Constructs a spring curve object. This API is deprecated since API version 9. Yo | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ----- | | velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| -| mass | number | Yes | Mass. Force object of the elastic system, which will have inertia effect on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| | damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| @@ -247,6 +309,7 @@ Constructs a spring curve object. This API is deprecated since API version 9. Yo ```ts // xxx.ets import Curves from '@ohos.curves' + @Entry @Component struct ImageComponent { @@ -256,16 +319,16 @@ struct ImageComponent { build() { Column() { Text() - .margin({top:100}) + .margin({ top: 100 }) .width(this.widthSize) .height(this.heightSize) .backgroundColor(Color.Red) - .onClick(()=> { + .onClick(() => { let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); this.widthSize = curve.interpolate(0.5) * this.widthSize; this.heightSize = curve.interpolate(0.5) * this.heightSize; }) - .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)}) + .animation({ duration: 2000, curve: Curves.stepsCurve(9, true) }) }.width("100%").height("100%") } } diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 5fedece20aac3dc30e68020964be1fbca1cefdfa..4cdef60fa628733e5be8cc6df783548b7b5bcd07 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,4 +1,4 @@ -# Data Share Result Set +# @ohos.data.dataShareResultSet (DataShare Result Set) The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 779d30c40263eecd1a8ecf70209a95008aa228dd..f41bea4da45a6f6c0224e126f698d45d274e25dc 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,4 +1,4 @@ -# DataAbilityPredicates +# @ohos.data.dataAbility (DataAbility Predicates) **DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores. @@ -23,16 +23,16 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of a database table.| - | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a database table.| +| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** - | Type| Description| - | -------- | -------- | - | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| +| Type| Description| +| -------- | -------- | +| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -56,16 +56,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -83,16 +83,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -110,9 +110,9 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** @@ -135,9 +135,9 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** @@ -160,9 +160,9 @@ Adds the OR condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** @@ -182,9 +182,9 @@ Adds the AND condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** @@ -204,16 +204,16 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -231,16 +231,16 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -258,16 +258,16 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -285,15 +285,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -311,15 +311,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -337,16 +337,16 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -364,16 +364,16 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -391,17 +391,17 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -419,17 +419,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -447,16 +447,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -474,16 +474,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -501,16 +501,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -528,16 +528,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -555,15 +555,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -581,15 +581,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -607,9 +607,9 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| **Example** @@ -627,15 +627,15 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Maximum number of records.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Maximum number of records.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| **Example** @@ -653,15 +653,15 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| **Example** @@ -680,15 +680,15 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fields | Array<string> | Yes| Names of columns to group.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fields | Array<string> | Yes| Names of columns to group.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| **Example** @@ -706,15 +706,15 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | indexName | string | Yes| Name of the index column.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| indexName | string | Yes| Name of the index column.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| **Example** @@ -732,17 +732,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -760,16 +760,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** 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 a5f16c8c04d650608231c4757224c662c23bf387..82a333b14b2ea90e92540ee31142ea884c7f2593 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,4 +1,4 @@ -# Data Sharing +# @ohos.data.dataShare (DataShare) The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. @@ -17,6 +17,26 @@ The **DataShare** module allows an application to manage its own data and share import dataShare from '@ohos.data.dataShare' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## dataShare.createDataShareHelper @@ -24,6 +44,11 @@ createDataShareHelper(context: Context, uri: string, callback: AsyncCallback< Creates a **DataShareHelper** instance. 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 access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target **DataShareExtension** 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.DistributedDataManager.DataShare.Consumer **Parameters** @@ -34,21 +59,33 @@ Creates a **DataShareHelper** instance. This API uses an asynchronous callback t | 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.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri, (err, data) => { - if (err != undefined) { - console.info("createDataShareHelper failed, error message : " + err); - } else { +try { + dataShare.createDataShareHelper(this.context, uri, (err, data) => { + if (err != undefined) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + return; + } console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; - } -}); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## dataShare.createDataShareHelper @@ -57,6 +94,11 @@ createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper Creates a **DataShareHelper** instance. 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 access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target **DataShareExtension** 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.DistributedDataManager.DataShare.Consumer **Parameters** @@ -72,19 +114,31 @@ Creates a **DataShareHelper** instance. This API uses a promise to return the re | -------------------------------------------------- | -------------------------------------- | | Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri).then((data) => { - console.info("createDataShareHelper succeed, data : " + data); - dataShareHelper = data; -}).catch((err) => { - console.info("createDataShareHelper failed, error message : " + err); -}) +try { + dataShare.createDataShareHelper(this.context, uri).then((data) => { + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; + }). catch((err) => { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## DataShareHelper @@ -101,16 +155,17 @@ Subscribes to changes of the specified data. After an observer is registered, th **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the data is changed, the value of **err** is **undefined**. Otherwise, this callback is not invoked or the value of **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is changed, the value of **err** is undefined. Otherwise, this callback is not invoked or the value of **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function onCallback() { console.info("**** Observer on callback ****"); } @@ -128,7 +183,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| @@ -137,7 +192,8 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function offCallback() { console.info("**** Observer off callback ****"); } @@ -155,29 +211,34 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.
The data index is not returned if the APIs of the database in use, for example, the key-value database (KVDB), do not support the return of indexes.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose", "age": 22, "salary": 200.5, } -dataShareHelper.insert(uri, valueBucket, (err, data) => { - if (err != undefined) { - console.log("insert failed, error message : " + err); - }else{ - console.log("insert succeed, data : " + data); - } -}); +try { + dataShareHelper.insert(uri, valueBucket, (err, data) => { + if (err != undefined) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("insert succeed, data : " + data); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### insert @@ -193,7 +254,7 @@ Inserts a single data record into the database. This API uses a promise to retur | Name | Type | Mandatory| Description | | ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| **Return value** @@ -204,18 +265,23 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose1", "age": 221, "salary": 20.5, } -dataShareHelper.insert(uri, valueBucket).then((data) => { - console.log("insert succeed, data : " + data); -}).catch((err) => { - console.log("insert failed, error message : " + err); -}); +try { + dataShareHelper.insert(uri, valueBucket).then((data) => { + console.log("insert succeed, data : " + data); + }). catch((err) => { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -231,25 +297,29 @@ Deletes one or more data records from the database. This API uses an asynchronou | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.
The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da, (err, data) => { - if (err != undefined) { - console.log("delete failed, error message : " + err); - }else{ - console.log("delete succeed, data : " + data); - } -}); +try { + dataShareHelper.delete(uri, da, (err, data) => { + if (err != undefined) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("delete succeed, data : " + data); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -265,7 +335,7 @@ Deletes one or more data records from the database. This API uses a promise to r | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| **Return value** @@ -276,17 +346,21 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da).then((data) => { - console.log("delete succeed, data : " + data); -}).catch((err) => { - console.log("delete failed, error message : " + err); -}); +try { + dataShareHelper.delete(uri, da).then((data) => { + console.log("delete succeed, data : " + data); + }). catch((err) => { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -302,27 +376,31 @@ Queries data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | | callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns, (err, data) => { - if (err != undefined) { - console.log("query failed, error message : " + err); - }else{ +try { + dataShareHelper.query(uri, da, columns, (err, data) => { + if (err != undefined) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("query succeed, rowCount : " + data.rowCount); - } -}); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -338,7 +416,7 @@ Queries data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | **Return value** @@ -350,18 +428,22 @@ Queries data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns).then((data) => { - console.log("query succeed, rowCount : " + data.rowCount); -}).catch((err) => { - console.log("query failed, error message : " + err); -}); +try { + dataShareHelper.query(uri, da, columns).then((data) => { + console.log("query succeed, rowCount : " + data.rowCount); + }). catch((err) => { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -377,15 +459,15 @@ Updates data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.
The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -396,13 +478,17 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va, (err, data) => { - if (err != undefined) { - console.log("update failed, error message : " + err); - }else{ +try { + dataShareHelper.update(uri, da, va, (err, data) => { + if (err != undefined) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("update succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -418,8 +504,8 @@ Updates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | **Return value** @@ -430,8 +516,8 @@ Updates data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -442,11 +528,15 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va).then((data) => { - console.log("update succeed, data : " + data); -}).catch((err) => { - console.log("update failed, error message : " + err); -}); +try { + dataShareHelper.update(uri, da, va).then((data) => { + console.log("update succeed, data : " + data); + }). catch((err) => { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -462,24 +552,29 @@ Batch inserts data into the database. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.
The number of inserted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs, (err, data) => { - if (err != undefined) { - console.log("batchInsert failed, error message : " + err); - }else{ +try { + dataShareHelper.batchInsert(uri, vbs, (err, data) => { + if (err != undefined) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("batchInsert succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -495,7 +590,7 @@ Batch inserts data into the database. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | **Return value** @@ -506,16 +601,21 @@ Batch inserts data into the database. This API uses a promise to return the resu **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs).then((data) => { - console.log("batchInsert succeed, data : " + data); -}).catch((err) => { - console.log("batchInsert failed, error message : " + err); -}); +try { + dataShareHelper.batchInsert(uri, vbs).then((data) => { + console.log("batchInsert succeed, data : " + data); + }). catch((err) => { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### normalizeUri @@ -536,7 +636,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err != undefined) { @@ -570,7 +671,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri).then((data) => { console.log("normalizeUri = " + data); @@ -597,7 +699,8 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err != undefined) { @@ -631,7 +734,8 @@ Denormalizes a URI. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri).then((data) => { console.log("denormalizeUri = " + data); @@ -650,7 +754,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -658,7 +762,8 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.log("***** notifyChange *****"); @@ -688,7 +793,8 @@ Notifies the registered observer of data changes. This API uses a promise to ret **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 4d2df994d96b7b0986782774e9d531a12750cac7..78d896c54a2f1c1674825ddaff66088634129596 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,4 +1,4 @@ -# Data Share Predicates +# @ohos.data.dataSharePredicates (DataShare Predicates) You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. @@ -35,7 +35,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -65,7 +65,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -439,8 +439,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -470,8 +470,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -501,7 +501,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -531,7 +531,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -561,7 +561,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -591,7 +591,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -790,7 +790,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** @@ -820,7 +820,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** 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 6f24aa3255f0340e0ad8ef248ae25d62092e0774..d3285fa80427790ba723737e20bc5559f0cc85ab 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,8 +1,8 @@ -# Distributed Data Object +# @ohos.data.distributedDataObject (Distributed Data Object) The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. -> **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. @@ -13,32 +13,58 @@ The **distributedDataObject** module provides basic data object management, incl import distributedObject from '@ohos.data.distributedDataObject'; ``` -## distributedDataObject.createDistributedObject - -createDistributedObject(source: object): DistributedObject +## distributedObject.create9+ +create(context: Context, source: object): DistributedObjectV9 Creates a distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | source | object | Yes| Attribute of the distributed data object to create.| + +| 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).| +| source | object | Yes| Attributes of the distributed data object.| **Return value** + | Type| Description| | -------- | -------- | -| [DistributedObject](#distributedobject) | Distributed data object created.| +| [DistributedObjectV9](#distributedobjectv9) | Distributed data object created.| **Example** + +FA model: + ```js +// Import the module. import distributedObject from '@ohos.data.distributedDataObject'; -// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +import featureAbility from '@ohos.ability.featureAbility'; +// Obtain the context. +let context = featureAbility.getContext(); +// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. +let g_object = distributedObject.create(context, {name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); ``` +Stage model: + +```ts +// Import the module. +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 + } +} +// 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 @@ -49,14 +75,16 @@ Creates a random session ID. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Return value** - | Type| Description| - | -------- | -------- | - | string | Session ID created.| + +| Type| Description| +| -------- | -------- | +| string | Session ID created.| **Example** + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var sessionId = distributedObject.genSessionId(); +let sessionId = distributedObject.genSessionId(); ``` ## SaveSuccessResponse9+ @@ -65,11 +93,11 @@ Called when the **Save()** API is successfully called. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -| Name| Type| Description| -| -------- | -------- | -------- | -| sessionId | string | Unique ID for multi-device collaboration.| -| version | number |Version of the distributed data object saved.| -| deviceId | string | ID of the device where the distributed data object is stored. The default value is **local**, which identifies a local device. You can set it as required.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| Unique ID for multi-device collaboration.| +| version | number | Yes| Version of the distributed data object saved.| +| deviceId | string | Yes| ID of the device where the distributed data object is stored. The default value is **local**, which identifies a local device. You can set it as required.| ## RevokeSaveSuccessResponse9+ @@ -77,17 +105,144 @@ Called when the **revokeSave()** API is successfully called. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -| Name| Type| Description| -| -------- | -------- | -------- | -| sessionId | string | Unique ID for multi-device collaboration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| Unique ID for multi-device collaboration.| -## DistributedObject +## DistributedObjectV9 -Represents a distributed data object. +Provides APIs for managing a distributed data object. -### setSessionId +### setSessionId9+ -setSessionId(sessionId?: string): boolean +setSessionId(sessionId: string, callback: AsyncCallback<void>): void + +Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | Yes| ID of a distributed data object on a trusted network.| +| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the session ID is successfully set.| + +**Error codes** + + For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md). + +| ID| Error Message| +| -------- | -------- | +| 15400001 | Failed to create the in-memory database.| + +**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"); +}); +``` + +### setSessionId9+ + +setSessionId(callback: AsyncCallback<void>): void + +Exits all joined sessions. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Asynchronous callback invoked when the distributed data object exits all joined sessions.| + +**Error codes** + + For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md). + +| ID| Error Message| +| -------- | -------- | +| 15400001 | Failed to create the in-memory database.| + +**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"); +}); +// 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."); +}); +``` + +### setSessionId9+ + +setSessionId(sessionId?: string): Promise<void> Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. @@ -97,46 +252,100 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + + For details about the error codes, see [Distributed Data Object Error Codes] (../errorcodes/errorcode-distributed-dataObject.md). + +| ID| Error Message| +| -------- | -------- | +| 15400001 | Failed to create the in-memory database.| **Example** +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +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()); -// Remove g_object from the distributed network. -g_object.setSessionId(""); +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."); + }).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); +}); +``` -### on('change') +### on('change')9+ on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void -Subscribes to the changes of this distributed data object. +Subscribes to data changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** + +FA model: + ```js -import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +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) { @@ -148,81 +357,189 @@ globalThis.changeCallback = (sessionId, changeData) => { g_object.on("change", globalThis.changeCallback); ``` -### 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"}}); +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); +``` + +### off('change')9+ off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void -Unsubscribes from the changes of this distributed data object. +Unsubscribes from the data changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to 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'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +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"); ``` -### on('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"}}); +// Unregister the specified data change callback. +g_object.off("change", globalThis.changeCallback); +// Unregister all data change callbacks. +g_object.off("change"); +``` + +### on('status')9+ on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void -Subscribes to the status change (online or offline) of this distributed data object. +Subscribes to statue changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** + +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; } -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +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); ``` -### off('status') +Stage model: -off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void +```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); +``` +### off('status')9+ + +off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void -Unsubscribes from the status change (online or offline) of this distributed data object. +Unsubscribes from the status change of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unsubscribed from.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| **Example** + +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +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; } -// Unsubscribe from the specified status change callback for the distributed data object. +// Unregister the specified status change callback. g_object.off("status",globalThis.statusCallback); -// Unsubscribe from all status change callbacks for the distributed data object. +// 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; +} +// Unregister the specified status change callback. +g_object.off("status",globalThis.statusCallback); +// Unregister all status change callbacks. g_object.off("status"); ``` @@ -243,18 +560,45 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| - | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| +| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback invoked to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** -```js + +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'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +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", (status, result)=>{ - console.log("save status = " + status); +g_object.save("local", (result) => { console.log("save callback"); console.info("save sessionId: " + result.sessionId); console.info("save version: " + result.version); @@ -279,28 +623,55 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Type| Description| +| -------- | -------- | +| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +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)=>{ +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 sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); +}, () => { console.error("save failed"); }); ``` @@ -317,18 +688,62 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Yes| Callback invoked to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** +FA model: + ```js import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +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.revokeSave((result, data) =>{ +// 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 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); }); ``` @@ -345,20 +760,272 @@ If the object is stored on another device, the data on the local device will be **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Type| Description| +| -------- | -------- | +| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** -```js +FA model: + +```ts import distributedObject from '@ohos.data.distributedDataObject'; -var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false}); +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.revokeSave().then((result)=>{ +// Save data for persistence. +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.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.error("revokeSave failed"); }); ``` + +## distributedObject.createDistributedObject(deprecated) + +createDistributedObject(source: object): DistributedObject + + +Creates a distributed data object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use **distributedObject.create**. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | object | Yes| Attributes of the distributed data object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [DistributedObject](#distributedobjectdeprecated) | Distributed data object created.| + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +// Create a distributed data object, which contains attributes of the string, number, boolean, and object types. +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +``` + +## DistributedObject(deprecated) + +Provides APIs for managing a distributed data object. + +### setSessionId(deprecated) + +setSessionId(sessionId?: string): boolean + +Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setSessionId](#setsessionid9). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});; +// Add g_object to the distributed network. +g_object.setSessionId(distributedObject.genSessionId()); +// Remove g_object from the distributed network. +g_object.setSessionId(""); +``` + +### on('change')(deprecated) + +on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void + +Subscribes to data changes 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 [on('change')](#onchange9). + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback invoked to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); + } +} +g_object.on("change", globalThis.changeCallback); +``` + +### off('change')(deprecated) + +off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void + +Unsubscribes from the data changes 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('change')](#offchange9). + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes. | +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback for data changes. If this parameter is not specified, all data change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +// Unregister the specified data change callback. +g_object.off("change", globalThis.changeCallback); +// Unregister all data change callbacks. +g_object.off("change"); +``` + +### on('status')(deprecated) + +on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void + +Subscribes to status changes 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 [on('status')](#onstatus9). + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback invoked to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); +``` + +### off('status')(deprecated) + +off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void + +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. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object. | +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback for status changes. If this parameter is not specified, all status change callbacks of this distributed data object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the object status, which can be online or offline.| + + +**Example** + +```js +import distributedObject from '@ohos.data.distributedDataObject'; +let g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.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"); +``` 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 cad744cb266c3c5712de9d441fe0a56a1fc4ccbc..5ba79b73ed0370258a87975c1a4ee576816964b4 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,4 +1,4 @@ -# Preferences +# @ohos.data.preferences (Preferences) The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. @@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.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.| @@ -103,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 the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| **Return value** @@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.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.| @@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** @@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.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.| @@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** @@ -497,7 +497,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 87c75a024fb144c72c0942e44b114a7d250a8008..bcebd097f34c1337e5826e866302af9626696a32 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,4 +1,4 @@ -# Relational Database +# @ohos.data.rdb (RDB) The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. @@ -8,15 +8,17 @@ This module provides the following RDB-related functions: - [RdbStore](#rdbstore): provides APIs for managing an RDB store. > **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 no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore](js-apis-data-relationalStore.md). + ## Modules to Import ```js import data_rdb from '@ohos.data.rdb'; ``` - ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void @@ -27,12 +29,12 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| -| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| +| 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).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | **Example** @@ -41,7 +43,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db"} @@ -58,9 +60,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -76,6 +79,7 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { console.log("Got RdbStore successfully.") }) ``` + ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> @@ -86,16 +90,16 @@ Obtains an RDB store. This API uses a promise to return the result. You can set **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes|Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| +| 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).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------------------------ | ------------------------------- | | Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| **Example** @@ -105,7 +109,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db" } @@ -121,9 +125,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -149,11 +154,11 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| -| callback | AsyncCallback<void> | Yes| Callback invoked 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).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -162,7 +167,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { @@ -178,9 +183,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -206,16 +212,16 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| +| 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 RDB store to delete. | **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -224,11 +230,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ +promise.then(() => { console.log("Deleted RdbStore successfully.") }).catch((err) => { console.info("Failed to delete RdbStore, err: " + err) @@ -239,9 +245,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -256,16 +263,70 @@ promise.then(()=>{ }) ``` +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode8+ + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType8+ + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## StoreConfig + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Database file name.| + ## RdbPredicates Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. - ### constructor constructor(name: string) - A constructor used to create an **RdbPredicates** object. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -286,8 +347,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates - -Sets an **RdbPredicates** to specify the remote devices on the network to connect during distributed database synchronization. +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -314,7 +374,6 @@ predicates.inDevices(['12345678abcde']) inAllDevices(): RdbPredicates - Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -336,7 +395,6 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -366,7 +424,6 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -396,7 +453,6 @@ predicates.notEqualTo("NAME", "lisi") beginWrap(): RdbPredicates - Adds a left parenthesis to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1098,7 +1154,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. -Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). +Before using the following APIs, use [executeSql](#executesql8) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). ### insert @@ -1172,7 +1228,7 @@ promise.then((rowId) => { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void @@ -1210,7 +1266,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { console.log("Failed to batch insert data, status = " + status); @@ -1220,7 +1276,7 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> @@ -1263,7 +1319,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); @@ -1299,12 +1355,12 @@ const valueBucket = { } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +rdbStore.update(valueBucket, predicates, function (err, rows) { if (err) { console.info("Failed to update data, err: " + err) return } - console.log("Updated row count: " + ret) + console.log("Updated row count: " + rows) }) ``` @@ -1341,91 +1397,8 @@ const valueBucket = { let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.update(valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) -}).catch((err) => { - console.info("Failed to update data, err: " + err) -}) -``` - -### update9+ -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + ret) -}) -``` - -### update9+ - -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) }).catch((err) => { console.info("Failed to update data, err: " + err) }) @@ -1493,76 +1466,6 @@ promise.then((rows) => { }) ``` -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```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) -}) -``` - -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) -promise.then((rows) => { - console.log("Deleted rows: " + rows) -}).catch((err) => { - console.info("Failed to delete data, err: " + err) -}) -``` - ### query query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void @@ -1629,151 +1532,6 @@ Queries data from the RDB store based on specified conditions. This API uses a p }) ``` -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void - -Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```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) -}) -``` - -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> - -Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```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"]) -promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to query data, err: " + err) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void - -Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**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){ - if (err) { - console.info("Failed to remoteQuery, err: " + err) - return - } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> - -Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**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"]) -promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` - ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void @@ -1836,7 +1594,7 @@ promise.then((resultSet) => { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void @@ -1865,7 +1623,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> @@ -1884,7 +1642,7 @@ Executes an SQL statement that contains specified arguments but returns no value | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -1910,7 +1668,7 @@ Starts the transaction before executing an SQL statement. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1937,7 +1695,7 @@ Commits the executed SQL statements. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1964,7 +1722,7 @@ Rolls back the SQL statements that have been executed. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { try { @@ -1984,122 +1742,6 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -Backs up an RDB store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Failed to back up data, err: ' + err) - return - } - console.info('Backed up data successfully.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -Backs up an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseBackup = rdbStore.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backed up data successfully.') -}).catch((err)=>{ - console.info('Failed to back up data, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Failed to restore data, err: ' + err) - return - } - console.info('Restored data successfully.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -Restores an RDB store from a backup file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseRestore = rdbStore.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restored data successfully.') -}).catch((err)=>{ - console.info('Failed to restore data, err: ' + err) -}) -``` - ### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void @@ -2149,7 +1791,7 @@ Sets distributed tables. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -2306,8 +1948,6 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2315,7 +1955,7 @@ 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.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to register.| | observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| **Example** @@ -2339,8 +1979,6 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2348,7 +1986,7 @@ 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](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to unregister.| | observer | Callback<Array<string>> | Yes| Data change observer registered.| **Example** @@ -2365,60 +2003,3 @@ try { console.log('Failed to unregister observer') } ``` - -## StoreConfig - -Defines the RDB store configuration. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Database file name.| -| encrypt9+ | boolean | No| Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store, and the value **false** means the opposite.| - -## ValueType - -Defines the data types allowed. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Type| Description| -| -------- | -------- | -| number | Number.| -| string | String.| -| boolean | Boolean.| - - -## ValuesBucket - -Defines the types of the key and value in a KV pair. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Key Type| Value Type| -| -------- | -------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | - -## SyncMode8+ - -Defines the database synchronization mode. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |----- | -| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| -| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device.| - -## SubscribeType8+ - -Defines the subscription type. - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |---- | -| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md new file mode 100644 index 0000000000000000000000000000000000000000..4bd0a6e1357314bb04141ced51fe9d72238d6bc9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -0,0 +1,3202 @@ +# @ohos.data.relationalStore (RDB Store) + +The relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. + +The **relationalStore** module provides the following functions: + +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. +- [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store. + +> **NOTE**
+> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import data_rdb from '@ohos.data.relationalStore'; +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void + +Obtains an RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call getRdbStore. +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 + } + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call getRdbStore. +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 + } + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}) +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> + +Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | + +**Return value** + +| Type | Description | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call getRdbStore. +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +promise.then(async (rdbStore) => { + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}).catch((err) => { + console.log("Failed to get RdbStore, err: " + err) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call getRdbStore. +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +promise.then(async (rdbStore) => { + if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) { + console.log("RdbStore status is ON_CREATE") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}).catch((err) => { + console.log("Failed to get RdbStore, err: " + err) +}) +``` + +## data_rdb.deleteRdbStore + +deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void + +Deletes an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call deleteRdbStore. +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call deleteRdbStore. +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") +}) +``` + +## data_rdb.deleteRdbStore + +deleteRdbStore(context: Context, name: string): Promise<void> + +Deletes an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// Call deleteRdbStore. +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Deleted RdbStore successfully.") +}).catch((err) => { + console.info("Failed to delete RdbStore, err: " + err) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call deleteRdbStore. +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Deleted RdbStore successfully.") +}).catch((err) => { + console.info("Failed to delete RdbStore, err: " + err) +}) +``` + +## StoreConfig + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | Yes | Database file name. | +| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. | +| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store;
the value **false** means the opposite.| + +## SecurityLevel + +Enumerates the RDB store security levels. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Value | Description | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | The RDB store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, an RDB store that contains system data such as wallpapers.| +| S2 | 2 | The RDB store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, an RDB store that contains information created by users or call records, such as audio or video clips.| +| S3 | 3 | The RDB store security level is high. If data leakage occurs, major impact will be caused on the database. For example, an RDB store that contains information such as user fitness, health, and location data.| +| S4 | 4 | The RDB store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, an RDB store that contains information such as authentication credentials and financial data.| + +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## ConflictResolution10+ + +Defines the resolution to use when **insert()** and **update()** conflict. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------------- | ---- | ------------------------------------------------------------ | +| ON_CONFLICT_NONE | 0 | No operation is performed.| +| ON_CONFLICT_ROLLBACK | 1 | Abort the SQL statement and roll back the current transaction. | +| ON_CONFLICT_ABORT | 2 | Abort the current SQL statement and revert any changes made by the current SQL statement. However, the changes made by the previous SQL statement in the same transaction are retained and the transaction remains active.| +| ON_CONFLICT_FAIL | 3 | Abort the current SQL statement. The **FAIL** resolution does not revert previous changes made by the failed SQL statement or end the transaction.| +| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| +| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| + +## OpenStatus10+ + +Enumerates the RDB store status. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------- | ---- | --------------------------------------------------- | +| ON_CREATE | 0 | The RDB store is created for the first time. | +| ON_OPEN | 1 | The RDB store is already created. | + +## RdbPredicates + +Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. + +### constructor + +constructor(name: string) + +A constructor used to create an **RdbPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| name | string | Yes | Database table name.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +``` + +### inDevices + +inDevices(devices: Array<string>): RdbPredicates + + +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | -------------------------- | +| devices | Array<string> | Yes | IDs of the remote devices in the same network.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inDevices(['12345678abcde']) +``` + +### inAllDevices + +inAllDevices(): RdbPredicates + + +Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inAllDevices() +``` + +### equalTo + +equalTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") +``` + + +### notEqualTo + +notEqualTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notEqualTo("NAME", "lisi") +``` + + +### beginWrap + +beginWrap(): RdbPredicates + + +Adds a left parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap + +endWrap(): RdbPredicates + +Adds a right parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or + +or(): RdbPredicates + +Adds the OR condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and + +and(): RdbPredicates + +Adds the AND condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains + +contains(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string containing the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.contains("NAME", "os") +``` + +### beginsWith + +beginsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that starts with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.beginsWith("NAME", "os") +``` + +### endsWith + +endsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that ends with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.endsWith("NAME", "se") +``` + +### isNull + +isNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNull("NAME") +``` + +### isNotNull + +isNotNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is not null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNotNull("NAME") +``` + +### like + +like(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that is similar to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.like("NAME", "%os%") +``` + +### glob + +glob(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match the specified string. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.glob("NAME", "?h*g") +``` + +### between + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.between("AGE", 10, 50) +``` + +### notBetween + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notBetween("AGE", 10, 50) +``` + +### greaterThan + +greaterThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThan("AGE", 18) +``` + +### lessThan + +lessThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThan("AGE", 20) +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThanOrEqualTo("AGE", 18) +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThanOrEqualTo("AGE", 20) +``` + +### orderByAsc + +orderByAsc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByAsc("NAME") +``` + +### orderByDesc + +orderByDesc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in descending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByDesc("AGE") +``` + +### distinct + +distinct(): RdbPredicates + +Sets an **RdbPredicates** to filter out duplicate records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").distinct() +``` + +### limitAs + +limitAs(value: number): RdbPredicates + +Sets an **RdbPredicates** to specify the maximum number of records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| value | number | Yes | Maximum number of records.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").limitAs(3) +``` + +### offsetAs + +offsetAs(rowOffset: number): RdbPredicates + +Sets an **RdbPredicates** to specify the start position of the returned result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").offsetAs(3) +``` + +### groupBy + +groupBy(fields: Array<string>): RdbPredicates + +Sets an **RdbPredicates** to group rows that have the same value into summary rows. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | Yes | Names of columns to group.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.groupBy(["AGE", "NAME"]) +``` + +### indexedBy + +indexedBy(field: string): RdbPredicates + +Sets an **RdbPredicates** object to specify the index column. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| field | string | Yes | Name of the index column.| + +**Return value** + + +| Type | Description | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.indexedBy("SALARY_INDEX") +``` + +### in + +in(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.in("AGE", [18, 20]) +``` + +### notIn + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## RdbStore + +Provides methods to manage an RDB store. + +Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). + +### Attributes10+ + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ----------- | ---- | -------------------------------- | +| openStatus10+ | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. | + +### insert + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```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); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```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); +}) +``` + +### insert + +insert(table: string, values: ValuesBucket):Promise<number> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise<number> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```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) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +Batch inserts data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** + +```js +const valueBucket1 = { + "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]) +} +const valueBucket3 = { + "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); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +Batch inserts data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** + +```js +const valueBucket1 = { + "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]) +} +const valueBucket3 = { + "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); +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); +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```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) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```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) +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```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) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise<number> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```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) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +Updates data based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +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) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +Updates data based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### delete + +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**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) +}) +``` + +### delete + +delete(predicates: RdbPredicates):Promise<number> + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete(predicates) +promise.then((rows) => { + console.log("Deleted rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**Example** + +```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) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete("EMPLOYEE", predicates) +promise.then((rows) => { + console.log("Deleted rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` + +### query + +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**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) +}) +``` + +### query + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + + ```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) + ``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```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) +}) +``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```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"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void + +Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| device | string | Yes | Network ID of the remote device. | +| table | string | Yes | Name of the target table. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**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){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> + +Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| device | string | Yes | Network ID of the remote device. | +| table | string | Yes | Name of the target table. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**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"]) +promise.then((resultSet) => { + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + +### querySql + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void + +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**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) +}) +``` + +### querySql + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> + +Queries data using the specified SQL statement. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | Yes | SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let promise = rdbStore.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) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void + +Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ---------------------- | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.info("Failed to execute SQL, err: " + err) + return + } + console.info('Create table done.') +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> + +Executes an SQL statement that contains specified arguments but returns no value. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | Yes | SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promise = rdbStore.executeSql(SQL_CREATE_TABLE) +promise.then(() => { + console.info('Create table done.') +}).catch((err) => { + console.info("Failed to execute SQL, err: " + err) +}) +``` + +### beginTransaction + +beginTransaction():void + +Starts the transaction before executing an SQL statement. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```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() +}) +``` + +### commit + +commit():void + +Commits the executed SQL statements. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```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() +}) +``` + +### rollBack + +rollBack():void + +Rolls back the SQL statements that have been executed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```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() + } +}) +``` + +### backup + +backup(destName:string, callback: AsyncCallback<void>):void + +Backs up an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +rdbStore.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup + +backup(destName:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promiseBackup = rdbStore.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore + +restore(srcName:string, callback: AsyncCallback<void>):void + +Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +rdbStore.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore + +restore(srcName:string): Promise<void> + +Restores an RDB store from a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promiseRestore = rdbStore.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` + +### setDistributedTables + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void + +Sets distributed tables. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| tables | Array<string> | Yes | Names of the distributed tables to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**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.') +}) +``` + +### setDistributedTables + + setDistributedTables(tables: Array<string>): Promise<void> + +Sets distributed tables. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------ | +| tables | Array<string> | Yes | Names of the distributed tables to set.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) +promise.then(() => { + console.info("Set distributed tables successfully.") +}).catch((err) => { + console.info("Failed to set distributed tables, err: " + err) +}) +``` + +### obtainDistributedTableName + +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void + +Obtains the distributed table name for a remote device based on the local table name. This API uses an asynchronous callback to return the result. The distributed table name is required when the RDB store of a remote device is queried. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| device | string | Yes | Remote device. | +| table | string | Yes | Local table name. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** + +```js +rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { + if (err) { + console.info('Failed to obtain DistributedTableName, err: ' + err) + return + } + console.info('Obtained distributed table name successfully, tableName=.' + tableName) +}) +``` + +### obtainDistributedTableName + + obtainDistributedTableName(device: string, table: string): Promise<string> + +Obtains the distributed table name for a remote device based on the local table name. This API uses a promise to return the result. The distributed table name is required when the RDB store of a remote device is queried. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| device | string | Yes | Remote device.| +| table | string | Yes | Local table name.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------- | +| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** + +```js +let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +promise.then((tableName) => { + console.info('Obtained distributed table name successfully, tableName= ' + tableName) +}).catch((err) => { + console.info('Failed to obtain DistributedTableName, err: ' + err) +}) +``` + +### sync + +sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void + +Synchronizes data between devices. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [SyncMode](#syncmode) | Yes | Data synchronization mode. The value can be **push** or **pull**. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**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]) + } +}) +``` + +### sync + + sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> + +Synchronizes data between devices. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------ | +| mode | [SyncMode](#syncmode) | Yes | Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | + +**Return value** + +| Type | Description | +| -------------------------------------------- | ------------------------------------------------------------ | +| Promise<Array<[string, number]>> | Promise used to send the synchronization result.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +let promise = rdbStore.sync(data_rdb.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]) + } +}).catch((err) => { + console.log('Sync failed') +}) +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| 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 | Observer that listens for the data changes in the RDB store. | + +**Example** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Failed to register observer') +} +``` + +### off('dataChange') + +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| 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. | + +**Example** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Failed to unregister observer') +} +``` + +## ResultSet + +Provides APIs to access the result set obtained by querying the RDB store. A result set is a set of results returned after **query()** is called. + +### Usage + +Obtain the **resultSet** object by [RdbStore.query()](#query). + +```js +import dataRdb from '@ohos.data.rdb'; +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +predicates.equalTo("AGE", 18); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); +}); +``` + +### Attributes + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | Yes | Names of all columns in the result set. | +| columnCount | number | Yes | Number of columns in the result set. | +| rowCount | number | Yes | Number of rows in the result set. | +| rowIndex | number | Yes | Index of the current row in the result set. | +| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | +| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | +| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| +| isStarted | boolean | Yes | Whether the cursor has been moved. | +| isClosed | boolean | Yes | Whether the result set is closed. | + +### getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | Yes | Column name.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Column index obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +resultSet.goToFirstRow(); +const id = resultSet.getLong(resultSet.getColumnIndex("ID")); +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### getColumnName + +getColumnName(columnIndex: number): string + +Obtains the column name based on the specified column index. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | Yes | Column index.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Column name obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +const id = resultSet.getColumnName(0); +const name = resultSet.getColumnName(1); +const age = resultSet.getColumnName(2); + ``` + +### goTo + +goTo(offset:number): boolean + +Moves the cursor to the row based on the specified offset. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | Yes | Offset relative to the current position.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise= rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goTo(1); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToRow + +goToRow(position: number): boolean + +Moves to the specified row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| position | number | Yes | Destination position to move to.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.(5); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToFirstRow + +goToFirstRow(): boolean + + +Moves to the first row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToFirstRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToLastRow + +goToLastRow(): boolean + +Moves to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToLastRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToNextRow + +goToNextRow(): boolean + +Moves to the next row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToNextRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToPreviousRow + +goToPreviousRow(): boolean + +Moves to the previous row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToPreviousRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### getBlob + +getBlob(columnIndex: number): Uint8Array + +Obtains the value in the form of a byte array based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------- | -------------------------------- | +| Uint8Array | Value obtained.| + +**Example** + + ```js +const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); + ``` + +### getString + +getString(columnIndex: number): string + +Obtains the value in the form of a string based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | String obtained.| + +**Example** + + ```js +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + ``` + +### getLong + +getLong(columnIndex: number): number + +Obtains the value of the Long type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Value obtained.| + +**Example** + + ```js +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + ``` + +### getDouble + +getDouble(columnIndex: number): number + +Obtains the value of the double type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| number | Value obtained.| + +**Example** + + ```js +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +Checks whether the value in the specified column is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------------------- | +| boolean | Returns **true** if the value is null; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); + ``` + +### close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + + ```js +let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); +let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promiseClose.then((resultSet) => { + resultSet.close(); +}).catch((err) => { + console.log('resultset close failed'); +}); + ``` + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | 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 798ac7bba0926f47e1bc16eb6b672403bc082fa7..8cdecd1134a270075b3d4dd86a7e4e7a07fc7390 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,549 +1,17 @@ -# Result Set +# resultSet A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data. -> **NOTE** +> **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 no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset). -## ResultSetV99+ - -Provides methods to access the result set, which is obtained by querying the RDB store. - -### Usage - -You need to obtain the **resultSetV9** instance by using [RdbStoreV9.query()](js-apis-data-rdb.md#query). - -```js -import dataRdb from '@ohos.data.rdb'; -let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -predicatesV9.equalTo("AGE", 18); -let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSetV9) => { - console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); -}); -``` - -### Attributes9+ - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Type | Mandatory| Description | -| ------------ | ------------------- | ---- | -------------------------------- | -| columnNames | Array<string> | Yes | Names of all columns in the result set. | -| columnCount | number | Yes | Number of columns in the result set. | -| rowCount | number | Yes | Number of rows in the result set. | -| rowIndex | number | Yes | Index of the current row in the result set. | -| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | -| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | -| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| -| isStarted | boolean | Yes | Whether the cursor has been moved. | -| isClosed | boolean | Yes | Whether the result set is closed. | - -### getColumnIndex9+ - -getColumnIndex(columnName: string): number - -Obtains the column index based on the column name. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------------------- | -| columnName | string | Yes | Column name specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Index of the column obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -resultSetV9.goToFirstRow(); -const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### getColumnName9+ - -getColumnName(columnIndex: number): string - -Obtains the column name based on the column index. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------- | -| columnIndex | number | Yes | Column index specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| string | Column name obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const id = resultSetV9.getColumnName(0); -const name = resultSetV9.getColumnName(1); -const age = resultSetV9.getColumnName(2); - ``` - -### goTo9+ - -goTo(offset:number): boolean - -Moves the cursor to the row based on the specified offset. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------- | -| offset | number | Yes | Offset relative to the current position.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoto.then((resultSetV9) => { - resultSetV9.goTo(1); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToRow9+ - -goToRow(position: number): boolean - -Moves the cursor to the specified row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------ | -| position | number | Yes | Position to which the cursor is to be moved.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygotorow.then((resultSetV9) => { - resultSetV9.goToRow(5); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToFirstRow9+ - -goToFirstRow(): boolean - - -Moves the cursor to the first row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoFirst.then((resultSetV9) => { - resultSetV9.goToFirstRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToLastRow9+ - -goToLastRow(): boolean - -Moves the cursor to the last row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoLast.then((resultSetV9) => { - resultSetV9.goToLastRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToNextRow9+ - -goToNextRow(): boolean - -Moves the cursor to the next row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoNext.then((resultSetV9) => { - resultSetV9.goToNextRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToPreviousRow9+ - -goToPreviousRow(): boolean - -Moves the cursor to the previous row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoPrev.then((resultSetV9) => { - resultSetV9.goToPreviousRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### getBlob9+ - -getBlob(columnIndex: number): Uint8Array - -Obtains the value in the specified column in the current row as a byte array. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ---------- | -------------------------------- | -| Uint8Array | Value in the specified column as a byte array.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); - ``` - -### getString9+ - -getString(columnIndex: number): string - -Obtains the value in the specified column in the current row as a string. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| string | Value in the specified column as a string.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); - ``` - -### getLong9+ - -getLong(columnIndex: number): number - -Obtains the value in the specified column in the current row as a Long. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | -------------------------- | -| number | Value in the specified column as a Long.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); - ``` - -### getDouble9+ - -getDouble(columnIndex: number): number - -Obtains the value in the specified column in the current row as a double. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| number | Value in the specified column as a double.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### isColumnNull9+ - -isColumnNull(columnIndex: number): boolean - -Checks whether the value in the specified column of the current row is null. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------------------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); - ``` - -### close9+ - -close(): void - -Closes this result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Example** - - ```js -let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSetV9) => { - resultSetV9.close(); -}).catch((err) => { - console.log('Failed to close the resultset'); -}); - ``` - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -## ResultSet(deprecated) +## ResultSet Provides methods to access the result set, which is obtained by querying the RDB store. -> **NOTE** -> -> This object is supported since API version 7 and deprecated since API version 9. You are advised to use [ResultSetV9](#resultsetv99). - ### Usage You need to obtain a **resultSet** object by using [RdbStore.query()](js-apis-data-rdb.md#query). @@ -559,11 +27,7 @@ promise.then((resultSet) => { }); ``` -### Attributes(deprecated) - -> **NOTE** -> -> This parameter is supported since API version 7 and is deprecated since API version 9. You are advised to use [Attributes](#attributes9). +### Attributes **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -579,29 +43,25 @@ promise.then((resultSet) => { | isStarted | boolean | Yes| Whether the cursor has been moved.| | isClosed | boolean | Yes| Whether the result set is closed.| -### getColumnIndex(deprecated) +### getColumnIndex getColumnIndex(columnName: string): number Obtains the column index based on the column name. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnIndex](#getcolumnindex9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnName | string | Yes| Column name specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnName | string | Yes| Column name specified.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Index of the column obtained.| + | Type| Description| + | -------- | -------- | + | number | Index of the column obtained.| **Example** @@ -613,29 +73,25 @@ Obtains the column index based on the column name. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName(deprecated) +### getColumnName getColumnName(columnIndex: number): string Obtains the column name based on the column index. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnName](#getcolumnname9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Column index specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Column index specified.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Column name obtained.| + | Type| Description| + | -------- | -------- | + | string | Column name obtained.| **Example** @@ -645,29 +101,25 @@ Obtains the column name based on the column index. const age = resultSet.getColumnName(2); ``` -### goTo(deprecated) +### goTo goTo(offset:number): boolean Moves the cursor to the row based on the specified offset. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goTo](#goto9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| offset | number | Yes| Offset relative to the current position.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | offset | number | Yes| Offset relative to the current position.| **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** @@ -682,29 +134,25 @@ Moves the cursor to the row based on the specified offset. }); ``` -### goToRow(deprecated) +### goToRow goToRow(position: number): boolean Moves the cursor to the specified row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToRow](#gotorow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| position | number | Yes| Position to which the cursor is to be moved.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | position | number | Yes| Position to which the cursor is to be moved.| **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** @@ -719,23 +167,19 @@ Moves the cursor to the specified row in the result set. }); ``` -### goToFirstRow(deprecated) +### goToFirstRow goToFirstRow(): boolean Moves the cursor to the first row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToFirstRow](#gotofirstrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **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** @@ -750,23 +194,19 @@ Moves the cursor to the first row of the result set. }); ``` -### goToLastRow(deprecated) +### goToLastRow goToLastRow(): boolean Moves the cursor to the last row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToLastRow](#gotolastrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **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** @@ -781,23 +221,19 @@ Moves the cursor to the last row of the result set. }); ``` -### goToNextRow(deprecated) +### goToNextRow goToNextRow(): boolean Moves the cursor to the next row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToNextRow](#gotonextrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **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** @@ -812,23 +248,19 @@ Moves the cursor to the next row in the result set. }); ``` -### goToPreviousRow(deprecated) +### goToPreviousRow goToPreviousRow(): boolean Moves the cursor to the previous row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToPreviousRow](#gotopreviousrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **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** @@ -843,29 +275,25 @@ Moves the cursor to the previous row in the result set. }); ``` -### getBlob(deprecated) +### getBlob getBlob(columnIndex: number): Uint8Array Obtains the value in the specified column in the current row as a byte array. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getBlob](#getblob9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| Uint8Array | Value in the specified column as a byte array.| + | Type| Description| + | -------- | -------- | + | Uint8Array | Value in the specified column as a byte array.| **Example** @@ -873,29 +301,25 @@ Obtains the value in the specified column in the current row as a byte array. const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString(deprecated) +### getString getString(columnIndex: number): string Obtains the value in the specified column in the current row as a string. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getString](#getstring9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Value in the specified column as a string.| + | Type| Description| + | -------- | -------- | + | string | Value in the specified column as a string.| **Example** @@ -903,29 +327,25 @@ Obtains the value in the specified column in the current row as a string. const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong(deprecated) +### getLong getLong(columnIndex: number): number Obtains the value in the specified column in the current row as a Long. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getLong](#getlong9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a Long.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a Long.| **Example** @@ -933,29 +353,25 @@ Obtains the value in the specified column in the current row as a Long. const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble(deprecated) +### getDouble getDouble(columnIndex: number): number Obtains the value in the specified column in the current row as a double. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDouble](#getdouble9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a double.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a double.| **Example** @@ -963,29 +379,25 @@ Obtains the value in the specified column in the current row as a double. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull(deprecated) +### isColumnNull isColumnNull(columnIndex: number): boolean Checks whether the value in the specified column of the current row is null. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isColumnNull](#iscolumnnull9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value is null; returns **false** otherwise.| **Example** @@ -993,16 +405,12 @@ Checks whether the value in the specified column of the current row is null. const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close(deprecated) +### close close(): void Closes this result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [close](#close9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **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 b724dfabc1fed1e99d98ad5bba715d81d91677b8..63e6decf149d62da32381aefbee2707dab29c632 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -1,6 +1,6 @@ -# Lightweight Storage +# @ohos.data.storage (Lightweight Data Storage) -Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. +The **DataStorage** module provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md index 846f3f15481d700da9d738857bc217c64cbe6ac9..009ff71b091c7d91a92d92364450316e3aeecfa2 100644 --- a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md @@ -1,4 +1,4 @@ -# @ohos.data.ValuesBucket +# @ohos.data.ValuesBucket (Value Bucket) The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. @@ -34,6 +34,6 @@ Defines the types of the key and value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core -| Key Type | Value Type | -| ------------- | --------------------------------------------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | +| Key Type | Value Type | +| ------------- | --------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index dd19bdb98680553ff3f66b3484ab95aa97b5b52d..ad8ab9f54dfd43754e6e00cdfbe5ba5c9e1d39c4 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -297,9 +297,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -308,9 +308,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -318,9 +318,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -365,9 +365,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -377,9 +377,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -424,9 +424,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -436,9 +436,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index e295a1cf9c72875727705c131b4342868daff54a..d227b545aa9f5ad3b719b2da86800cab6ccc5084 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,7 +1,6 @@ # @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: @@ -41,7 +40,7 @@ A constructor used to create a **Deque** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -69,7 +68,7 @@ Inserts an element at the front of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -104,7 +103,7 @@ Inserts an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -145,7 +144,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -172,11 +171,11 @@ Removes the first element of this container. | Type| Description| | -------- | -------- | -| T | Element removed.| +| T | First element removed.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -206,11 +205,11 @@ Removes the last element of this container. | Type| Description| | -------- | -------- | -| T | Element removed.| +| T | Last element removed.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -254,7 +253,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -289,7 +288,7 @@ Obtains the first element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -322,7 +321,7 @@ Obtains the last element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -355,7 +354,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index 46a110814dc474f66393135a91313ab5df03b98e..2827737f79a76c23b04ecc12233774a30f34b39a 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,4 +1,4 @@ -# Device Information +# @ohos.deviceInfo (Device Information) The **deviceInfo** module provides product information. 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 09af96344c7bb7a86a28906d06730e2894296e2b..e8363f6203436eec807f436ca3c63c00cfc3bc74 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,6 +1,6 @@ # @ohos.distributedHardware.deviceManager (Device Management) -The **DeviceManager** module provides APIs for distributed device management. +The **deviceManager** module provides APIs for distributed device management. System applications can call the APIs to do the following: diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 2bc06da295e4bf610281929f32b7a797e46db204..15f5d8bdbc7796954b7c7129f3ab43321bba5555 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,4 +1,5 @@ -# Display +# @ohos.display (Display) + The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. > **NOTE** @@ -188,7 +189,7 @@ Checks whether there is a visible privacy window on a display. The privacy windo | Type | Description | | -------------------------------- |-----------------------------------------------------------------------| -|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| +|boolean | Whether there is a visible privacy window on the display. The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.| **Error codes** @@ -264,7 +265,7 @@ Unsubscribes from display changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event indicating that a display is disconnected.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event that a display is disconnected.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| | callback | Callback<number> | No| Callback used to return the ID of the display.| **Example** @@ -404,6 +405,8 @@ Implements a **Display** instance, with properties and APIs defined. Before calling any API in **Display**, you must use [getAllDisplays()](#displaygetalldisplays9) or [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) to obtain a **Display** instance. +### Attributes + **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name| Type| Readable| Writable| Description| @@ -416,9 +419,9 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg | rotation | number | Yes| No| Screen rotation angle of the display.
The value **0** indicates that the screen of the display rotates by 0°.
The value **1** indicates that the screen of the display rotates by 90°.
The value **2** indicates that the screen of the display rotates by 180°.
The value **3** indicates that the screen of the display rotates by 270°.| | 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, in DPI.| -| densityPixels | number | Yes| No| Screen density of the display, in pixels.| -| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| +| densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. Generally, the value is **160** or **480**.| +| 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.| | yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index 772a7372c276270eaa9a2e2d63d9eec009b06e58..23ee9ed06ec230543ed4ee8594954bc3d72871cf 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -1,4 +1,4 @@ -# Distributed Data Management +# @ohos.data.distributedData (Distributed Data Management) The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. @@ -119,7 +119,7 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | userInfo | [UserInfo](#userinfo) | Yes | User information.| -| bundleName | string | Yes | Bundle name.| +| bundleName | string | Yes | Bundle name of the caller.| ## UserInfo diff --git a/en/application-dev/reference/apis/js-apis-distributedBundle.md b/en/application-dev/reference/apis/js-apis-distributedBundleManager.md similarity index 80% rename from en/application-dev/reference/apis/js-apis-distributedBundle.md rename to en/application-dev/reference/apis/js-apis-distributedBundleManager.md index 2ddd4b91388067d0b301f8d7ba26bbf748eb15cb..71e153396ecfc529530cf2e9fae3869bd398a0fa 100644 --- a/en/application-dev/reference/apis/js-apis-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-distributedBundleManager.md @@ -1,4 +1,4 @@ -# @ohos.bundle.distributedBundle +# @ohos.bundle.distributedBundleManager (distributedBundleManager) The **distributedBundle** module provides APIs for managing distributed bundles. @@ -11,10 +11,10 @@ The **distributedBundle** module provides APIs for managing distributed bundles. ## Modules to Import ``` -import distributedBundle from '@ohos.bundle.distributedBundle'; +import distributedBundle from '@ohos.bundle.distributedBundleManager'; ``` -## System Capability +## System Capabilities SystemCapability.BundleManager.DistributedBundleFramework @@ -43,7 +43,7 @@ Obtains information about the remote ability that matches the given element name | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -64,16 +64,16 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -99,7 +99,7 @@ Obtains information about the remote ability that matches the given element name | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.| +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned.| **Error codes** @@ -120,14 +120,14 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }).then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -135,7 +135,7 @@ try { getRemoteAbilityInfo(elementNames: Array\, callback: AsyncCallback\>): void; -Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. +Obtains information about the remote abilities that match the given element names. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -148,7 +148,7 @@ Obtains information about remote abilities that match the given element names. T | Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -170,22 +170,22 @@ try { { deviceId: '1', bundleName: 'com.example.application1', - abilityName: 'MainAbility1' + abilityName: 'EntryAbility1' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ], (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -193,7 +193,7 @@ try { getRemoteAbilityInfo(elementNames: Array\): Promise\>; -Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result. +Obtains information about the remote abilities that match the given element names. This API uses a promise to return the result. **System API**: This is a system API. @@ -211,7 +211,7 @@ Obtains information about remote abilities that match the given element names an | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.| +| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned.| **Error codes** @@ -233,20 +233,20 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ]).then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -268,7 +268,7 @@ Obtains information about the remote ability that matches the given element name | ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | | locale | string |Yes| Target locale.| -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -289,16 +289,16 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, 'zh-Hans-CN', (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -325,7 +325,7 @@ Obtains information about the remote ability that matches the given element name | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.| +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned.| **Error codes** @@ -346,14 +346,14 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, 'zh-Hans-CN').then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -361,7 +361,7 @@ try { getRemoteAbilityInfo(elementNames: Array\, locale: string, callback: AsyncCallback\>): void; -Obtains information about remote abilities that match the given element names and locales. This API uses an asynchronous callback to return the result. +Obtains information about the remote abilities that match the given element names and locale. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -375,7 +375,7 @@ Obtains information about remote abilities that match the given element names an | ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | | locale | string |Yes| Target locale.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -397,22 +397,22 @@ try { { deviceId: '1', bundleName: 'com.example.application1', - abilityName: 'MainAbility1' + abilityName: 'EntryAbility1' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ], 'zh-Hans-CN', (err, data) => { if (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } else { console.info('Operation succeed:' + JSON.stringify(data)); } }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` @@ -420,7 +420,7 @@ try { getRemoteAbilityInfo(elementNames: Array\, locale: string): Promise\>; -Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result. +Obtains information about the remote abilities that match the given element names and locale. This API uses a promise to return the result. **System API**: This is a system API. @@ -439,7 +439,7 @@ Obtains information about remote abilities that match the given element names an | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.| +| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned.| **Error codes** @@ -461,19 +461,19 @@ try { { deviceId: '1', bundleName: 'com.example.application', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' }, { deviceId: '1', bundleName: 'com.example.application2', - abilityName: 'MainAbility' + abilityName: 'EntryAbility' } ], 'zh-Hans-CN').then(data => { console.info('Operation succeed:' + JSON.stringify(data)); }).catch(err => { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); }); } catch (err) { - console.error('Operation failed:' + JSON.stringify(err)); + console.log(`Operation failed: error code is ${err.code} and error message is ${err.message}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md index 81308054abd5ef5f55ad9d4c78b52f427c16792c..440da83fd42e403b1ddd4d6ad7f20d02b58b5ba4 100644 --- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -1,4 +1,4 @@ -# Distributed KV Store +# @ohos.data.distributedKVStore (Distributed KV Store) The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. @@ -10,7 +10,7 @@ The **distributedKVStore** module provides the following functions: - [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data. The single KV stores manage data without distinguishing devices. - [DeviceKVStore](#devicekvstore): provides APIs for querying in device KV stores and synchronizing data. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. -> **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. @@ -248,79 +248,9 @@ try { ## distributedKVStore.createKVManager -createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void +createKVManager(config: KVManagerConfig): KVManager -Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | -| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name of the invoker and the context of the application.| -| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created. | - -**Example** - -Stage model: - -```js -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - } - try { - 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; - }); - } catch (e) { - console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); - } - } -} -``` - -FA model: - -```js -import featureAbility from '@ohos.ability.featureAbility' -let kvManager; -let context = featureAbility.getContext() -const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', -} -try { - 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; - }); -} catch (e) { - console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); -} -``` - -## distributedKVStore.createKVManager - -createKVManager(config: KVManagerConfig): Promise<KVManager> - -Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. +Creates a **KVManager** instance to manage KV stores. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -328,13 +258,13 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | --------------------------------------------------------- | -| config | [KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name and user information of the caller.| **Return value** | Type | Description | | -------------------------------------- | ------------------------------------------ | -| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| +| [KVManager](#kvmanager) | **KVManager** instance created.| **Example** @@ -352,12 +282,8 @@ export default class MyAbilityStage extends AbilityStage { bundleName: 'com.example.datamanagertest', } try { - distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; - }).catch((err) => { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); - }); + kvManager = distributedKVStore.createKVManager(kvManagerConfig); + console.log("Created KVManager successfully"); } catch (e) { console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); } @@ -376,12 +302,8 @@ const kvManagerConfig = { bundleName: 'com.example.datamanagertest', } try { - distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; - }).catch((err) => { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); - }); + kvManager = distributedKVStore.createKVManager(kvManagerConfig); + console.log("Created KVManager successfully"); } catch (e) { console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); } @@ -617,7 +539,7 @@ Deletes a distributed KV store. This API uses an asynchronous callback to return For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message**| +| ID| **Error Message**| | ------------ | ------------ | | 15100004 | Not found. | @@ -681,7 +603,7 @@ Deletes a distributed KV store. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message**| +| ID| **Error Message**| | ------------ | ------------ | | 15100004 | Not found. | @@ -799,7 +721,7 @@ Subscribes to service status changes. | Name | Type | Mandatory| Description | | ------------- | -------------------- | ---- | ------------------------------------------------------------ | | event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| -| deathCallback | Callback<void> | Yes | Callback invoked to return the result. | +| deathCallback | Callback<void> | Yes | Callback invoked to service status changes. | **Example** @@ -2185,7 +2107,7 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2234,7 +2156,7 @@ Adds a KV pair of the specified type to this KV store. This API uses a promise t For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2275,7 +2197,7 @@ Batch inserts KV pairs to this single KV store. This API uses an asynchronous ca For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2342,7 +2264,7 @@ Batch inserts KV pairs to this single KV store. This API uses a promise to retur For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2395,14 +2317,14 @@ Writes data to this single KV store. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write.| +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2447,7 +2369,7 @@ Write data to this KV store. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write. | +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. | **Return value** @@ -2459,7 +2381,7 @@ Write data to this KV store. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2507,7 +2429,7 @@ Deletes a KV pair from this KV store. This API uses an asynchronous callback to For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2562,7 +2484,7 @@ Deletes a KV pair from this KV store. This API uses a promise to return the resu For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2610,7 +2532,7 @@ Deletes KV pairs from this KV store. This API uses an asynchronous callback to r For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2660,7 +2582,7 @@ Deletes KV pairs from this KV store. This API uses a promise to return the resul For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2709,7 +2631,7 @@ Batch deletes KV pairs from this single KV store. This API uses an asynchronous For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2777,7 +2699,7 @@ Batch deletes KV pairs from this single KV store. This API uses a promise to ret For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -2836,7 +2758,7 @@ Deletes data of a device. This API uses an asynchronous callback to return the r For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -2890,7 +2812,7 @@ Deletes data of a device. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -2941,7 +2863,7 @@ Obtains the value of the specified key. This API uses an asynchronous callback t For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -2997,7 +2919,7 @@ Obtains the value of the specified key. This API uses a promise to return the re For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -3044,7 +2966,7 @@ Obtains all KV pairs that match the specified key prefix. This API uses an async For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3112,7 +3034,7 @@ Obtains all KV pairs that match the specified key prefix. This API uses a promis For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3170,7 +3092,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3237,7 +3159,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses a For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3298,7 +3220,7 @@ Obtains a result set with the specified prefix from this single KV store. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3372,7 +3294,7 @@ Obtains a result set with the specified prefix from this single KV store. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3435,7 +3357,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3503,7 +3425,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3565,7 +3487,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3626,7 +3548,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3745,7 +3667,7 @@ Obtains the number of results that matches the specified **Query** object. This For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3808,7 +3730,7 @@ Obtains the number of results that matches the specified **Query** object. This For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3866,7 +3788,7 @@ Backs up a distributed KV store. This API uses an asynchronous callback to retur For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -3912,7 +3834,7 @@ Backs up an RDB store. This API uses a promise to return the result. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -3951,7 +3873,7 @@ Restores a distributed KV store from a database file. This API uses an asynchron For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -3997,7 +3919,7 @@ Restores a distributed KV store from a database file. This API uses a promise to For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4104,7 +4026,7 @@ Starts the transaction in this single KV store. This API uses an asynchronous ca For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4172,7 +4094,7 @@ Starts the transaction in this single KV store. This API uses a promise to retur For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4214,7 +4136,7 @@ Commits the transaction in this single KV store. This API uses an asynchronous c For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4253,7 +4175,7 @@ Commits the transaction in this single KV store. This API uses a promise to retu For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4290,7 +4212,7 @@ Rolls back the transaction in this single KV store. This API uses an asynchronou For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4329,7 +4251,7 @@ Rolls back the transaction in this single KV store. This API uses a promise to r For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4579,7 +4501,7 @@ Synchronizes the KV store manually. For details about the synchronization modes For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | ------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -4632,7 +4554,7 @@ Synchronizes the KV store manually. This API returns the result synchronously. F For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | ------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -4679,13 +4601,13 @@ Subscribes to data changes of the specified type. | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | | event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| | type | [SubscribeType](#subscribetype) | Yes | Type of data change. | -| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the data change. | **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100001 | Over max subscribe limits. | | 15100005 | Database or result set already closed. | @@ -4716,7 +4638,7 @@ Subscribes to synchronization complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the synchronization result. | +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return the synchronization complete event. | **Example** @@ -4751,13 +4673,13 @@ Unsubscribes from data changes. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | | event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| -| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback invoked to return the result. | +| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback for data changes. | **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4805,7 +4727,7 @@ Unsubscribes from synchronization complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | | event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback | Callback<Array<[string, number]>> | No | Callback used to return the synchronization result. | +| syncCallback | Callback<Array<[string, number]>> | No | Callback for the synchronization complete event. | **Example** @@ -4856,7 +4778,7 @@ Obtains the security level of this KV store. This API uses an asynchronous callb For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID** | **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4895,7 +4817,7 @@ Obtains the security level of this KV store. This API uses a promise to return t For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100005 | Database or result set already closed. | @@ -4943,7 +4865,7 @@ Obtains the value of the specified key for this device. This API uses an asynchr For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -4999,7 +4921,7 @@ Obtains the value of the specified key for this device. This API uses a promise For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -5047,7 +4969,7 @@ Obtains a string value that matches the specified device ID and key. This API us For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -5104,7 +5026,7 @@ Obtains a string value that matches the specified device ID and key. This API us For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100004 | Not found. | @@ -5151,7 +5073,7 @@ Obtains all KV pairs that match the specified key prefix for this device. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5219,7 +5141,7 @@ Obtains all KV pairs that match the specified key prefix for this device. This A For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5278,7 +5200,7 @@ Obtains all KV pairs that match the specified device ID and key prefix. This API For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5347,7 +5269,7 @@ Obtains all KV pairs that match the specified device ID and key prefix. This API For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5402,13 +5324,13 @@ Obtains all KV pairs that match the specified **Query** object for this device. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ----------------------------------------------------- | | query | [Query](query) | Yes | Key prefix to match. | -| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs obtained.| +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| **Error codes** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5475,7 +5397,7 @@ Obtains all KV pairs that match the specified **Query** object for this device. For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5537,7 +5459,7 @@ Obtains the KV pairs that match the specified device ID and **Query** object. Th For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5611,7 +5533,7 @@ Obtains the KV pairs that match the specified device ID and **Query** object. Th For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5673,7 +5595,7 @@ Obtains a result set with the specified prefix for this device. This API uses an For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5747,7 +5669,7 @@ Obtains a result set with the specified prefix for this device. This API uses a For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5811,7 +5733,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5867,7 +5789,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and k For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5914,7 +5836,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -5991,7 +5913,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6064,7 +5986,7 @@ Obtains a **KVStoreResultSet** object that matches the specified **Query** objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6130,7 +6052,7 @@ Obtains a **KVStoreResultSet** object that matches the specified device ID and * For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6200,7 +6122,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6261,7 +6183,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6314,7 +6236,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6376,7 +6298,7 @@ Obtains a **KVStoreResultSet** object that matches the specified predicate objec For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6425,7 +6347,7 @@ Obtains the number of results that match the specified **Query** object for this For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6488,7 +6410,7 @@ Obtains the number of results that match the specified **Query** object for this For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6547,7 +6469,7 @@ Obtains the number of results that matches the specified device ID and **Query** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6616,7 +6538,7 @@ Obtains the number of results that matches the specified device ID and **Query** For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). -| **ID**| **Error Message** | +| ID| **Error Message** | | ------------ | -------------------------------------- | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index aa49db0f38c911850ec73e2fdb00fa98399ff1fc..770689ba93a6a375f7d48a46d49cbe2334bd9bc3 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -1,4 +1,4 @@ -# Distributed Mission Management +# @ohos.distributedMissionManager (Distributed Mission Management) The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device. @@ -372,6 +372,19 @@ Continues a mission on a remote device. This API uses an asynchronous callback t | options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 16300501 | The system ability work abnormally. | +| 16300502 | Failed to get the missionInfo of the specified missionId. | +| 16300503 | The application is not installed on the remote end and installation-free is not supported. | +| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. | +| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. | +| 16300506 | The local continuation task is already in progress. | + **Example** ```ts @@ -381,11 +394,11 @@ Continues a mission on a remote device. This API uses an asynchronous callback t missionId: 1, wantParam: {"key": "value"} }; - function OnContinueDone(resultCode) { - console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + function onContinueDone(resultCode) { + console.log('onContinueDone resultCode: ' + JSON.stringify(resultCode)); }; var options = { - OnContinueDone: OnContinueDone + onContinueDone: onContinueDone }; try { distributedMissionManager.continueMission(parameter, options, (error) => { @@ -422,6 +435,19 @@ Continues a mission on a remote device. This API uses a promise to return the re | ------------------- | ---------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 16300501 | The system ability work abnormally. | +| 16300502 | Failed to get the missionInfo of the specified missionId. | +| 16300503 | The application is not installed on the remote end and installation-free is not supported. | +| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. | +| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. | +| 16300506 | The local continuation task is already in progress. | + **Example** ```ts @@ -431,11 +457,11 @@ Continues a mission on a remote device. This API uses a promise to return the re missionId: 1, wantParam: {"key": "value"} }; - function OnContinueDone(resultCode) { - console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + function onContinueDone(resultCode) { + console.log('onContinueDone resultCode: ' + JSON.stringify(resultCode)); }; var options = { - OnContinueDone: OnContinueDone + onContinueDone: onContinueDone }; try { distributedMissionManager.continueMission(parameter, options) diff --git a/en/application-dev/reference/apis/js-apis-document.md b/en/application-dev/reference/apis/js-apis-document.md index 1ff80d1b41633b2fc1dc351a3c0180baec1d71b6..4b0e41497e37caa1ff6addc5a85885fbe262cb5b 100644 --- a/en/application-dev/reference/apis/js-apis-document.md +++ b/en/application-dev/reference/apis/js-apis-document.md @@ -1,8 +1,9 @@ -# File Interaction +# @ohos.document (File Operation) -> **NOTE**
+> **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 have been deprecated since API version 9 and are not recommended for use. An exception will be thrown if any of the APIs is called. +> - The APIs provided by this module have been deprecated since API version 9 and are not recommended for use. An exception will be thrown if any of the APIs is called. ## Modules to Import @@ -12,7 +13,7 @@ import document from '@ohos.document'; ## document.choose(deprecated) -choose(types? : string[]): Promise<string> +choose(types?: string[]): Promise<string> Chooses files of the specified types using the file manager. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md index d44645af1980b3a963bd73878dc040db60abe205..7826d164b3c3f9cfbcde07dd9989b1fce3021e4b 100644 --- a/en/application-dev/reference/apis/js-apis-effectKit.md +++ b/en/application-dev/reference/apis/js-apis-effectKit.md @@ -1,4 +1,4 @@ -# Image Effect +# @ohos.effectKit (Image Effects) The **EffectKit** module provides basic image processing capabilities, including brightness adjustment, blurring, grayscale adjustment, and color picker. diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index a072663e8c5cf3f667860cd72d1ef50c2bb72334..95b8eb45f0dc91295274ba2ff26087d3268dbce4 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -1,10 +1,12 @@ -# @ohos.events.emitter +# @ohos.events.emitter (Emitter) -The **Emitter** module provides APIs for sending and processing in-process events, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. +The **Emitter** module provides the capabilities of sending and processing inter- or intra-thread events in a process. You can use the APIs of this module to subscribe to an event in persistent or one-shot manner, unsubscribe from an event, or emit an event to the event queue. > **NOTE** > -> The initial APIs of this module are supported since API version 7. +> 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 in the FA model or stage model. ## Modules to Import @@ -20,16 +22,16 @@ None on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)\>): void -Subscribes to an event in persistent manner. This API uses a callback to return the event. +Subscribes to an event in persistent manner and executes a callback after the event is received. **System capability**: SystemCapability.Notification.Emitter **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | --------------------------------------- | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. The **EventPriority** settings do not take effect.| -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------ | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. The [EventPriority](#eventpriority) settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback to execute after the event is received. | **Example** @@ -37,26 +39,28 @@ Subscribes to an event in persistent manner. This API uses a callback to return let innerEvent = { eventId: 1 }; -function EmitterCallback(eventData) { + +// Execute the callback after receiving the event whose eventId is 1. +function emitterCallback() { console.info('callback'); } -emitter.on(innerEvent, EmitterCallback); +emitter.on(innerEvent, emitterCallback); ``` ## emitter.once once(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)\>): void -Subscribes to an event in one-shot manner and unsubscribes from it after the event callback is received. +Subscribes to an event in one-shot manner and unsubscribes from it after the event callback is executed. **System capability**: SystemCapability.Notification.Emitter **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | --------------------------------------- | -| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. The **EventPriority** settings do not take effect.| -| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------------------------ | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. The [EventPriority](#eventpriority) settings do not take effect.| +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback to execute after the event is received. | **Example** @@ -64,10 +68,12 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve let innerEvent = { eventId: 1 }; -function EmitterCallback(eventData) { + +// Execute the callback after receiving the event whose eventId is 1. +function emitterCallback() { console.info('once callback'); }; -emitter.once(innerEvent, EmitterCallback); +emitter.once(innerEvent, emitterCallback); ``` ## emitter.off @@ -92,17 +98,17 @@ emitter.off(1); ## emitter.emit -emit(event: InnerEvent, data?: EventData): void +emit(event: [InnerEvent](#innerevent), data?: [EventData](#eventdata)): void -Emits an event to the event queue. +Emits an event. **System capability**: SystemCapability.Notification.Emitter **Parameters** | Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | -------------- | -| event | [InnerEvent](#innerevent) | Yes | Event to emit. | +| ------ | ------------------------- | ---- | ------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to emit, where [EventPriority](#eventpriority) specifies the emit priority of the event.| | data | [EventData](#eventdata) | No | Data carried by the event.| **Example** @@ -112,11 +118,14 @@ let eventData = { data: { "content": "c", "id": 1, - }}; + } +}; + let innerEvent = { eventId: 1, priority: emitter.EventPriority.HIGH }; + emitter.emit(innerEvent, eventData); ``` @@ -126,23 +135,23 @@ Enumerates the event emit priority levels. **System capability**: SystemCapability.Notification.Emitter -| Name | Value | Description | +| Name | Value | Description | | --------- | ---- | --------------------------------------------------- | -| IMMEDIATE | 0 | The event will be emitted immediately. | -| HIGH | 1 | The event will be emitted before low-priority events. | -| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority.| -| IDLE | 3 | The event will be emitted after all the other events. | +| IMMEDIATE | 0 | The event will be emitted immediately. | +| HIGH | 1 | The event will be emitted before low-priority events. | +| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | +| IDLE | 3 | The event will be emitted after all the other events. | ## InnerEvent -Describes an in-process event. +Describes an event to subscribe to or emit. The **EventPriority** settings do not take effect under event subscription. **System capability**: SystemCapability.Notification.Emitter -| Name | Type | Readable| Writable| Description | -| -------- | ------------------------------- | ---- | ---- | ---------------------------------- | +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------- | ---- | ---- | ------------------------------ | | eventId | number | Yes | Yes | Event ID.| -| priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | +| priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | ## EventData diff --git a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md index 173baa4aabaea2fc2c9846e7fcfc4cc35f47f880..0fd78714ed4bdf8a177fa46a814c16107e05b3ff 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.adminManager +# @ohos.enterprise.adminManager (Enterprise Device Management) The **adminManager** module provides enterprise device management capabilities so that devices have the custom capabilities required in enterprise settings. @@ -48,7 +48,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -100,7 +100,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -157,7 +157,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -324,7 +324,7 @@ Disables a device super administrator application based on the specified bundle For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). -| ID| Error Message | +| ID| Error Message | | ------- | ----------------------------------------------------------------- | | 9200005 | failed to disable the administrator application of the device. | @@ -582,7 +582,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -635,7 +635,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; let enterpriseInfo = { name: "enterprise name", @@ -676,7 +676,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; adminManager.getEnterpriseInfo(wantTemp, (error, result) => { if (error != null) { @@ -723,7 +723,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; adminManager.getEnterpriseInfo(wantTemp).then((result) => { console.log(result.name); diff --git a/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md b/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md index bc28cffaa5844cf46dbf73ffaa198e4b3e89ff7b..009c9ede294f78a6e6ec5f823b52c539ccf53c18 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.dateTimeManager +# @ohos.enterprise.dateTimeManager (System Time Management) The **dateTimeManager** module provides APIs for system time management, which can only be called by device administrator applications. diff --git a/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md b/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md index 4953081a07f6d1df20c441f669ed1b507e488dc1..5442a147c0a45781ccbdeee3ede23b8ac3d3d87c 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-deviceInfo.md @@ -1,4 +1,4 @@ -# @ohos.enterprise.deviceInfo +# @ohos.enterprise.deviceInfo (Device Information Management) The **deviceInfo** module provides APIs for enterprise device information management, including the API for obtaining device serial numbers. These APIs can only be called by device administrator applications. @@ -45,7 +45,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceSerial(wantTemp, (error, result) => { if (error != null) { @@ -94,7 +94,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceSerial(wantTemp).then((result) => { console.log(result); @@ -136,7 +136,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDisplayVersion(wantTemp, (error, result) => { if (error != null) { @@ -185,7 +185,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDisplayVersion(wantTemp).then((result) => { console.log(result); @@ -227,7 +227,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceName(wantTemp, (error, result) => { if (error != null) { @@ -276,7 +276,7 @@ For details about the following error codes, see [Enterprise Device Management E ```js let wantTemp = { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", }; deviceInfo.getDeviceName(wantTemp).then((result) => { console.log(result); diff --git a/en/application-dev/reference/apis/js-apis-environment.md b/en/application-dev/reference/apis/js-apis-environment.md index 3f879c77b9ef5cc9427ff5ac74b5758769ddb70f..aca809efc243720dfdc7b95c4300ea84aee2f5c8 100644 --- a/en/application-dev/reference/apis/js-apis-environment.md +++ b/en/application-dev/reference/apis/js-apis-environment.md @@ -1,4 +1,4 @@ -# Environment +# @ohos.environment (Directory Environment Capability) The **Environment** module provides APIs for obtaining the root directories of the storage and public files. diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index ac903232328a4da80fe021b39266fd0025ca9fcb..dba3fb3f36ce7a0043738ff1c7bce26f22ae4973 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -1,6 +1,7 @@ -# Fault Logger +# @ohos.faultLogger (FaultLogger) -> **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md index 743e17c77f8dd2c4baa48f90de3ff9ac47fedfc0..8c5680f3b5077354af57fd32b0a846177bfcd52c 100644 --- a/en/application-dev/reference/apis/js-apis-fileAccess.md +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,11 +1,11 @@ -# User File Access and Management +# @ohos.data.fileAccess (User File Access and Management) -The **fileAccess** module is a framework for accessing and operating user files based on the extension mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of unified file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. +The **fileAccess** module is a framework for accessing and operating user files based on the Extension ability mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. >**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 and cannot be called by third-party applications. Currently, the APIs can be called only by FilePicker and the file manager app. +>- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **Files**. ## Modules to Import @@ -21,17 +21,13 @@ Obtains information about all wants with **extension** set to **fileAcesss** in **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER - -**Parameters** - -None +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **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,27 +51,27 @@ Synchronously creates a **Helper** object to connect to the specified wants. The **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **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** ```js createFileAccessHelper() { - let fileAccesssHelper = null; - // Obtain want information by using getFileAccessAbilityInfo(). + let fileAccessHelper = null; + / / Obtain wantInfos by using getFileAccessAbilityInfo(). // Create a Helper object to interact with the media library service only. let wantInfos = [ { @@ -84,8 +80,9 @@ Synchronously creates a **Helper** object to connect to the specified wants. The }, ] try { - fileAccesssHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); - if (!fileAccesssHelper) + // This.context is passed by MainAbility. + fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); + if (!fileAccessHelper) console.error("createFileAccessHelper interface returns an undefined object"); } catch (error) { console.error("createFileAccessHelper failed, error " + error); @@ -97,23 +94,23 @@ Synchronously creates a **Helper** object to connect to the specified wants. The createFileAccessHelper(context: Context) : FileAccessHelper -Synchronously creates a **Helper** object that connects to all file management services in the current system. +Synchronously creates a **Helper** object to connect to all file management services in the system. **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **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** @@ -122,6 +119,7 @@ Synchronously creates a **Helper** object that connects to all file management s let fileAccesssHelperAllServer = null; // Create a Helper object to interact with all file management services configured with fileAccess in the system. try { + // This.context is passed by MainAbility. fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context); if (!fileAccesssHelperAllServer) console.error("createFileAccessHelper interface returns an undefined object"); @@ -135,22 +133,18 @@ Synchronously creates a **Helper** object that connects to all file management s getRoots( ) : Promise<RootIterator> -Obtains information about the root nodes for the devices of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which +Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** -| Type| Description| -| --- | -- | -| Promise<RootIterator> | **RootIterator** object obtained.| + | Type| Description| + | --- | -- | + | Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| **Example** @@ -160,7 +154,8 @@ None let rootinfos = []; let isDone = false; try { - rootIterator = await fileAccesssHelper.getRoots(); + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + rootIterator = await fileAccessHelper.getRoots(); if (!rootIterator) { console.error("getRoots interface returns an undefined object"); return; @@ -182,7 +177,7 @@ None listFile(filter?: Filter) : FileIterator -Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the root node of a device. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). +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). **System capability**: SystemCapability.FileManagement.UserFileService @@ -190,28 +185,28 @@ 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** ```js - / / Obtain root information by using getRoots(). + / / Obtain rootInfos by using getRoots(). // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; let rootInfo = rootinfos[0]; let fileInfos = []; let isDone = false; try { let fileIterator = rootInfo.listFile(); - // ListFile that contains the filter implementation. + // listFile contains the filter implementation. // let fileIterator = rootInfo.listFile(filter); if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -233,7 +228,7 @@ Synchronously obtains the **FileIterator** object of the first-level files (file scanFile(filter?: Filter) : FileIterator -Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the root node of a device synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using the [next()](#fileiteratornext). +Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the device root node synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -241,39 +236,39 @@ 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** ```js - / / Obtain root information by using getRoots(). + // Obtain rootInfos by using getRoots(). // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; - let rootInfo = rootinfos[0]; + let rootInfo = rootInfos[0]; let fileInfos = []; let isDone = false; try { - let fileIterator = rootInfo.scanFile(); - // ScanFile that contains the filter implementation - // let fileIterator = rootInfo.scanFile(filter); - if (!fileIterator) { - console.error("scanFile interface returns undefined object"); - return; - } - while (!isDone) { - let result = fileIterator.next(); - console.log("next result = " + JSON.stringify(result)); - isDone = result.done; - if (!isDone) - fileInfos.push(result.value); - } + let fileIterator = rootInfo.scanFile(); + // scanFile contains the filter implementation. + // let fileIterator = rootInfo.scanFile(filter); + if (!fileIterator) { + console.error("scanFile interface returns undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + fileInfos.push(result.value); + } } catch (error) { console.error("scanFile failed, error " + error); } @@ -291,15 +286,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** @@ -311,7 +306,7 @@ Synchronously obtains the **FileIterator** object of the next-level files (file let isDone = false; try { let fileIterator = fileInfoDir.listFile(); - // ListFile that contains the filter implementation. + // listFile contains the filter implementation. // let fileIterator = rootInfo.listFile(filter); if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -341,16 +336,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** @@ -362,7 +357,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit let isDone = false; try { let fileIterator = fileInfoDir.scanFile(); - // ScanFile that contains the filter implementation + // scanFile contains the filter implementation. // let fileIterator = rootInfo.scanFile(filter); if (!fileIterator) { console.error("scanFile interface returns an undefined object"); @@ -370,7 +365,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit } while (!isDone) { let result = fileIterator.next(); - console.error("next result = " + JSON.stringify(result)); + console.log("next result = " + JSON.stringify(result)); isDone = result.done; if (!isDone) subfileInfos.push(result.value); @@ -392,25 +387,28 @@ 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. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| + | 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. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the file created.| +| Promise<string> | Promise used to return the URI of the file created.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; let displayName = "file1" let fileUri = null; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. fileUri = await fileAccessHelper.createFile(sourceUri, displayName) if (!fileUri) { console.error("createFile return undefined object"); @@ -434,25 +432,28 @@ 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 folder to create.| + | displayName | string | Yes| Name of the folder to create.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the folder created.| +| Promise<string> | Promise used to return the URI of the folder created.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; let dirName = "dirTest" let dirUri = null; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. dirUri = await fileAccessHelper.mkDir(sourceUri, dirName) if (!dirUri) { console.error("mkDir return undefined object"); @@ -466,7 +467,7 @@ Creates a folder in a directory. This API uses a promise to return the result. ## FileAccessHelper.openFile -openFile(uri: string, flags: [OPENFLAGS](#openflags)) : Promise<number> +openFile(uri: string, flags: OPENFLAGS) : Promise<number> Opens a file. This API uses a promise to return the result. @@ -476,25 +477,28 @@ 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 | |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** | Type| Description| | --- | -- | -| Promise<number> | Handle of the file opened.| +| Promise<number> | Promise used to return the handle to the file opened.| **Example** ```js - // The URI of a shared disk is used as an example. - let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + // The media library URI is used as an example. + //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let targetUri = "datashare:///media/file/100"; try { - let fd = await fileAccessHelper.openFile(targetUri, OPENFLAGS.READ); - } cache (error) { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ); + } catch (error) { console.error("openFile failed, error " + error); }; ``` @@ -511,9 +515,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 folder to delete.| **Return value** @@ -524,13 +528,16 @@ Deletes a file or folder. This API uses a promise to return the result. **Example** ```js - // The URI of a shared disk is used as an example. - let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + // The media library URI is used as an example. + //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let targetUri = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let code = await fileAccessHelper.delete(targetUri); if (code != 0) console.error("delete failed, code " + code); - } cache (error) { + } catch (error) { console.error("delete failed, error " + error); }; ``` @@ -547,27 +554,30 @@ 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 is moved.| + | 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.| **Return value** | Type| Description| | ----- | ------ | -| Promise<string> | URI of the file or folder in the destination directory.| +| Promise<string> | Promise used to return the URI of the file or folder in the destination directory.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; - let destFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // 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. + // You can use the URI obtained. + let sourceFile = "datashare:///media/file/102"; + let destFile = "datashare:///media/file/101"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let fileUri = await fileAccessHelper.move(sourceFile, destFile); console.log("Operation successful. fileUri: " + JSON.stringify(fileUri)); - } cache (error) { + } catch (error) { console.error("move failed, error " + error); }; ``` @@ -584,26 +594,29 @@ 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 folder to rename.| + | displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the renamed file or folder.| +| Promise<string> | Promise used to return the URI of the renamed file or folder.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceDir = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let DestDir = await fileAccessHelper.rename(sourceDir, "testDir"); console.log("Operation successful. DestDir: " + JSON.stringify(DestDir)); - } cache (error) { + } catch (error) { console.error("rename failed, error " + error); }; ``` @@ -620,9 +633,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 folder.| **Return value** @@ -633,15 +646,18 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Example** ```js - // The URI of a shared disk is used as an example. - let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceDir = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let existJudgment = await fileAccessHelper.access(sourceDir); if (existJudgment) console.log("sourceDir exists"); else console.log("sourceDir does not exist"); - } cache (error) { + } catch (error) { console.error("rename failed, error " + error); }; ``` @@ -656,10 +672,6 @@ Obtains the next-level device root directory. **RootIterator** is an iterator ob **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** | Type| Description| @@ -676,10 +688,6 @@ Obtains the information about the next-level file or folder. **FileIterator** is **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** | Type| Description| @@ -720,7 +728,7 @@ Represents the file or folder attribute information and interface capabilities. | 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| Media resource type of the file or folder.| +| mimeType | string | Yes| No| MIME type of the file or folder.| ## OPENFLAGS diff --git a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md index fce0a93c72553be6306910412404e2fe09bc2290..60dec02915e73066d5263bed0e6f77230478b45f 100644 --- a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md +++ b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md @@ -1,4 +1,4 @@ -# User File Extension Info +# @ohos.fileExtensionInfo (User File Access and Management Attributes) The **fileExtensionInfo** module defines attributes in **RootInfo** and **FileInfo** of the user file access and management module. @@ -37,10 +37,10 @@ Defines the values of **deviceFlags** used in **RootInfo**. **deviceFlags** is u ### Attributes - | Name| Type | Value| Readable| Writable| Description | - | ------ | ------ | ---- | ---- | ---- | -------- | - | SUPPORTS_READ | number | 0b1 | Yes | No | Read support.| - | SUPPORTS_WRITE | number | 0b10 | Yes | No | Write support.| + | Name| Type | Readable| Writable| Description | + | ------ | ------ | ---- | ---- | -------- | + | SUPPORTS_READ | number | Yes | No | The device supports read.| + | SUPPORTS_WRITE | number | Yes | No | This device supports write.| ## fileExtensionInfo.DocumentFlag @@ -50,9 +50,9 @@ Defines the values of **mode** used in **FileInfo**. ### Attributes - | Name| Type | Value| Readable| Writable| Description | - | ------ | ------ | ---- | ---- | ---- | -------- | - | REPRESENTS_FILE | number | 0b1 | Yes | No | File.| - | REPRESENTS_DIR | number | 0b10 | Yes | No | Directory.| - | SUPPORTS_READ | number | 0b100 | Yes | No | Read support.| - | SUPPORTS_WRITE | number | 0b1000 | Yes | No | Write support.| + | Name| Type | Readable| Writable| Description | + | ------ | ------ | ---- | ---- | -------- | + | REPRESENTS_FILE | number | Yes | No | File.| + | REPRESENTS_DIR | number | Yes | No | Directory.| + | SUPPORTS_READ | number | Yes | No | This file is readable.| + | SUPPORTS_WRITE | number | Yes | No | This file is writable.| diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 8a55647849f7b2633a7b69e6fc5ff49f4a20f1e6..c36cd359305b59373a0e6a809ff3dc1ba7ebdfc4 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -1,8 +1,9 @@ -# File Management +# @ohos.fileio (File Management) The **fileio** module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. -> **NOTE**
+> **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. @@ -20,8 +21,9 @@ Before using the APIs provided by this module to perform operations on files or Stage Model ```js -import Ability from '@ohos.application.Ability'; -class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { let context = this.context; let pathDir = context.filesDir; @@ -29,19 +31,20 @@ class MainAbility extends Ability { } ``` - For details about how to obtain the stage model context, see [Stage Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-ability-context.md#abilitycontext). + For details about how to obtain the stage model context, see [AbilityContext](js-apis-ability-context.md#abilitycontext). FA Model ```js import featureAbility from '@ohos.ability.featureAbility'; + let context = featureAbility.getContext(); context.getFilesDir().then((data) => { let pathDir = data; }) ``` - - For details about how to obtain the context of the FA model, see [FA Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-Context.md#context). + + For details about how to obtain the FA model context, see [Contex](js-apis-inner-app-context.md#context). ## fileio.stat @@ -67,10 +70,10 @@ Obtains file information. This API uses a promise to return the result. ```js let filePath = pathDir + "test.txt"; - fileio.stat(filePath).then(function(stat){ - console.info("Got file info:"+ JSON.stringify(stat)); - }).catch(function(err){ - console.info("Failed to get file info. Error:"+ err); + fileio.stat(filePath).then(function (stat) { + console.info("getFileInfo succeed, the size of file is " + stat.size); + }).catch(function (err) { + console.info("getFileInfo failed with error:" + err); }); ``` @@ -152,10 +155,10 @@ Opens a file directory. This API uses a promise to return the result. ```js let dirPath = pathDir + "/testDir"; - fileio.opendir(dirPath).then(function(dir){ - console.info("Directory opened:"+ JSON.stringify(dir)); - }).catch(function(err){ - console.info("Failed to open the directory. Error:"+ err); + fileio.opendir(dirPath).then(function (dir) { + console.info("opendir succeed"); + }).catch(function (err) { + console.info("opendir failed with error:" + err); }); ``` @@ -240,17 +243,17 @@ Checks whether the current process can access a file. This API uses a promise to ```js let filePath = pathDir + "/test.txt"; - fileio.access(filePath).then(function() { + fileio.access(filePath).then(function () { console.info("Access successful"); - }).catch(function(err){ - console.info("Access failed. Error:"+ err); + }).catch(function (err) { + console.info("access failed with error:" + err); }); ``` ## fileio.access -access(path: string, mode: number, callback: AsyncCallback<void>): void +access(path: string, mode?: number, callback: AsyncCallback<void>): void Checks whether the current process can access a file. This API uses an asynchronous callback to return the result. @@ -296,7 +299,7 @@ Synchronously checks whether the current process can access the specified file. try { fileio.accessSync(filePath); } catch(err) { - console.info("accessSync failed with error:"+ err); + console.info("accessSync failed with error:" + err); } ``` @@ -326,10 +329,10 @@ Closes a file. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.close(fd).then(function(){ + fileio.close(fd).then(function () { console.info("File closed"); - }).catch(function(err){ - console.info("Failed to close the file. Error:"+ err); + }).catch(function (err) { + console.info("close file failed with error:" + err); }); ``` @@ -385,7 +388,7 @@ Synchronously closes a file. ## fileio.copyFile -copyFile(src: string | number, dest: string | number, mode?: number): Promise<void> +copyFile(src: string|number, dest: string|number, mode?: number): Promise<void> Copies a file. This API uses a promise to return the result. @@ -395,8 +398,8 @@ Copies a file. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ---- | -------------------------- | ---- | ---------------------------------------- | - | src | string \| number | Yes | Path or file descriptor of the file to copy. | - | dest | string \| number | Yes | Path or file descriptor of the new file. | + | src | string\|number | Yes | Path or file descriptor of the file to copy. | + | dest | string\|number | Yes | Path or file descriptor of the new file. | | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| **Return value** @@ -410,17 +413,17 @@ Copies a file. This API uses a promise to return the result. ```js let srcPath = pathDir + "srcDir/test.txt"; let dstPath = pathDir + "dstDir/test.txt"; - fileio.copyFile(srcPath, dstPath).then(function(){ + fileio.copyFile(srcPath, dstPath).then(function () { console.info("File copied"); - }).catch(function(err){ - console.info("Failed to copy the file. Error:"+ err); + }).catch(function (err) { + console.info("copyFile failed with error:" + err); }); ``` ## fileio.copyFile -copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback<void>): void +copyFile(src: string|number, dest: string|number, mode: number, callback: AsyncCallback<void>): void Copies a file. This API uses an asynchronous callback to return the result. @@ -430,8 +433,8 @@ Copies a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory | Description | | -------- | -------------------------- | ---- | ---------------------------------------- | - | src | string \| number | Yes | Path or file descriptor of the file to copy. | - | dest | string \| number | Yes | Path or file descriptor of the new file. | + | src | string\|number | Yes | Path or file descriptor of the file to copy. | + | dest | string\|number | Yes | Path or file descriptor of the new file. | | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | @@ -448,7 +451,7 @@ Copies a file. This API uses an asynchronous callback to return the result. ## fileio.copyFileSync -copyFileSync(src: string | number, dest: string | number, mode?: number): void +copyFileSync(src: string|number, dest: string|number, mode?: number): void Synchronously copies a file. @@ -458,8 +461,8 @@ Synchronously copies a file. | Name | Type | Mandatory | Description | | ---- | -------------------------- | ---- | ---------------------------------------- | - | src | string \| number | Yes | Path or file descriptor of the file to copy. | - | dest | string \| number | Yes | Path or file descriptor of the new file. | + | src | string\|number | Yes | Path or file descriptor of the file to copy. | + | dest | string\|number | Yes | Path or file descriptor of the new file. | | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| **Example** @@ -496,10 +499,10 @@ Creates a directory. This API uses a promise to return the result. ```js let dirPath = pathDir + '/testDir'; - fileio.mkdir(dirPath).then(function() { + fileio.mkdir(dirPath).then(function () { console.info("Directory created"); - }).catch(function (error){ - console.info("Failed to create the directory. Error:"+ error); + }).catch(function (error) { + console.info("mkdir failed with error:" + error); }); ``` @@ -524,7 +527,7 @@ Creates a directory. This API uses an asynchronous callback to return the result ```js let dirPath = pathDir + '/testDir'; - fileio.mkdir(dirPath, function(err) { + fileio.mkdir(dirPath, function (err) { console.info("Directory created"); }); ``` @@ -579,10 +582,10 @@ Opens a file. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; - fileio.open(filePath, 0o1, 0o0200).then(function(number){ + fileio.open(filePath, 0o1, 0o0200).then(function (number) { console.info("File opened"); - }).catch(function(err){ - console.info("Failed to open the file. Error:"+ err); + }).catch(function (err) { + console.info("open file failed with error:" + err); }); ``` @@ -602,13 +605,13 @@ Opens a file. This API uses an asynchronous callback to return the result. | path | string | Yes | Application sandbox path of the file. | | flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **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.
- **0o200000**: If **path** does not point to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| -| callback | AsyncCallback <void> | Yes | Callback invoked when the file is open asynchronously. | +| callback | AsyncCallback<number> | Yes | Callback invoked when the file is open asynchronously. | **Example** ```js let filePath = pathDir + "/test.txt"; - fileio.open(filePath, 0, function(err, fd) { + fileio.open(filePath, 0, function (err, fd) { // Do something. }); ``` @@ -655,11 +658,7 @@ Synchronously opens a file. ## fileio.read -read(fd: number, buffer: ArrayBuffer, options?: { - offset?: number; - length?: number; - position?: number; -}): Promise<ReadOut> +read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }): Promise<ReadOut> Reads data from a file. This API uses a promise to return the result. @@ -685,22 +684,18 @@ Reads data from a file. This API uses a promise to return the result. let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); - fileio.read(fd, buf).then(function(readOut){ + fileio.read(fd, buf).then(function (readOut) { console.info("Read file data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - }).catch(function(err){ - console.info("Failed to read file data. Error:"+ err); + }).catch(function (err) { + console.info("read file data failed with error:" + err); }); ``` ## fileio.read -read(fd: number, buffer: ArrayBuffer, options: { - offset?: number; - length?: number; - position?: number; -}, callback: AsyncCallback<ReadOut>): void +read(fd: number, buffer: ArrayBuffer, options: { offset?: number; length?: number; position?: number; }, callback: AsyncCallback<ReadOut>): void Reads data from a file. This API uses an asynchronous callback to return the result. @@ -732,11 +727,7 @@ Reads data from a file. This API uses an asynchronous callback to return the res ## fileio.readSync -readSync(fd: number, buffer: ArrayBuffer, options?: { - offset?: number; - length?: number; - position?: number; -}): number +readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }): number Synchronously reads data from a file. @@ -790,10 +781,10 @@ Deletes a directory. This API uses a promise to return the result. ```js let dirPath = pathDir + '/testDir'; - fileio.rmdir(dirPath).then(function() { + fileio.rmdir(dirPath).then(function () { console.info("Directory deleted"); - }).catch(function(err){ - console.info("Failed to delete the directory. Error:"+ err); + }).catch(function (err) { + console.info("rmdir failed with error:" + err); }); ``` @@ -817,7 +808,7 @@ Deletes a directory. This API uses an asynchronous callback to return the result ```js let dirPath = pathDir + '/testDir'; - fileio.rmdir(dirPath, function(err){ + fileio.rmdir(dirPath, function (err) { // Do something. console.info("Directory deleted"); }); @@ -870,10 +861,10 @@ Deletes a file. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; - fileio.unlink(filePath).then(function(){ + fileio.unlink(filePath).then(function () { console.info("File deleted"); - }).catch(function(error){ - console.info("Failed to delete the file. Error:"+ error); + }).catch(function (error) { + console.info("remove file failed with error:" + error); }); ``` @@ -897,7 +888,7 @@ Deletes a file. This API uses an asynchronous callback to return the result. ```js let filePath = pathDir + "/test.txt"; - fileio.unlink(filePath, function(err) { + fileio.unlink(filePath, function (err) { console.info("File deleted"); }); ``` @@ -927,12 +918,7 @@ Synchronously deletes a file. ## fileio.write -write(fd: number, buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}): Promise<number> +write(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): Promise<number> Writes data into a file. This API uses a promise to return the result. @@ -943,7 +929,7 @@ Writes data into a file. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to write. | - | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| **Return value** @@ -957,22 +943,17 @@ Writes data into a file. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); - fileio.write(fd, "hello, world").then(function(number){ - console.info("Data written to the file. Size is:"+ number); - }).catch(function(err){ - console.info("Failed to write data to the file. Error:"+ err); + fileio.write(fd, "hello, world").then(function (number) { + console.info("write data to file succeed and size is:" + number); + }).catch(function (err) { + console.info("write data to file failed with error:" + err); }); ``` ## fileio.write -write(fd: number, buffer: ArrayBuffer | string, options: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}, callback: AsyncCallback<number>): void +write(fd: number, buffer: ArrayBuffer|string, options: { offset?: number; length?: number; position?: number; encoding?: string; }, callback: AsyncCallback<number>): void Writes data into a file. This API uses an asynchronous callback to return the result. @@ -983,7 +964,7 @@ Writes data into a file. This API uses an asynchronous callback to return the re | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to write. | - | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | @@ -994,7 +975,7 @@ Writes data into a file. This API uses an asynchronous callback to return the re let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { - console.info("Data written to the file. Size is:"+ bytesWritten); + console.info("write data to file succeed and size is:" + bytesWritten); } }); ``` @@ -1002,12 +983,7 @@ Writes data into a file. This API uses an asynchronous callback to return the re ## fileio.writeSync -writeSync(fd: number, buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}): number +writeSync(fd: number, buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): number Synchronously writes data into a file. @@ -1018,7 +994,7 @@ Synchronously writes data into a file. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to write. | - | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| **Return value** @@ -1061,10 +1037,10 @@ Calculates the hash value of a file. This API uses a promise to return the resul ```js let filePath = pathDir + "/test.txt"; - fileio.hash(filePath, "sha256").then(function(str){ - console.info("Calculated file hash:"+ str); - }).catch(function(err){ - console.info("Failed to calculate the file hash. Error:"+ err); + fileio.hash(filePath, "sha256").then(function (str) { + console.info("calculate file hash succeed:" + str); + }).catch(function (err) { + console.info("calculate file hash failed with error:" + err); }); ``` @@ -1089,9 +1065,9 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r ```js let filePath = pathDir + "/test.txt"; - fileio.hash(filePath, "sha256", function(err, hashStr) { + fileio.hash(filePath, "sha256", function (err, hashStr) { if (hashStr) { - console.info("Calculated file hash:"+ hashStr); + console.info("calculate file hash succeed:" + hashStr); } }); ``` @@ -1122,10 +1098,10 @@ Changes file permissions. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; - fileio.chmod(filePath, 0o700).then(function() { + fileio.chmod(filePath, 0o700).then(function () { console.info("File permissions changed"); - }).catch(function(err){ - console.info("Failed to change file permissions. Error:"+ err); + }).catch(function (err) { + console.info("chmod failed with error:" + err); }); ``` @@ -1191,7 +1167,7 @@ Obtains file information based on the file descriptor. This API uses a promise t | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the target file.| + | fd | number | Yes | Descriptor of the target file.| **Return value** @@ -1204,10 +1180,10 @@ Obtains file information based on the file descriptor. This API uses a promise t ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.fstat(fd).then(function(stat){ - console.info("Obtained file info:"+ JSON.stringify(stat)); - }).catch(function(err){ - console.info("Failed to obtain file info. Error:"+ err); + fileio.fstat(fd).then(function (stat) { + console.info("fstat succeed, the size of file is " + stat.size); + }).catch(function (err) { + console.info("fstat failed with error:" + err); }); ``` @@ -1293,17 +1269,17 @@ Truncates a file based on the file descriptor. This API uses a promise to return ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.ftruncate(fd, 5).then(function(err) { + fileio.ftruncate(fd, 5).then(function (err) { console.info("File truncated"); - }).catch(function(err){ - console.info("Failed to truncate the file. Error:"+ err); + }).catch(function (err) { + console.info("truncate file failed with error:" + err); }); ``` ## fileio.ftruncate7+ -ftruncate(fd: number, len: number, callback: AsyncCallback<void>): void +ftruncate(fd: number, len?: number, callback: AsyncCallback<void>): void Truncates a file based on the file descriptor. This API uses an asynchronous callback to return the result. @@ -1323,7 +1299,7 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); let len = 5; - fileio.ftruncate(fd, 5, function(err){ + fileio.ftruncate(fd, 5, function (err) { // Do something. }); ``` @@ -1366,7 +1342,7 @@ Truncates a file based on the file path. This API uses a promise to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to truncate.| +| path | string | Yes | Application sandbox path of the file to truncate. | | len | number | No | File length, in bytes, after truncation.| **Return value** @@ -1380,17 +1356,17 @@ Truncates a file based on the file path. This API uses a promise to return the r ```js let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncate(filePath, len).then(function(){ + fileio.truncate(filePath, len).then(function () { console.info("File truncated"); - }).catch(function(err){ - console.info("Failed to truncate the file. Error:"+ err); + }).catch(function (err) { + console.info("truncate file failed with error:" + err); }); ``` ## fileio.truncate7+ -truncate(path: string, len: number, callback: AsyncCallback<void>): void +truncate(path: string, len?: number, callback: AsyncCallback<void>): void Truncates a file based on the file path. This API uses an asynchronous callback to return the result. @@ -1409,7 +1385,7 @@ Truncates a file based on the file path. This API uses an asynchronous callback ```js let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncate(filePath, len, function(err){ + fileio.truncate(filePath, len, function (err) { // Do something. }); ``` @@ -1441,11 +1417,7 @@ Synchronously truncates a file based on the file path. ## fileio.readText7+ -readText(filePath: string, options?: { - position?: number; - length?: number; - encoding?: string; -}): Promise<string> +readText(filePath: string, options?: { position?: number; length?: number; encoding?: string; }): Promise<string> Reads the text content of a file. This API uses a promise to return the result. @@ -1468,21 +1440,17 @@ Reads the text content of a file. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; - fileio.readText(filePath).then(function(str) { - console.info("Read text successfully:"+ str); - }).catch(function(err){ - console.info("Failed to read the text. Error:"+ err); + fileio.readText(filePath).then(function (str) { + console.info("readText succeed:" + str); + }).catch(function (err) { + console.info("readText failed with error:" + err); }); ``` ## fileio.readText7+ -readText(filePath: string, options: { - position?: number; - length?: number; - encoding?: string; -}, callback: AsyncCallback<string>): void +readText(filePath: string, options: { position?: number; length?: number; encoding?: string; }, callback: AsyncCallback<string>): void Reads the text content of a file. This API uses an asynchronous callback to return the result. @@ -1500,7 +1468,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu ```js let filePath = pathDir + "/test.txt"; - fileio.readText(filePath, { position: 1, encoding: 'UTF-8' }, function(err, str){ + fileio.readText(filePath, { position: 1, encoding: 'UTF-8' }, function (err, str) { // Do something. }); ``` @@ -1508,11 +1476,7 @@ Reads the text content of a file. This API uses an asynchronous callback to retu ## fileio.readTextSync7+ -readTextSync(filePath: string, options?: { - position?: number; - length?: number; - encoding?: string; -}): string +readTextSync(filePath: string, options?: { position?: number; length?: number; encoding?: string; }): string Synchronously reads the text of a file. @@ -1563,10 +1527,10 @@ Obtains link information. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; - fileio.lstat(filePath).then(function(stat){ - console.info("Get link info:"+ JSON.stringify(stat)); - }).catch(function(err){ - console.info("Failed to obtain link info. Error:"+ err); + fileio.lstat(filePath).then(function (stat) { + console.info("get link status succeed, the size of file is" + stat.size); + }).catch(function (err) { + console.info("get link status failed with error:" + err); }); ``` @@ -1637,7 +1601,7 @@ Renames a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| -| newPath | String | Yes | Application sandbox path of the file renamed. | +| newPath | string | Yes | Application sandbox path of the file renamed. | **Return value** @@ -1650,10 +1614,10 @@ Renames a file. This API uses a promise to return the result. ```js let srcFile = pathDir + "/test.txt"; let dstFile = pathDir + '/new.txt'; - fileio.rename(srcFile, dstFile).then(function() { + fileio.rename(srcFile, dstFile).then(function () { console.info("File renamed"); - }).catch(function(err){ - console.info("Failed to rename the file. Error:"+ err); + }).catch(function (err) { + console.info("rename failed with error:" + err); }); ``` @@ -1671,15 +1635,15 @@ Renames a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| -| newPath | String | Yes | Application sandbox path of the file renamed. | -| Callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | +| newPath | string | Yes | Application sandbox path of the file renamed. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | **Example** ```js let srcFile = pathDir + "/test.txt"; let dstFile = pathDir + '/new.txt'; - fileio.rename(srcFile, dstFile, function(err){ + fileio.rename(srcFile, dstFile, function (err) { }); ``` @@ -1697,7 +1661,7 @@ Synchronously renames a file. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| -| newPath | String | Yes | Application sandbox path of the file renamed. | +| newPath | string | Yes | Application sandbox path of the file renamed. | **Example** @@ -1733,10 +1697,10 @@ Flushes data of a file to disk. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.fsync(fd).then(function(){ + fileio.fsync(fd).then(function () { console.info("Data flushed"); - }).catch(function(err){ - console.info("Failed to flush data. Error:"+ err); + }).catch(function (err) { + console.info("sync data failed with error:" + err); }); ``` @@ -1761,7 +1725,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.fsync(fd, function(err){ + fileio.fsync(fd, function (err) { // Do something. }); ``` @@ -1815,10 +1779,10 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.fdatasync(fd).then(function(err) { + fileio.fdatasync(fd).then(function (err) { console.info("Data flushed"); - }).catch(function(err){ - console.info("Failed to flush data. Error:"+ err); + }).catch(function (err) { + console.info("sync data failed with error:" + err); }); ``` @@ -1836,7 +1800,7 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ----------------- | | fd | number | Yes | File descriptor of the file to synchronize. | - | callback | AsyncCallback <void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| **Example** @@ -1898,10 +1862,10 @@ Creates a symbolic link based on the file path. This API uses a promise to retur ```js let srcFile = pathDir + "/test.txt"; let dstFile = pathDir + '/test'; - fileio.symlink(srcFile, dstFile).then(function() { + fileio.symlink(srcFile, dstFile).then(function () { console.info("Symbolic link created"); - }).catch(function(err){ - console.info("Failed to create the symbolic link. Error:"+ err); + }).catch(function (err) { + console.info("symlink failed with error:" + err); }); ``` @@ -1984,10 +1948,10 @@ Changes the file owner based on the file path. This API uses a promise to return ```js let filePath = pathDir + "/test.txt"; let stat = fileio.statSync(filePath); - fileio.chown(filePath, stat.uid, stat.gid).then(function(){ + fileio.chown(filePath, stat.uid, stat.gid).then(function () { console.info("File owner changed"); - }).catch(function(err){ - console.info("Failed to change the file owner. Error:"+ err); + }).catch(function (err) { + console.info("chown failed with error:" + err); }); ``` @@ -2014,7 +1978,7 @@ Changes the file owner based on the file path. This API uses an asynchronous cal ```js let filePath = pathDir + "/test.txt"; let stat = fileio.statSync(filePath) - fileio.chown(filePath, stat.uid, stat.gid, function (err){ + fileio.chown(filePath, stat.uid, stat.gid, function (err) { // Do something. }); ``` @@ -2068,10 +2032,10 @@ Creates a temporary directory. This API uses a promise to return the result. **Example** ```js - fileio.mkdtemp(pathDir + "/XXXXXX").then(function(pathDir){ - console.info("mkdtemp succeed:"+ pathDir); - }).catch(function(err){ - console.info("Failed to create the temporary directory. Error:"+ err); + fileio.mkdtemp(pathDir + "/XXXXXX").then(function (pathDir) { + console.info("mkdtemp succeed:" + pathDir); + }).catch(function (err) { + console.info("mkdtemp failed with error:" + err); }); ``` @@ -2154,10 +2118,10 @@ Changes file permissions based on the file descriptor. This API uses a promise t let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); let mode = 0o700; - fileio.fchmod(fd, mode).then(function() { + fileio.fchmod(fd, mode).then(function () { console.info("File permissions changed"); - }).catch(function(err){ - console.info("Failed to change file permissions. Error:"+ err); + }).catch(function (err) { + console.info("chmod failed with error:" + err); }); ``` @@ -2176,7 +2140,7 @@ Changes file permissions based on the file descriptor. This API uses an asynchro | -------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback <void> | Yes | Callback invoked when the file permissions are changed asynchronously. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | **Example** @@ -2240,10 +2204,10 @@ Opens a file stream based on the file path. This API uses a promise to return th ```js let filePath = pathDir + "/test.txt"; - fileio.createStream(filePath, "r+").then(function(stream){ + fileio.createStream(filePath, "r+").then(function (stream) { console.info("Stream created"); - }).catch(function(err){ - console.info("Failed to create the stream. Error:"+ err); + }).catch(function (err) { + console.info("createStream failed with error:" + err); }); ``` @@ -2268,7 +2232,7 @@ Opens a file stream based on the file path. This API uses an asynchronous callba ```js let filePath = pathDir + "/test.txt"; - fileio.createStream(filePath, "r+", function(err, stream){ + fileio.createStream(filePath, "r+", function (err, stream) { // Do something. }); ``` @@ -2329,10 +2293,10 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret ```js let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); - fileio.fdopenStream(fd, "r+").then(function(stream){ + fileio.fdopenStream(fd, "r+").then(function (stream) { console.info("Stream opened"); - }).catch(function(err){ - console.info("Failed to open the stream. Error:"+ err); + }).catch(function (err) { + console.info("openStream failed with error:" + err); }); ``` @@ -2351,7 +2315,7 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - | callback | AsyncCallback <[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | + | callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | **Example** @@ -2422,10 +2386,10 @@ Changes the file owner based on the file descriptor. This API uses a promise to let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); let stat = fileio.statSync(filePath); - fileio.fchown(fd, stat.uid, stat.gid).then(function() { + fileio.fchown(fd, stat.uid, stat.gid).then(function () { console.info("File owner changed"); - }).catch(function(err){ - console.info("Failed to change the file owner. Error:"+ err); + }).catch(function (err) { + console.info("chown failed with error:" + err); }); ``` @@ -2453,7 +2417,7 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono let filePath = pathDir + "/test.txt"; let fd = fileio.openSync(filePath); let stat = fileio.statSync(filePath); - fileio.fchown(fd, stat.uid, stat.gid, function (err){ + fileio.fchown(fd, stat.uid, stat.gid, function (err) { // Do something. }); ``` @@ -2512,10 +2476,10 @@ Changes the file owner (owner of the symbolic link, not the file referred to by ```js let filePath = pathDir + "/test.txt"; let stat = fileio.statSync(filePath); - fileio.lchown(filePath, stat.uid, stat.gid).then(function() { + fileio.lchown(filePath, stat.uid, stat.gid).then(function () { console.info("File owner changed"); - }).catch(function(err){ - console.info("Failed to change the file owner. Error:"+ err); + }).catch(function (err) { + console.info("chown failed with error:" + err); }); ``` @@ -2542,7 +2506,7 @@ Changes the file owner (owner of the symbolic link, not the file referred to by ```js let filePath = pathDir + "/test.txt"; let stat = fileio.statSync(filePath); - fileio.lchown(filePath, stat.uid, stat.gid, function (err){ + fileio.lchown(filePath, stat.uid, stat.gid, function (err) { // Do something. }); ``` @@ -2586,8 +2550,8 @@ Listens for file or directory changes. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file. | -| events | Number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| -| callback | AsyncCallback<number > | Yes | Called each time a change is detected. | +| events | number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| +| callback | AsyncCallback<number> | Yes | Called each time a change is detected. | **Return value** @@ -2599,8 +2563,8 @@ Listens for file or directory changes. This API uses an asynchronous callback to ```js let filePath = pathDir +"/test.txt"; - fileio.createWatcher(filePath, 1, function(number){ - console.info("Monitoring times: "+number); + fileio.createWatcher(filePath, 1, function (number) { + console.info("Monitoring times: " +number); }); ``` @@ -2616,7 +2580,7 @@ Obtains the file read result. This class applies only to the **read()** method. | --------- | ---------- | ---- | ---- | ----------------- | | bytesRead | number | Yes | Yes | Length of the data read. | | offset | number | Yes | Yes | Position of the buffer to which the data will be read in reference to the start address of the buffer.| -| buffer | ArrayBufer | Yes | Yes | Buffer for storing the data read. | +| buffer | ArrayBuffer | Yes | Yes | Buffer for storing the data read. | ## Stat @@ -2631,7 +2595,7 @@ Provides detailed file information. Before calling a method of the **Stat** clas | ------ | ------ | ---- | ---- | ---------------------------------------- | | dev | number | Yes | No | Major device number. | | ino | number | Yes | No | File ID. Different files on the same device have different **ino**s. | -| mode | number | Yes | No | File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| +| mode | number | Yes | No | File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| | nlink | number | Yes | No | Number of hard links in the file. | | uid | number | Yes | No | User ID, that is ID of the file owner. | | gid | number | Yes | No | Group ID, that is, ID of the user group of the file. | @@ -2814,10 +2778,10 @@ Stops the **watcher** instance. This API uses a promise to return the result. ```js let filePath = path + "/test.txt"; - let watcher = fileio.createWatcher(filePath, 1, function(number){ - console.info("Monitoring times: "+number); + let watcher = fileio.createWatcher(filePath, 1, function (number) { + console.info("Monitoring times: " +number); }); - watcher.stop().then(function(){ + watcher.stop().then(function () { console.info("Watcher stopped"); }); ``` @@ -2841,10 +2805,10 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return ```js let filePath = path +"/test.txt"; - let watcher = fileio.createWatcher(filePath, 1, function(number){ - console.info("Monitoring times: "+number); + let watcher = fileio.createWatcher(filePath, 1, function (number) { + console.info("Monitoring times: " +number); }); - watcher.stop(function(){ + watcher.stop(function () { console.info("Watcher stopped"); }) ``` @@ -2874,10 +2838,10 @@ Closes the stream. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let ss= fileio.createStreamSync(filePath, "r+"); - ss.close().then(function(){ + ss.close().then(function () { console.info("File stream closed"); - }).catch(function(err){ - console.info("Failed to close the file stream. Error:"+ err); + }).catch(function (err) { + console.info("close fileStream failed with error:" + err); }); ``` @@ -2943,10 +2907,10 @@ Flushes the stream. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let ss= fileio.createStreamSync(filePath, "r+"); - ss.flush().then(function (){ + ss.flush().then(function () { console.info("Stream flushed"); - }).catch(function(err){ - console.info("Failed to flush the stream. Error:"+ err); + }).catch(function (err) { + console.info("flush failed with error:" + err); }); ``` @@ -2995,12 +2959,7 @@ Synchronously flushes the stream. ### write7+ -write(buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}): Promise<number> +write(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): Promise<number> Writes data into the stream. This API uses a promise to return the result. @@ -3010,7 +2969,7 @@ Writes data into the stream. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | - | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size | **Return value** @@ -3024,22 +2983,17 @@ Writes data into the stream. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let ss= fileio.createStreamSync(filePath, "r+"); - ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ - console.info("Data written to the stream. Size is:"+ number); - }).catch(function(err){ - console.info("Failed to write data to the stream. Error:"+ err); + ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number) { + console.info("write succeed and size is:" + number); + }).catch(function (err) { + console.info("write failed with error:" + err); }); ``` ### write7+ -write(buffer: ArrayBuffer | string, options: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}, callback: AsyncCallback<number>): void +write(buffer: ArrayBuffer|string, options: { offset?: number; length?: number; position?: number; encoding?: string; }, callback: AsyncCallback<number>): void Writes data into the stream. This API uses an asynchronous callback to return the result. @@ -3049,7 +3003,7 @@ Writes data into the stream. This API uses an asynchronous callback to return th | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | - | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size| | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | @@ -3061,7 +3015,7 @@ Writes data into the stream. This API uses an asynchronous callback to return th ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (bytesWritten) { // Do something. - console.info("Data written to the stream. Size is:"+ bytesWritten); + console.info("write succeed and size is:" + bytesWritten); } }); ``` @@ -3069,12 +3023,7 @@ Writes data into the stream. This API uses an asynchronous callback to return th ### writeSync7+ -writeSync(buffer: ArrayBuffer | string, options?: { - offset?: number; - length?: number; - position?: number; - encoding?: string; -}): number +writeSync(buffer: ArrayBuffer|string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): number Synchronously writes data into the stream. @@ -3084,7 +3033,7 @@ Synchronously writes data into the stream. | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------------------------------------- | - | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | buffer | ArrayBuffer\|string | Yes | Data to write. It can be a string or data from a buffer. | | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.
Constraints: offset + length <= Buffer size | **Return value** @@ -3104,11 +3053,7 @@ Synchronously writes data into the stream. ### read7+ -read(buffer: ArrayBuffer, options?: { - position?: number; - offset?: number; - length?: number; -}): Promise<ReadOut> +read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }): Promise<ReadOut> Reads data from the stream. This API uses a promise to return the result. @@ -3132,22 +3077,18 @@ Reads data from the stream. This API uses a promise to return the result. ```js let filePath = pathDir + "/test.txt"; let ss = fileio.createStreamSync(filePath, "r+"); - ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut){ + ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut) { console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - }).catch(function(err){ - console.info("Failed to read data. Error:"+ err); + }).catch(function (err) { + console.info("read data failed with error:" + err); }); ``` ### read7+ -read(buffer: ArrayBuffer, options: { - position?: number; - offset?: number; - length?: number; -}, callback: AsyncCallback<ReadOut>): void +read(buffer: ArrayBuffer, options: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback<ReadOut>): void Reads data from the stream. This API uses an asynchronous callback to return the result. @@ -3177,11 +3118,7 @@ Reads data from the stream. This API uses an asynchronous callback to return the ### readSync7+ -readSync(buffer: ArrayBuffer, options?: { - position?: number; - offset?: number; - length?: number; -}): number +readSync(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }): number Synchronously reads data from the stream. @@ -3231,10 +3168,10 @@ Reads the next directory entry. This API uses a promise to return the result. **Example** ```js - dir.read().then(function (dirent){ - console.log("Read the next directory entry:"+JSON.stringify(dirent)); - }).catch(function(err){ - console.info("Failed to read the next directory entry. Error:"+ err); + dir.read().then(function (dirent) { + console.log("read succeed, the name of dirent is " + dirent.name); + }).catch(function (err) { + console.info("read failed with error:" + err); }); ``` @@ -3259,7 +3196,7 @@ Reads the next directory entry. This API uses an asynchronous callback to return dir.read(function (err, dirent) { if (dirent) { // Do something. - console.log("Read the next directory entry:"+JSON.stringify(dirent)); + console.log("read succeed, the name of file is " + dirent.name); } }); ``` @@ -3297,7 +3234,7 @@ Closes a directory. This API uses a promise to return the result. After a direct **Example** ```js - dir.close().then(function(err){ + dir.close().then(function (err) { console.info("close dir successfully"); }); ``` @@ -3314,7 +3251,7 @@ Closes a directory. This API uses an asynchronous callback to return the result. **Example** ```js - dir.close(function(err){ + dir.close(function (err) { console.info("close dir successfully"); }); ``` @@ -3503,17 +3440,16 @@ Checks whether a directory entry is a symbolic link. ## Filter9+ -Defines the file filter configuration. - **System API**: This is a system API. **System capability**: SystemCapability.FileManagement.File.FileIO +Defines the file filter configuration. | Name | Type | Description | | ----------- | --------------- | ------------------ | | suffix | Array<string> | File name extensions. The keywords in the array are of the OR relationship. | -| displayName | Array<string> | File name for fuzzy match. The keywords in the array are of the OR relationship.| +| displayName | Array<string> | File names for fuzzy match. The keywords in the array are of the OR relationship.| | mimeType | Array<string> | MIME types to match. The keywords in the array are of the OR relationship. | | fileSizeOver | number | File size to match. The files which are of the same or a lager size are matched. | | lastModifiedAfter | Date | File modification time to match. The files modified after the specified time are matched. | diff --git a/en/application-dev/reference/apis/js-apis-freeInstall.md b/en/application-dev/reference/apis/js-apis-freeInstall.md index 94ab3e8ac8cad4c8a41a4820741e595535f388a3..73d618e2f6eeed9df97b72dd4df8ba5839b1864c 100644 --- a/en/application-dev/reference/apis/js-apis-freeInstall.md +++ b/en/application-dev/reference/apis/js-apis-freeInstall.md @@ -1,4 +1,4 @@ -# @ohos.bundle.freeInstall +# @ohos.bundle.freeInstall (freeInstall) The **Bundle.freeInstall** module provides APIs for setting and obtaining installation-free information and APIs for obtaining **BundlePackInfo** and **DispatchInfo**. @@ -63,7 +63,7 @@ Sets an upgrade flag for a module. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **null**; otherwise, **err** is an error object.| @@ -113,7 +113,7 @@ Sets an upgrade flag for a module. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| @@ -166,7 +166,7 @@ Checks whether a module can be removed. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | --------------------------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned.| @@ -266,7 +266,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This | Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Bundle name. | -| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. | +| 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.| **Error codes** @@ -311,7 +311,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundleFlag**. This API | Name | Type | Mandatory| Description | | -------------- | --------------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md index 5d22ce86255fa5bb680d4cf66c530a98fe4f215a..e102353bf8b19431fab51151c9c634916fa39ff4 100644 --- a/en/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -1,9 +1,8 @@ -# Geolocation Manager +# @ohos.geoLocationManager (Geolocation Manager) -The Geolocation Manager module provides location service management functions. +The **geoLocationManager** module provides location service management functions. -> **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. ## Applying for Permissions diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index a5c7034c0333cb640dbe1a51b7f5f6e6f63743ca..147ce8af9468e56116112b3af3c46e9a39527ab0 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,10 +1,11 @@ -# Geolocation +# @ohos.geolocation (Geolocation) -The Geolocation module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. +The **geolocation** module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. > **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 provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. +> +> - 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 provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. ## Applying for Permissions @@ -47,7 +48,7 @@ on(type: 'locationChange', request: LocationRequest, callback: Callback<Locat Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). **Required permissions**: ohos.permission.LOCATION @@ -63,7 +64,6 @@ Registers a listener for location changes with a location request initiated. The | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| - **Example** ```ts @@ -82,7 +82,7 @@ off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange). **Required permissions**: ohos.permission.LOCATION @@ -116,7 +116,7 @@ on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationenabledchange). **Required permissions**: ohos.permission.LOCATION @@ -148,7 +148,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationenabledchange). **Required permissions**: ohos.permission.LOCATION @@ -182,6 +182,7 @@ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, ca Registers a listener for cached GNSS location reports. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroncachedgnsslocationschange). @@ -217,6 +218,7 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati Unregisters the listener for cached GNSS location reports. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroffcachedgnsslocationschange). @@ -252,6 +254,7 @@ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): voi Registers a listener for GNSS satellite status change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageronsatellitestatuschange). @@ -285,6 +288,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): v Unregisters the listener for GNSS satellite status change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffsatellitestatuschange). @@ -318,6 +322,7 @@ on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageronnmeamessage). @@ -351,6 +356,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageroffnmeamessage). @@ -385,6 +391,7 @@ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange). @@ -434,6 +441,7 @@ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffgnssfencestatuschange). @@ -482,7 +490,7 @@ getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<L Obtains the current location. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). **Required permissions**: ohos.permission.LOCATION @@ -520,7 +528,7 @@ getCurrentLocation(callback: AsyncCallback<Location>): void Obtains the current location. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). **Required permissions**: ohos.permission.LOCATION @@ -555,7 +563,7 @@ getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> Obtains the current location. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation-2). **Required permissions**: ohos.permission.LOCATION @@ -592,7 +600,7 @@ getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). **Required permissions**: ohos.permission.LOCATION @@ -627,7 +635,7 @@ getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). **Required permissions**: ohos.permission.LOCATION @@ -657,7 +665,7 @@ isLocationEnabled(callback: AsyncCallback<boolean>): void Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). **Required permissions**: ohos.permission.LOCATION @@ -691,7 +699,7 @@ isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). **Required permissions**: ohos.permission.LOCATION @@ -720,7 +728,7 @@ requestEnableLocation(callback: AsyncCallback<boolean>): void Requests to enable the location service. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation). **Required permissions**: ohos.permission.LOCATION @@ -754,7 +762,7 @@ requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1). **Required permissions**: ohos.permission.LOCATION @@ -783,7 +791,7 @@ isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). **Required permissions**: ohos.permission.LOCATION @@ -817,7 +825,7 @@ isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). **Required permissions**: ohos.permission.LOCATION @@ -846,7 +854,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation). **Required permissions**: ohos.permission.LOCATION @@ -882,7 +890,7 @@ getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<Ge Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation-1). **Required permissions**: ohos.permission.LOCATION @@ -918,7 +926,7 @@ getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback< Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname). **Required permissions**: ohos.permission.LOCATION @@ -954,7 +962,7 @@ getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAd Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname-1). **Required permissions**: ohos.permission.LOCATION @@ -991,6 +999,7 @@ getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize). @@ -1026,6 +1035,7 @@ getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize-1). @@ -1056,6 +1066,7 @@ flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations). @@ -1091,6 +1102,7 @@ flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations-1). @@ -1121,6 +1133,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): v Sends an extended command to the location subsystem. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). @@ -1158,6 +1171,7 @@ sendCommand(command: LocationCommand): Promise<boolean>; Sends an extended command to the location subsystem. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). @@ -1192,7 +1206,7 @@ Sends an extended command to the location subsystem. Sets the priority of the location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestPriority](js-apis-geoLocationManager.md#locationrequestpriority). **Required permissions**: ohos.permission.LOCATION @@ -1211,7 +1225,7 @@ Sets the priority of the location request. Sets the scenario of the location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestScenario](js-apis-geoLocationManager.md#locationrequestscenario). **Required permissions**: ohos.permission.LOCATION @@ -1232,7 +1246,7 @@ Sets the priority of the location request. Enumerates error codes of the location service. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. **Required permissions**: ohos.permission.LOCATION @@ -1254,7 +1268,7 @@ Enumerates error codes of the location service. Defines a reverse geocoding request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.ReverseGeoCodeRequest](js-apis-geoLocationManager.md#reversegeocoderequest). **Required permissions**: ohos.permission.LOCATION @@ -1273,7 +1287,7 @@ Defines a reverse geocoding request. Defines a geocoding request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoCodeRequest](js-apis-geoLocationManager.md#geocoderequest). **Required permissions**: ohos.permission.LOCATION @@ -1295,7 +1309,7 @@ Defines a geocoding request. Defines a geographic location. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoAddress](js-apis-geoLocationManager.md#geoaddress). **Required permissions**: ohos.permission.LOCATION @@ -1328,7 +1342,7 @@ Defines a geographic location. Defines a location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequest](js-apis-geoLocationManager.md#locationrequest). **Required permissions**: ohos.permission.LOCATION @@ -1348,7 +1362,7 @@ Defines a location request. Defines the current location request. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#currentlocationrequest). **Required permissions**: ohos.permission.LOCATION @@ -1368,6 +1382,7 @@ Defines the current location request. Defines the satellite status information. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.SatelliteStatusInfo](js-apis-geoLocationManager.md#satellitestatusinfo). @@ -1390,6 +1405,7 @@ Defines the satellite status information. Represents a request for reporting cached GNSS locations. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.CachedGnssLocationsRequest](js-apis-geoLocationManager.md#cachedgnsslocationsrequest). @@ -1408,6 +1424,7 @@ Represents a request for reporting cached GNSS locations. Defines a GNSS geofence. Currently, only circular geofences are supported. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.Geofence](js-apis-geoLocationManager.md#geofence). @@ -1428,6 +1445,7 @@ Defines a GNSS geofence. Currently, only circular geofences are supported. Represents a GNSS geofencing request. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeofenceRequest](js-apis-geoLocationManager.md#geofencerequest). @@ -1447,6 +1465,7 @@ Represents a GNSS geofencing request. Defines the privacy statement type. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationPrivacyType](js-apis-geoLocationManager.md#locationprivacytype). @@ -1466,6 +1485,7 @@ Defines the privacy statement type. Defines an extended command. > **NOTE** +> > This API is supported since API version 8. > This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationCommand](js-apis-geoLocationManager.md#locationcommand). @@ -1483,7 +1503,7 @@ Defines an extended command. Defines a location. -> **NOTE** +> **NOTE**
> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location). **Required permissions**: ohos.permission.LOCATION diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index d8da0f628f90a5090e9b2ccf0576b6ffb03ff69d..d39dbd1e6649359d5e6433fe11b0a2d68febf953 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -1,7 +1,6 @@ # @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. @@ -43,7 +42,7 @@ A constructor used to create a **HashMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -72,7 +71,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -108,7 +107,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -146,7 +145,7 @@ Checks whether this container contains the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -184,7 +183,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -216,7 +215,7 @@ Adds all elements in a **HashMap** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -256,7 +255,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -292,7 +291,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -318,7 +317,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -350,7 +349,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -387,7 +386,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -431,7 +430,7 @@ Replaces an element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -470,7 +469,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -504,7 +503,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -542,14 +541,13 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The Symbol.iterator method cannot be bound. | **Example** - ```ts let hashMap = new HashMap(); hashMap.set("squirrel", 123); diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 2c52b1268a1ee4d61f3c89c26949823baa28e566..f2ece05248321395e2ca3f651ff32a462503d5c4 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -1,7 +1,6 @@ # @ohos.util.HashSet (Nonlinear Container HashSet) > **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. **HashSet** is implemented based on [HashMap](js-apis-hashmap.md). In **HashSet**, only the **value** object is processed. @@ -51,7 +50,7 @@ A constructor used to create a **HashSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -80,7 +79,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -116,7 +115,7 @@ Checks whether this container contains the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -154,7 +153,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -190,7 +189,7 @@ Removes an element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -216,7 +215,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -248,7 +247,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -293,7 +292,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -326,7 +325,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -364,7 +363,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index 24125f48cde82856302fc0b981b707c53387d54b..260c8c541809f723cee63a3cf7f7ce9374ff886d 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -1,4 +1,4 @@ -# HiAppEvent +# @ohos.hiAppEvent (Application Event Logging) The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 16c1d7b2ea9ca7327060d599da5fd0b6e89235ef..1a6339e406c98eb2dfd81239da3e852bcb4afe47 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -1,8 +1,9 @@ -# HiChecker +# @ohos.hichecker (HiChecker) -HiChecker is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. +The HiChecker module allows you to check issues that may be easily ignored during development of applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. -> **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. @@ -13,7 +14,7 @@ import hichecker from '@ohos.hichecker'; ``` -## Constant +## Constants Provides the constants of all rule types. @@ -26,10 +27,8 @@ Provides the constants of all rule types. | RULE_THREAD_CHECK_SLOW_PROCESS | bigint | Caution rule, which is programmed to detect whether any time-consuming function is invoked. | | RULE_CHECK_ABILITY_CONNECTION_LEAK | bigint | Caution rule, which is programmed to detect whether ability leakage has occurred. | - ## hichecker.addCheckRule9+ -## hichecker.addRule addCheckRule(rule: bigint): void Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. @@ -121,12 +120,10 @@ catch (err) { ## hichecker.addRule(deprecated) -## hichecker.addRule +addRule(rule: bigint): void > **NOTE**
This API is deprecated since API version 9. You are advised to use [hichecker.addCheckRule](#hicheckeraddcheckrule9) instead. -addRule(rule: bigint): void - Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. **System capability**: SystemCapability.HiviewDFX.HiChecker diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 7c9393e17557cc927cc880b2529c9e25966124af..189d855e894451790976eee2c3816cf17ae950b9 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,10 +1,10 @@ -# HiDebug +# @ohos.hidebug (HiDebug) -> **NOTE** -> +The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling 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 HiDebug module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 66c180ce7fd431a39674276f2b1f20e406cfddb7..54355b12b723cf9cad06f5a4064568d5d772bea5 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,6 +1,6 @@ -# HiLog +# @ohos.hilog (HiLog) -The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. +The **hilog** module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. > **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. diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 50243525c010d6cbfcb3dd9ba9454f8ebb9dac65..b61207a81a9be58f9b8b405535e118757218529e 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -1,6 +1,6 @@ -# HiSysEvent +# @ohos.hiSysEvent (System Event Logging) -This module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file. +The **hiSysEvent** module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file. > **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. diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index aaf38a1962e65293b97f4fe18b4e93d68ef9d92a..b72b026ce908bbde85e385f46212d32e4a7fd61b 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -1,8 +1,8 @@ -# Distributed Call Chain Tracing +# @ohos.hiTraceChain (Distributed Call Chain Tracing) -This module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. +The **hiTraceChain** module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index 04a9db2a0e7bc00cb9ff8a017eb6e39c47d97f30..af19e063a728abd4feb7d7238051d94ca49c2459 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -1,9 +1,8 @@ -# Performance Tracing +# @ohos.hiTraceMeter (Performance Tracing) -The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. +The **hiTraceMeter** module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. -> **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. diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md index 742c83b9c3fdedd2b8e3d8ef59df0535598478c0..86e09db17bda0e6efa68bbeeb973a26f4a4ff467 100644 --- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -1,8 +1,8 @@ -# Application Event Logging +# @ohos.hiviewdfx.hiAppEvent (Application Event Logging) -This module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. +The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. -> **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. diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 683ecdb676eacc3267f0570c02e7c059170fb68c..3735792dd3f5ce66569fbebf3a1036019e7457ed 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -1,11 +1,9 @@ -# Data Request +# @ohos.net.http (Data Request) -This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. +The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. ->**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. -> +> **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. ## Modules to Import @@ -72,7 +70,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req **Return value** | Type | Description | -| :---------- | :----------------------------------------------------------- | +| ---------- | ----------------------------------------------------------- | | HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| **Example** @@ -181,7 +179,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the **Return value** | Type | Description | -| :------------------------------------- | :-------------------------------- | +| ------------------------------------- | -------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| @@ -374,7 +372,7 @@ Defines an HTTP request method. **System capability**: SystemCapability.Communication.NetStack | Name | Value | Description | -| :------ | ------- | :------------------ | +| ------ | ------- | ------------------ | | OPTIONS | "OPTIONS" | OPTIONS method.| | GET | "GET" | GET method. | | HEAD | "HEAD" | HEAD method. | @@ -459,7 +457,7 @@ Creates a default object to store responses to HTTP access requests. **Return value** | Type | Description | -| :---------- | :----------------------------------------------------------- | +| ---------- | ----------------------------------------------------------- | | [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| **Example** @@ -602,6 +600,6 @@ Enumerates HTTP protocol versions. **System capability**: SystemCapability.Communication.NetStack | Name | Description | -| :-------- | :----------- | +| -------- | ----------- | | HTTP1_1 | HTTP1.1 | | HTTP2 | HTTP2 | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 08bf0cfe66b40f46262765048463081b9c1a66a6..cda33f5434360fe5ca3f21f9f2c0a04ad5b50474 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,15 +1,18 @@ -# Internationalization – I18N +# @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 [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. +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** -> 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 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. +> +> - This 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. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). + ## Modules to Import ```js -import i18n from '@ohos.i18n'; +import I18n from '@ohos.i18n'; ``` @@ -39,16 +42,16 @@ Obtains the localized script for the specified country. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayCountry = i18n.System.getDisplayCountry("zh-CN", "en-GB"); + 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}.`) } @@ -78,16 +81,16 @@ Obtains the localized script for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayLanguage = i18n.System.getDisplayLanguage("zh", "en-GB"); + 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}.`) } @@ -109,16 +112,16 @@ Obtains the list of system languages. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguages = i18n.System.getSystemLanguages(); + 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}.`) } @@ -134,9 +137,9 @@ Obtains the list of countries and regions supported for the specified language. **Parameters** -| Name | Type | Description | -| -------- | ------ | ----- | -| language | string | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Return value** @@ -146,16 +149,16 @@ Obtains the list of countries and regions supported for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemCountries = i18n.System.getSystemCountries('zh'); + 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}.`) } @@ -184,16 +187,16 @@ Checks whether the system language matches the specified region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var res = i18n.System.isSuggested('zh', 'CN'); + let res = I18n.System.isSuggested('zh', 'CN'); // res = true } catch(error) { console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) } @@ -215,16 +218,16 @@ Obtains the system language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguage = i18n.System.getSystemLanguage(); + 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}.`) } @@ -236,7 +239,7 @@ static setSystemLanguage(language: string): void Sets the system language. Currently, this API does not support real-time updating of the system language. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -244,22 +247,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| language | string | Yes | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLanguage('zh'); + 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}.`) } @@ -281,16 +284,16 @@ Obtains the system region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemRegion = i18n.System.getSystemRegion(); + 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}.`) } @@ -302,7 +305,7 @@ static setSystemRegion(region: string): void Sets the system region. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -310,22 +313,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| region | string | Yes | Region ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| region | string | Yes | Region ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemRegion('CN'); + 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}.`) } @@ -347,16 +350,16 @@ Obtains the system locale. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLocale = i18n.System.getSystemLocale(); + 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}.`) } @@ -368,7 +371,7 @@ static setSystemLocale(locale: string): void Sets the system locale. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -376,22 +379,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| locale | string | Yes | System locale ID, for example, **zh-CN**.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| locale | string | Yes | System locale ID, for example, **zh-CN**.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLocale('zh-CN'); + 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}.`) } @@ -413,16 +416,16 @@ Checks whether the 24-hour clock is used. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var is24HourClock = i18n.System.is24HourClock(); + 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}.`) } @@ -434,7 +437,7 @@ static set24HourClock(option: boolean): void Sets the 24-hour clock. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -448,17 +451,17 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Set the system time to the 24-hour clock. try { - i18n.System.set24HourClock(true); + I18n.System.set24HourClock(true); } catch(error) { console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -470,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void Adds a preferred language to the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -485,19 +488,19 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; + let language = 'zh-CN'; + let index = 0; try { - i18n.System.addPreferredLanguage(language, index); + 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}.`) } @@ -509,7 +512,7 @@ static removePreferredLanguage(index: number): void Deletes a preferred language from the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -523,18 +526,18 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; + let index = 0; try { - i18n.System.removePreferredLanguage(index); + I18n.System.removePreferredLanguage(index); } catch(error) { console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -544,7 +547,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. **System capability**: SystemCapability.Global.I18n @@ -552,20 +555,20 @@ Obtains the list of preferred languages. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var preferredLanguageList = i18n.System.getPreferredLanguageList(); + 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}.`) } @@ -587,16 +590,16 @@ Obtains the first language in the preferred language list. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var firstPreferredLanguage = i18n.System.getFirstPreferredLanguage(); + 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}.`) } @@ -618,16 +621,16 @@ Obtains the preferred language of an application. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var appPreferredLanguage = i18n.System.getAppPreferredLanguage(); + 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}.`) } @@ -637,9 +640,9 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static setUsingLocalDigit(flag: boolean): void -Sets whether to turn on the local digit switch. +Sets whether to enable the local digit switch. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -649,20 +652,20 @@ This is a system API. | Name | Type | Mandatory | Description | | ---- | ------- | ---- | ------------------------------- | -| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| +| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - i18n.System.setUsingLocalDigit(true); + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. } catch(error) { console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } @@ -684,23 +687,23 @@ Checks whether the local digit switch is turned on. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - var status = i18n.System.getUsingLocalDigit(); + 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}.`) } ``` -## i18n.isRTL7+ +## I18n.isRTL7+ isRTL(locale: string): boolean @@ -710,9 +713,9 @@ Checks whether the localized script for the specified language is displayed from **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| locale | string | Yes | Locale ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| locale | string | Yes | Locale ID.| **Return value** @@ -727,7 +730,7 @@ Checks whether the localized script for the specified language is displayed from ``` -## i18n.getCalendar8+ +## I18n.getCalendar8+ getCalendar(locale: string, type? : string): Calendar @@ -750,7 +753,7 @@ Obtains a **Calendar** object. **Example** ```js - i18n.getCalendar("zh-Hans", "gregory"); + I18n.getCalendar("zh-Hans", "chinese"); // Obtain the Calendar object for the Chinese lunar calendar. ``` @@ -773,8 +776,8 @@ Sets the date for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - var date = new Date(2021, 10, 7, 8, 0, 0, 0); + let calendar = I18n.getCalendar("en-US", "gregory"); + let date = new Date(2021, 10, 7, 8, 0, 0, 0); calendar.setTime(date); ``` @@ -795,7 +798,7 @@ Sets the date and time for this **Calendar** object. The value is represented by **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); + let calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); ``` @@ -821,7 +824,7 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 ``` @@ -842,7 +845,7 @@ Sets the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); ``` @@ -863,9 +866,9 @@ Obtains the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); - calendar.getTimeZone(); // Asia/Shanghai" + let timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai" ``` @@ -885,8 +888,8 @@ Obtains the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - calendar.getFirstDayOfWeek(); + let calendar = I18n.getCalendar("en-US", "gregory"); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` @@ -906,8 +909,9 @@ Sets the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.setFirstDayOfWeek(0); + let calendar = I18n.getCalendar("zh-Hans"); + calendar.setFirstDayOfWeek(3); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3 ``` @@ -927,8 +931,8 @@ Obtains the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.getMinimalDaysInFirstWeek(); + let calendar = I18n.getCalendar("zh-Hans"); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 ``` @@ -948,8 +952,9 @@ Sets the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` @@ -975,9 +980,9 @@ Obtains the value of the specified field in the **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 - calendar.get("hour_of_day"); // 8 + let hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8 ``` @@ -1003,8 +1008,8 @@ Obtains the **Calendar** object name displayed for the specified locale. **Example** ```js - var calendar = i18n.getCalendar("en-US", "buddhist"); - calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. + let calendar = I18n.getCalendar("en-US", "buddhist"); + let calendarName = calendar.getDisplayName("zh"); // calendarName = "Buddhist Calendar" ``` @@ -1030,10 +1035,10 @@ Checks whether the specified date in this **Calendar** object is a weekend. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 calendar.isWeekend(); // false - var date = new Date(2011, 11, 6, 9, 0, 0); + let date = new Date(2011, 11, 6, 9, 0, 0); calendar.isWeekend(date); // true ``` @@ -1054,11 +1059,11 @@ Creates a **PhoneNumberFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------- | | country | string | Yes | Country or region to which the phone number to be formatted belongs.| -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. | +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | **Example** ```js - var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); + let phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"}); ``` @@ -1084,8 +1089,8 @@ Checks whether the format of the specified phone number is valid. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.isValidNumber("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true ``` @@ -1111,8 +1116,8 @@ Formats a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.format("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312" ``` @@ -1139,18 +1144,18 @@ Obtains the home location of a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.getLocationName("15812312345", "zh-CN"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "Zhanjiang, Guangdong Province" ``` -## PhoneNumberFormatOptions9+ +## PhoneNumberFormatOptions8+ Defines the options for this PhoneNumberFormat object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | | type | string | Yes | Yes | Format type of a phone number. The available options are as follows: E164, INTERNATIONAL, NATIONAL, and RFC3966.| @@ -1161,7 +1166,7 @@ Defines the measurement unit information. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | unit | string | Yes | Yes | Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| | measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**, **US**, or **UK**.| @@ -1189,7 +1194,7 @@ Creates an **IndexUtil** object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); + let indexUtil= I18n.getInstance("zh-CN"); ``` @@ -1212,8 +1217,10 @@ Obtains the index list for this **locale** object. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); - var indexList = indexUtil.getIndexList(); + let indexUtil = I18n.getInstance("zh-CN"); + // indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", + // "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ] + let indexList = indexUtil.getIndexList(); ``` @@ -1233,7 +1240,7 @@ Adds the index of the new **locale** object to the index list. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); ``` @@ -1260,12 +1267,12 @@ Obtains the index of a text object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); - indexUtil.getIndex("hi"); // Return hi. + let indexUtil= I18n.getInstance("zh-CN"); + let index = indexUtil.getIndex("hi"); // index = "H" ``` -## i18n.getLineInstance8+ +## I18n.getLineInstance8+ getLineInstance(locale: string): BreakIterator @@ -1287,7 +1294,7 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); ``` @@ -1310,8 +1317,8 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); - iterator.setLineBreakText("Apple is my favorite fruit."); + let iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit ."); // Set a short sentence as the text to be processed by the BreakIterator object. ``` @@ -1331,9 +1338,9 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.getLineBreakText(); // Apple is my favorite fruit. + let breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit." ``` @@ -1353,9 +1360,9 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.current(); // 0 + let currentPos = iterator.current(); // currentPos = 0 ``` @@ -1375,9 +1382,9 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 + let firstPos = iterator.first(); // firstPos = 0 ``` @@ -1397,9 +1404,9 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.last(); // 27 + let lastPos = iterator.last(); // lastPos = 27 ``` @@ -1425,11 +1432,11 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(); // 6 - iterator.next(10); // -1 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(); // pos = 6 + pos = iterator.next(10); // pos = -1 ``` @@ -1449,11 +1456,11 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(3); // 12 - iterator.previous(); // 9 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(3); // pos = 12 + pos = iterator.previous(); // pos = 9 ``` @@ -1479,11 +1486,11 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.following(0); // 6 - iterator.following(100); // -1 - iterator.current(); // 27 + let pos = iterator.following(0); // pos = 6 + pos = iterator.following(100); // pos = -1 + pos = iterator.current(); // pos = 27 ``` @@ -1509,14 +1516,14 @@ Checks whether the position specified by the offset is a text boundary. If **tru **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.isBoundary(0); // true; - iterator.isBoundary(5); // false; + let isBoundary = iterator.isBoundary(0); // isBoundary = true; + isBoundary = iterator.isBoundary(5); // isBoundary = false; ``` -## i18n.getTimeZone7+ +## I18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone @@ -1538,7 +1545,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. **Example** ```js - var timezone = i18n.getTimeZone(); + let timezone = I18n.getTimeZone(); ``` @@ -1561,8 +1568,8 @@ Obtains the ID of the specified **TimeZone** object. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getID(); + let timezone = I18n.getTimeZone(); + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" ``` @@ -1570,7 +1577,7 @@ Obtains the ID of the specified **TimeZone** object. getDisplayName(locale?: string, isDST?: boolean): string -Obtains the representation of a **TimeZone** object in the specified locale. +Obtains the localized representation of the time zone. **System capability**: SystemCapability.Global.I18n @@ -1589,8 +1596,8 @@ Obtains the representation of a **TimeZone** object in the specified locale. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getDisplayName("zh-CN", false); + let timezone = I18n.getTimeZone(); + let timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "China Standard Time" ``` @@ -1610,8 +1617,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getRawOffset(); + let timezone = I18n.getTimeZone(); + let offset = timezone.getRawOffset(); // offset = 28800000 ``` @@ -1631,8 +1638,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getOffset(1234567890); + let timezone = I18n.getTimeZone(); + let offset = timezone.getOffset(1234567890); // offset = 28800000 ``` @@ -1652,7 +1659,8 @@ Obtains the list of time zone IDs supported by the system. **Example** ```ts - var ids = i18n.TimeZone.getAvailableIDs(); + // ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 24 time zones supported in total + let ids = I18n.TimeZone.getAvailableIDs(); ``` @@ -1672,7 +1680,8 @@ Obtains the list of time zone city IDs supported by the system. **Example** ```ts - var cityIDs = i18n.TimeZone.getAvailableZoneCityIDs(); + // cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"], 24 time zone cities supported in total + let cityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); ``` @@ -1680,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. static getCityDisplayName(cityID: string, locale: string): string -Obtains the localized display of a time zone city in the specified locale. +Obtains the localized representation of a time zone city in the specified locale. **System capability**: SystemCapability.Global.I18n @@ -1699,7 +1708,7 @@ Obtains the localized display of a time zone city in the specified locale. **Example** ```ts - var displayName = i18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); + let displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "Shanghai (China)" ``` @@ -1725,7 +1734,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID **Example** ```ts - var timezone = i18n.TimeZone.getTimezoneFromCity("Shanghai"); + let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai"); ``` @@ -1748,7 +1757,9 @@ Obtains a list of IDs supported by the **Transliterator** object. **Example** ```ts - i18n.Transliterator.getAvailableIDs(); + // ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...], 671 IDs supported in total + // Each ID consists of two parts separated by a hyphen (-). The format is source-destination. + let ids = I18n.Transliterator.getAvailableIDs(); ``` @@ -1774,7 +1785,7 @@ Creates a **Transliterator** object. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); ``` @@ -1800,8 +1811,8 @@ Converts the input string from the source format to the target format. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); - transliterator.transform ("China"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); + let res = transliterator.transform("China"); // res = "zhōng guó" ``` @@ -1830,7 +1841,7 @@ Checks whether the input character string is composed of digits. **Example** ```js - var isdigit = i18n.Unicode.isDigit("1"); // Return true. + let isdigit = I18n.Unicode.isDigit("1"); // isdigit = true ``` @@ -1856,7 +1867,7 @@ Checks whether the input character is a space. **Example** ```js - var isspacechar = i18n.Unicode.isSpaceChar("a"); // Return false. + let isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false ``` @@ -1882,7 +1893,7 @@ Checks whether the input character is a white space. **Example** ```js - var iswhitespace = i18n.Unicode.isWhitespace("a"); // Return false. + let iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false ``` @@ -1908,7 +1919,7 @@ Checks whether the input character is of the right to left (RTL) language. **Example** ```js - var isrtl = i18n.Unicode.isRTL("a"); // Return false. + let isrtl = I18n.Unicode.isRTL("a"); // isrtl = false ``` @@ -1934,7 +1945,7 @@ Checks whether the input character is an ideographic character. **Example** ```js - var isideograph = i18n.Unicode.isIdeograph("a"); // Return false. + let isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false ``` @@ -1960,7 +1971,7 @@ Checks whether the input character is a letter. **Example** ```js - var isletter = i18n.Unicode.isLetter("a"); // Return true. + let isletter = I18n.Unicode.isLetter("a"); // isletter = true ``` @@ -1986,7 +1997,7 @@ Checks whether the input character is a lowercase letter. **Example** ```js - var islowercase = i18n.Unicode.isLowerCase("a"); // Return true. + let islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true ``` @@ -2012,7 +2023,7 @@ Checks whether the input character is an uppercase letter. **Example** ```js - var isuppercase = i18n.Unicode.isUpperCase("a"); // Return false. + let isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false ``` @@ -2038,7 +2049,7 @@ Obtains the type of the input character string. **Example** ```js - var type = i18n.Unicode.getType("a"); + let type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER" ``` @@ -2071,7 +2082,7 @@ Converts one measurement unit into another and formats the unit based on the spe **Example** ```js - i18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); + let res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters ``` @@ -2097,11 +2108,11 @@ Obtains the sequence of the year, month, and day in the specified locale. **Example** ```js - i18n.I18NUtil.getDateOrder("zh-CN"); + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" ``` -## i18n.getDisplayCountry(deprecated) +## I18n.getDisplayCountry(deprecated) getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string @@ -2127,12 +2138,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayCountry("zh-CN", "en-GB", true); - i18n.getDisplayCountry("zh-CN", "en-GB"); + let countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true + countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true ``` -## i18n.getDisplayLanguage(deprecated) +## I18n.getDisplayLanguage(deprecated) getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string @@ -2158,12 +2169,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayLanguage("zh", "en-GB", true); - i18n.getDisplayLanguage("zh", "en-GB"); + let languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese" + languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese" ``` -## i18n.getSystemLanguage(deprecated) +## I18n.getSystemLanguage(deprecated) getSystemLanguage(): string @@ -2181,11 +2192,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLanguage(); + let systemLanguage = I18n.getSystemLanguage(); // Obtain the current system language. ``` -## i18n.getSystemRegion(deprecated) +## I18n.getSystemRegion(deprecated) getSystemRegion(): string @@ -2203,11 +2214,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemRegion(); + let region = I18n.getSystemRegion(); // Obtain the current system region. ``` -## i18n.getSystemLocale(deprecated) +## I18n.getSystemLocale(deprecated) getSystemLocale(): string @@ -2225,11 +2236,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLocale(); + let locale = I18n.getSystemLocale (); // Obtain the system locale. ``` -## i18n.is24HourClock(deprecated) +## I18n.is24HourClock(deprecated) is24HourClock(): boolean @@ -2247,11 +2258,11 @@ This API is deprecated since API version 9. You are advised to use [System.is24H **Example** ```js - var is24HourClock = i18n.is24HourClock(); + let is24HourClock = I18n.is24HourClock(); ``` -## i18n.set24HourClock(deprecated) +## I18n.set24HourClock(deprecated) set24HourClock(option: boolean): boolean @@ -2278,11 +2289,11 @@ This API is deprecated since API version 9. You are advised to use [System.set24 **Example** ```js // Set the system time to the 24-hour clock. - var success = i18n.set24HourClock(true); + let success = I18n.set24HourClock(true); ``` -## i18n.addPreferredLanguage(deprecated) +## I18n.addPreferredLanguage(deprecated) addPreferredLanguage(language: string, index?: number): boolean @@ -2310,13 +2321,13 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; - var success = i18n.addPreferredLanguage(language, index); + let language = 'zh-CN'; + let index = 0; + let success = I18n.addPreferredLanguage(language, index); ``` -## i18n.removePreferredLanguage(deprecated) +## I18n.removePreferredLanguage(deprecated) removePreferredLanguage(index: number): boolean @@ -2343,16 +2354,16 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; - var success = i18n.removePreferredLanguage(index); + let index = 0; + let success = I18n.removePreferredLanguage(index); ``` -## i18n.getPreferredLanguageList(deprecated) +## I18n.getPreferredLanguageList(deprecated) getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. @@ -2362,15 +2373,15 @@ This API is supported since API version 8 and is deprecated since API version 9. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Example** ```js - var preferredLanguageList = i18n.getPreferredLanguageList(); + let preferredLanguageList = I18n.getPreferredLanguageList(); // Obtain the preferred language list. ``` -## i18n.getFirstPreferredLanguage(deprecated) +## I18n.getFirstPreferredLanguage(deprecated) getFirstPreferredLanguage(): string @@ -2388,7 +2399,7 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js - var firstPreferredLanguage = i18n.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.getFirstPreferredLanguage(); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index f776c56334112c2b739b5b6a85ef7153c4da1564..54c8f0400be1f1e8b9f9b836098a94ace0c4f637 100644 --- a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -1,6 +1,6 @@ # AbilityResult -The **AbilityResult** module defines the result code and data returned when an ability is started or destroyed. +The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-context.md#abilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-context.md#abilitycontextterminateselfwithresult). > **NOTE** > @@ -10,17 +10,5 @@ The **AbilityResult** module defines the result code and data returned when an a | Name | Readable | Writable | Type | Mandatory| Description | | ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ | -| resultCode | Yes | No | number | No | Result code returned when the ability is started or destroyed. | -| want | Yes | No | [Want](./js-apis-app-ability-want.md) | No | Data returned when the ability is destroyed.| - -**Example** - ```ts - let want = { - bundleName: 'com.example.mydocapplication', - abilityName: 'MainAbility', - }; - this.context.startAbilityForResult(want, (error, data) => { - let resultCode = data.resultCode; - let want = data.want; - }); - ``` +| resultCode | Yes | Yes | number | Yes | Result code returned after the started ability is terminated. | +| want | Yes | Yes | [Want](./js-apis-app-ability-want.md) | No | Data returned after the started ability is terminated. | 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 685329b15fe26618c4b2a3be2242d4912415a66d..db0814fa146e09114eeb4fa635dfa78564ee595e 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 @@ -1,45 +1,11 @@ # ConnectOptions -The **ConnectOptions** module defines the options for connection. +**ConnectOptions** can be used as an input parameter to receive status changes during the connection to a background service. For example, it is used as an input parameter of [connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) to connect to a ServiceExtensionAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory | Description | | ------------ | -------- | ---- | ------------------------- | -| onConnect7+ | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect7+ | function | Yes | Callback invoked when the connection fails. | -| onFailed7+ | function | Yes | Callback invoked when **connectAbility** fails to be called.| - -**Return value** - -| Type | Description | -| ------ | -------------------- | -| number | ID of the Service ability connected.| - -**Example** - -```ts -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)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` +| 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.| 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 f06df85ac59ffe3074519efd2c9aef95a5093cd7..d6b0c51051feb92f30495bdc552f84cae5e06018 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 @@ -1,5 +1,7 @@ # DataAbilityHelper +The **DataAbilityHelper** object is obtained through [acquireDataAbilityHelper](js-apis-ability-featureAbility.md#featureabilityacquiredataabilityhelper7). + > **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. @@ -9,15 +11,15 @@ Import the following modules based on the actual situation before using the current module: ```ts -import ohos_data_ability from '@ohos.data.dataAbility' -import ohos_data_rdb from '@ohos.data.rdb' +import ohos_data_ability from '@ohos.data.dataAbility'; +import ohos_data_rdb from '@ohos.data.rdb'; ``` ## DataAbilityHelper.openFile openFile(uri: string, mode: string, callback: AsyncCallback\): void -Opens a file with a specified URI. This API uses an asynchronous callback to return the result. +Opens a file with a specified URI. This API uses an asynchronous callback to return a file descriptor. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -26,22 +28,19 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ---------------------------------- | | uri | string | Yes | URI of the file to open. | -| mode | string | Yes | Mode for opening the file. The value can be **rwt**. | +| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. | | callback | AsyncCallback\ | Yes | Callback used to return the file descriptor.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rwt"; -DAHelper.openFile( - "dataability:///com.example.DataAbility", - mode, - (err) => { - console.info("==========================>Called=======================>"); +var mode = "rw"; +DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { + console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -49,7 +48,7 @@ DAHelper.openFile( openFile(uri: string, mode: string): Promise\ -Opens a file with a specified URI. This API uses a promise to return the result. +Opens a file with a specified URI. This API uses a promise to return a file descriptor. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -58,7 +57,7 @@ Opens a file with a specified URI. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------------ | | uri | string | Yes | URI of the file to open.| -| mode | string | Yes | Mode for opening the file. The value can be **rwt**. | +| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. | **Return value** @@ -69,15 +68,13 @@ Opens a file with a specified URI. This API uses a promise to return the result. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rwt"; -DAHelper.openFile( - "dataability:///com.example.DataAbility", - mode).then((data) => { - console.info("==========================>openFileCallback=======================>"); +var mode = "rw"; +DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { + console.info("openFile data: " + JSON.stringify(data)); }); ``` @@ -85,7 +82,7 @@ DAHelper.openFile( on(type: 'dataChange', uri: string, callback: AsyncCallback\): void -Registers an observer to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Registers an observer to listen for changes in the data specified by a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -93,32 +90,32 @@ Registers an observer to observe data specified by a given URI. This API uses an | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Type of the event to observe. The value is **dataChange**. | +| 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. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); + console.info("onChangeNotify call back"); }; -helper.on( +DAHelper.on( "dataChange", "dataability:///com.example.DataAbility", onChangeNotify -) +); ``` ## DataAbilityHelper.off off(type: 'dataChange', uri: string, callback?: AsyncCallback\): void -Deregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Deregisters the observer that listens for changes in the data specified by a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -126,36 +123,36 @@ Deregisters the observer used to observe data specified by a given URI. This API | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Type of the event to observe. The value is **dataChange**. | +| type | string | Yes | The value **dataChange** means data changes. | | uri | string | Yes | URI of the data.| -| callback | AsyncCallback\ | No | Callback used to return the result. | +| callback | AsyncCallback\ | No | Callback of the listener to deregister. If the callback is set to **null**, all data change listeners are canceled. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); + console.info("onChangeNotify call back"); }; -helper.off( +DAHelper.off( "dataChange", "dataability:///com.example.DataAbility", -) -helper.off( + onChangeNotify +); +DAHelper.off( "dataChange", "dataability:///com.example.DataAbility", - onChangeNotify -) +); ``` ## DataAbilityHelper.getType getType(uri: string, callback: AsyncCallback\): void -Obtains the MIME type of the data specified by a given URI. This API uses an asynchronous callback to return the result. +Obtains the media resource type of the data specified by a given URI. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -164,19 +161,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses an asy | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------- | | uri | string | Yes | URI of the data. | -| callback | AsyncCallback\ | Yes | Callback used to return the MIME type.| +| callback | AsyncCallback\ | Yes | Callback used to return the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getType( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { + console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -184,7 +179,7 @@ DAHelper.getType( getType(uri: string): Promise\ -Obtains the MIME type of the data specified by a given URI. This API uses a promise to return the result. +Obtains the media resource type of the data specified by a given URI. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -198,19 +193,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses a prom | Type | Description | | ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the MIME type.| +| Promise\ | Promise used to return the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getType( - "dataability:///com.example.DataAbility" - ).then((data) => { - console.info("==========================>getTypeCallback=======================>"); +DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { + console.info("getType data: " + JSON.stringify(data)); }); ``` @@ -218,7 +211,7 @@ DAHelper.getType( getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>): void -Obtains the supported MIME types of a specified file. This API uses an asynchronous callback to return the result. +Obtains the supported media resource types of a specified file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -227,31 +220,26 @@ Obtains the supported MIME types of a specified file. This API uses an asynchron | Name | Type | Mandatory| Description | | -------------- | ------------------------------ | ---- | ---------------------------------- | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME type of the file. | -| callback | AsyncCallback\> | Yes | Callback used to return the supported MIME types.| +| mimeTypeFilter | string | Yes | Media resource type of the file to obtain. | +| callback | AsyncCallback\> | Yes | Callback used to return an array holding the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getFileTypes( - "dataability:///com.example.DataAbility", - "image/*", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => { + console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` - - ## DataAbilityHelper.getFileTypes getFileTypes(uri: string, mimeTypeFilter: string): Promise\> -Obtains the supported MIME types of a specified file. This API uses a promise to return the result. +Obtains the supported media resource types of a specified file. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -260,26 +248,23 @@ Obtains the supported MIME types of a specified file. This API uses a promise to | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ---------------------------- | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME type of the file.| +| mimeTypeFilter | string | Yes | Media resource type of the file to obtain.| **Return value** | Type | Description | | ------------------------ | ------------------------ | -| Promise\> | Promise used to return the supported MIME types.| +| Promise\> | Promise used to return an array holding the media resource type.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getFileTypes( - "dataability:///com.example.DataAbility", - "image/*" - ).then((data) => { - console.info("==========================>getFileTypesCallback=======================>"); +DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { + console.info("getFileTypes data: " + JSON.stringify(data)); }); ``` @@ -301,14 +286,12 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.normalizeUri( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { + console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -335,14 +318,12 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.normalizeUri( - "dataability:///com.example.DataAbility", - ).then((data) => { - console.info("==========================>normalizeUriCallback=======================>"); +DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { + console.info("normalizeUri data: " + JSON.stringify(data)); }); ``` @@ -358,25 +339,21 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------------- | -| uri | string | Yes | URI object to normalize. | +| uri | string | Yes | URI object to denormalize. | | callback | AsyncCallback\ | Yes | Callback used to return the denormalized URI object.| **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.denormalizeUri( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { + console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` - - ## DataAbilityHelper.denormalizeUri denormalizeUri(uri: string): Promise\ @@ -400,14 +377,12 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.denormalizeUri( - "dataability:///com.example.DataAbility", - ).then((data) => { - console.info("==========================>denormalizeUriCallback=======================>"); +DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { + console.info("denormalizeUri data: " + JSON.stringify(data)); }); ``` @@ -423,20 +398,18 @@ Notifies the registered observer of a change to the data specified by the URI. T | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| uri | string | Yes | URI of the data.| +| uri | string | Yes | URI of the data that changes.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -helper.notifyChange( - "dataability:///com.example.DataAbility", - (err) => { - console.info("==========================>Called=======================>"); +DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { + console.info("==========================>Called=======================>"); }); ``` @@ -452,7 +425,7 @@ Notifies the registered observer of a change to the data specified by the URI. T | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------------ | -| uri | string | Yes | URI of the data.| +| uri | string | Yes | URI of the data that changes.| **Return value** @@ -463,14 +436,12 @@ Notifies the registered observer of a change to the data specified by the URI. T **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var 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================>"); }); ``` @@ -493,7 +464,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -502,12 +473,9 @@ const valueBucket = { "age": 22, "salary": 200.5, "blobType": "u8", -} -DAHelper.insert( - "dataability:///com.example.DataAbility", - valueBucket, - (err, data) => { - console.info("==========================>Called=======================>"); +}; +DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => { + console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -535,7 +503,7 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -544,12 +512,9 @@ const valueBucket = { "age": 221, "salary": 20.5, "blobType": "u8", -} -DAHelper.insert( - "dataability:///com.example.DataAbility", - valueBucket - ).then((data) => { - console.info("==========================>insertCallback=======================>"); +}; +DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => { + console.info("insert data: " + JSON.stringify(data)); }); ``` @@ -572,18 +537,15 @@ Inserts multiple data records into the database. This API uses an asynchronous c **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var 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("==========================>Called=======================>"); + {"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)); }); ``` @@ -600,7 +562,7 @@ Inserts multiple data records into the database. This API uses a promise to retu | Name | Type | Mandatory| Description | | ------------ | ----------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| valuesBucket | Array | Yes | Data record to insert. | +| valuesBucket | Array | Yes | Data records to insert. | **Return value** @@ -611,18 +573,15 @@ Inserts multiple data records into the database. This API uses a promise to retu **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; var 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("==========================>batchInsertCallback=======================>"); + {"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)); }); ``` @@ -645,17 +604,14 @@ Deletes one or more data records from the database. This API uses an asynchronou **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var 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("==========================>Called=======================>"); +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)); }); ``` @@ -683,17 +639,14 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var 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("==========================>deleteCallback=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => { + console.info("delete data: " + JSON.stringify(data)); }); ``` @@ -717,8 +670,8 @@ Updates data records in the database. This API uses an asynchronous callback to **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -727,14 +680,10 @@ const va = { "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("==========================>Called=======================>"); +}; +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)); }); ``` @@ -763,8 +712,8 @@ Updates data records in the database. This API uses a promise to return the resu **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -773,14 +722,10 @@ const va = { "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("==========================>updateCallback=======================>"); +}; +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => { + console.info("update data: " + JSON.stringify(data)); }); ``` @@ -804,19 +749,15 @@ Queries data in the database. This API uses an asynchronous callback to return t **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var 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("==========================>Called=======================>"); +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)); }); ``` @@ -847,27 +788,23 @@ Queries data in the database. This API uses a promise to return the result. **Example** ```ts -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var 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("==========================>queryCallback=======================>"); +var 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)); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap): Promise\ +call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void -Calls the extended API of the Data ability. This API uses a promise to return the result. +Calls an extended API of the DataAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -875,35 +812,35 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | -| arg | string | Yes |Parameter to pass. | +| arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | - -**Return value** - -| Type| Description| -|------ | ------- | -|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| +| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | **Example** ```ts import featureAbility from '@ohos.ability.featureAbility'; -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}).then((data) => { +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "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; + } console.info('Operation succeeded: ' + data); -}).catch((error) => { - console.error('Operation failed. Cause: ' + error); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void +call(uri: string, method: string, arg: string, extras: PacMap): Promise\ -Calls the extended API of the Data ability. This API uses an asynchronous callback to return the result. +Calls an extended API of the DataAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -911,24 +848,30 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | -| arg | string | Yes |Parameter to pass. | +| arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | -| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | + +**Return value** + +| Type| Description| +|------ | ------- | +|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| **Example** ```ts import featureAbility from '@ohos.ability.featureAbility'; -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("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; - } +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", + "method", "arg", {"key1":"value1"}).then((data) => { console.info('Operation succeeded: ' + data); +}).catch((error) => { + console.error('Operation failed. Cause: ' + error); }); ``` @@ -936,17 +879,17 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", " executeBatch(uri: string, operations: Array\, callback: AsyncCallback\>): void; -Operates data in the database. This API uses an asynchronous callback to return the result. +Operates data in the database in batches. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. | -| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | +| Name | Type | Mandatory| Description | +| ----------| ---------------------------------| ---- | ------------------------------------------------ | +| 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. | **Example** @@ -955,7 +898,9 @@ 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"); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + err); @@ -969,7 +914,7 @@ dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbi executeBatch(uri: string, operations: Array\): Promise\>; -Operates data in the database. This API uses a promise to return the result. +Operates data in the database in batches. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -977,14 +922,14 @@ Operates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | -------------------------------| ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | A list of data operations on the database. | +| 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** | Type| Description| |------ | ------- | -|Promise\> | Callback used to return the result of each operation in the **DataAbilityResult** array.| +|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| **Example** @@ -993,8 +938,10 @@ import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility",op ).then((data) => { +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => { console.info('Operation succeeded: ' + data); }).catch((error) => { console.error('Operation failed. Cause: ' + error); 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 30148ab3a64188abe2aef5a8c5cf2814f297da3e..0b96b8caa97bb28e7515bbc00ee1d7852ad2d21a 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 @@ -1,6 +1,6 @@ # DataAbilityOperation -The **DataAbilityOperation** module defines the operation on Data abilities. +The **DataAbilityOperation** module defines the operation on DataAbilities. It can be used as an input parameter of [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to specify the database operation information. > **NOTE** > @@ -11,56 +11,11 @@ The **DataAbilityOperation** module defines the operation on Data abilities. | Name | Template | Mandatory| Description | | -------- | -------- | --------| -------- | -| uri | string | Yes | URI of the Data ability. 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. | -| predicates? | dataAbility.DataAbilityPredicates | No | Predicates to set. If no predicate is set, all data records are displayed. | -| predicatesBackReferences? | Map\ | No | Back references of the predicates. | -| interrupted? | boolean | No | Whether batch operations can be interrupted. | -| expectedCount? | number | No | Expected number of rows to be updated or deleted. | - -**Example** -```ts -import featureAbility from '@ohos.ability.featureAbility' - -let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); -let DAHelper; -try { - DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); - if(DAHelper == null){ - console.error('DAHelper is null'); - return; - } -} catch (err) { - console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); - return; -} - -let valueBucket = { - "name": "DataAbilityHelperTest", - "age": 24, - "salary": 2024.20, -}; -let dataAbilityOperation = { - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true -} -let operations = [ - dataAbilityOperation -]; -try { - DAHelper.executeBatch(dataAbilityUri, operations, - (err, data) => { - console.log("executeBatch, data: " + JSON.stringify(data)); - } - ); -} catch (err) { - console.error('executeBatch fail: ' + JSON.stringify(err)); -} -``` +| 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. | +| predicates? | dataAbility.DataAbilityPredicates | No | Predicates to set. If no predicate is set, all data records are displayed. | +| predicatesBackReferences? | Map\ | No | Back references of the predicates. | +| interrupted? | boolean | No | Whether batch operations can be interrupted. | +| expectedCount? | number | No | Expected number of rows to be updated or deleted. | 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 fe602f38efcbcbb8619a29e1d05c3a6f92bf2635..49b14bebedfaa76b495e8a127e3f4bd243c649b7 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 @@ -1,6 +1,6 @@ # DataAbilityResult -The **DataAbilityResult** module defines the operation result on Data abilities. +The **DataAbilityResult** module defines the operation result on DataAbilities. When you call [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to operate the database, the operation result is returned through the **DataAbilityResult** object. > **NOTE** > @@ -11,63 +11,67 @@ The **DataAbilityResult** module defines the operation result on Data abilities. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| uri? | string | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| count? | number | No | Number of rows affected by the operation. | +| 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' -let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); -let DAHelper; -try { - DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); - if(DAHelper == null){ - console.error('DAHelper is null'); +// Perform database operations in batches. +function executeBatchOperation() { + let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); + let DAHelper; + try { + DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); + if (DAHelper == null) { + console.error('DAHelper is null'); + return; + } + } catch (err) { + console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); return; } -} catch (err) { - console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); - return; -} -let valueBucket = { - "name": "DataAbilityHelperTest", - "age": 24, - "salary": 2024.20, -}; -let operations = [ -{ - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true, -}, -{ - uri: dataAbilityUri, - type: featureAbility.DataAbilityOperationType.TYPE_INSERT, - valuesBucket: valueBucket, - predicates: null, - expectedCount: 1, - PredicatesBackReferences: {}, - interrupted: true, -} -]; + let valueBucket = { + "name": "DataAbilityHelperTest", + "age": 24, + "salary": 2024.20, + }; + let operations = [ + { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, + }, + { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, + } + ]; -try { - let promise = 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); - } - }).catch(err => { + try { + 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); + } + }).catch(err => { + console.error('executeBatch error: ' + JSON.stringify(err)); + }); + } catch (err) { console.error('executeBatch error: ' + JSON.stringify(err)); - }); -} catch (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 bbb025920d5a49ec02cc9fc84fed7c1bee8e6fca..71b8d529703d28e01072d8f18f92ebe30b82c556 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 @@ -1,6 +1,6 @@ # StartAbilityParameter -The **StartAbilityParameter** module defines the parameters for starting an ability. +The **StartAbilityParameter** module defines the parameters for starting an ability. The parameters can be used as input parameters in [startAbility](js-apis-ability-featureAbility.md#featureabilitystartability) to start the specified ability. > **NOTE** > @@ -11,8 +11,8 @@ The **StartAbilityParameter** module defines the parameters for starting an abil | Name | Type | Mandatory | Description | | ------------------- | -------- | ---- | -------------------------------------- | -| want | [Want](js-apis-application-want.md)| Yes | Information about the ability to start. | -| abilityStartSetting | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| +| want | [Want](js-apis-application-want.md)| Yes | Want information about the target ability. | +| abilityStartSetting | {[key: string]: any} | No | Special attribute of the target ability. This attribute can be passed in the call.| **Example** ```ts @@ -20,7 +20,7 @@ import featureAbility from '@ohos.ability.featureAbility' let Want = { bundleName: "com.example.abilityStartSettingApp2", - abilityName: "com.example.abilityStartSettingApp.MainAbility", + abilityName: "com.example.abilityStartSettingApp.EntryAbility", } let abilityStartSetting ={ @@ -31,13 +31,15 @@ let abilityStartSetting ={ } let startAbilityParameter = { - want:Want, - abilityStartSetting:abilityStartSetting + want : Want, + abilityStartSetting : abilityStartSetting } -featureAbility.startAbility(startAbilityParameter, (err,data)=>{ - console.log('errCode : ' + JSON.stringify(err)); - console.log('data : ' + JSON.stringify(data)); +try { + featureAbility.startAbility(startAbilityParameter, (err, data) => { + console.log('errCode : ' + JSON.stringify(err)); + console.log('data : ' + JSON.stringify(data)); + }); } catch(error) { console.log("startAbility error: " + JSON.stringify(error)); } diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md index 4eea38a4e28c3e344a8ecdc60118af0fe93ddf19..afb331b3fc2cb610025dd741e94abe0392fe4a5b 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 @@ -1,6 +1,6 @@ # Want -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a 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. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to specify a 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. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. > **NOTE** > @@ -10,56 +10,62 @@ Want is a carrier for information transfer between objects (application componen | Name | Type | Mandatory| Description | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | string | No | ID of the device running the ability. | -| bundleName | string | No | Bundle name of the application. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| 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#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. | +| 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. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | | moduleName9+ | string | No | Module to which the ability belongs.| **Example** -- Basic usage +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). ```ts - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry" // moduleName is optional. - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + let want = { + "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) + }) ``` -- Passing a file descriptor (FD) +- Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility): ```ts - import fileio from '@ohos.fileio'; - var fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); - } - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName is optional. - "parameters": { - "keyFd":{"type":"FD", "value":fd} - } - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. - console.log("error.code = " + error.code) - }) + import fileio from '@ohos.fileio'; + + // ... + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + 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) + }) + // ... ``` - + +- For more details and examples, see [Want](../../application-models/want-overview.md). + + diff --git a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md index a8eb10e600ef981de57a8acc227b1b6371efde26..39c846bb6e96a2e8db53b71c6685e3e1ce3a4579 100644 --- a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md @@ -1,24 +1,15 @@ # AppVersionInfo -The **AppVersionInfo** module defines the application version information. +The **AppVersionInfo** module defines the application version information. You can use [getAppVersionInfo](js-apis-inner-app-context.md#contextgetappversioninfo7) to obtain the version information of the current application. -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +> **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. -| Name | Type | Readable | Writable | Description | -| ----------- | ------ | ---- | ---- | ------- | -| appName | string | Yes | No | Module name. | -| versionCode | number | Yes | No | Module description.| -| versionName | string | Yes | No | Module description ID.| +**System capability**: SystemCapability.Ability.AbilityRuntime.Core -**Example** -```ts -let appName; -let versionCode; -let versionName; -this.context.getAppVersionInfo((error, data) => { - console.info('getAppVersionInfo data is:' + JSON.stringify(data)); - appName = data.appName; - versionCode = data.versionCode; - versionName = data.versionName; -}); -``` +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------- | +| appName | string | Yes | No | Application name. | +| versionCode | number | Yes | No | Application version code.| +| versionName | string | Yes | No | Application version name. | 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 84b46fd028782c8517e3c6aca5bad324c8eac179..ec729194807c24ea49b7b117cb308628c031a75a 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 @@ -5,11 +5,12 @@ The **Context** module provides context for abilities or applications. It allows > **NOTE** > > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. ## Usage -The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: +The **Context** object is created in a **featureAbility** and returned through its [getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext) API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: ```ts import featureAbility from '@ohos.ability.featureAbility'; @@ -93,14 +94,15 @@ 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'; +import bundle from '@ohos.bundle.bundleManager'; var context = featureAbility.getContext(); bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ - context.verifyPermission("com.example.permission", {uid:datainfo.uid}, (err, data) =>{ + context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); }); ``` +For details about **getBundleInfo** in the sample code, see [bundleManager](js-apis-bundleManager.md). @@ -250,7 +252,7 @@ Obtains information about the current application. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ------------ | -| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information.| +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Yes | Callback used to return the application information.| **Example** @@ -352,7 +354,7 @@ Obtains the display orientation of this ability. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Yes | Callback used to return the display orientation.| **Example** @@ -376,7 +378,7 @@ Obtains the display orientation of this ability. This API uses a promise to retu | Type | Description | | ---------------------------------------- | --------- | -| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Promise\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Promise used to return the display orientation.| **Example** @@ -448,7 +450,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | ------------ | -| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.| +| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | Display orientation to set.| | callback | AsyncCallback\ | Yes | Callback used to return the display orientation. | **Example** @@ -457,7 +459,7 @@ Sets the display orientation for this ability. This API uses an asynchronous cal import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -var orientation=bundle.DisplayOrientation.UNSPECIFIED +var orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation, (err) => { console.info("setDisplayOrientation err: " + JSON.stringify(err)); }); @@ -475,7 +477,7 @@ Sets the display orientation for this ability. This API uses a promise to return | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | +| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | | Promise\ | Promise used to return the display orientation. | **Example** @@ -484,7 +486,7 @@ Sets the display orientation for this ability. This API uses a promise to return import featureAbility from '@ohos.ability.featureAbility'; import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -var orientation=bundle.DisplayOrientation.UNSPECIFIED +var orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation).then((data) => { console.info("setDisplayOrientation data: " + JSON.stringify(data)); }); @@ -510,7 +512,7 @@ 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 +var show = true; context.setShowOnLockScreen(show, (err) => { console.info("setShowOnLockScreen err: " + JSON.stringify(err)); }); @@ -541,7 +543,7 @@ 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 +var show = true; context.setShowOnLockScreen(show).then((data) => { console.info("setShowOnLockScreen data: " + JSON.stringify(data)); }); @@ -567,7 +569,7 @@ 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 +var wakeUp = true; context.setWakeUpScreen(wakeUp, (err) => { console.info("setWakeUpScreen err: " + JSON.stringify(err)); }); @@ -598,7 +600,7 @@ 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 +var wakeUp = true; context.setWakeUpScreen(wakeUp).then((data) => { console.info("setWakeUpScreen data: " + JSON.stringify(data)); }); @@ -673,7 +675,7 @@ This API is available only to Page abilities. | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[ElementName](js-apis-bundle-ElementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** @@ -701,7 +703,7 @@ This API is available only to Page abilities. | Type | Description | | --------------------- | ------------------------------------ | -| Promise\<[ElementName](js-apis-bundle-ElementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| **Example** @@ -769,7 +771,7 @@ context.getProcessName().then((data) => { getCallingBundle(callback: AsyncCallback\): void -Obtains the bundle name of the calling ability. This API uses an asynchronous callback to return the result. +Obtains the bundle name of the caller ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -795,7 +797,7 @@ context.getCallingBundle((err, data) => { getCallingBundle(): Promise\ -Obtains the bundle name of the calling ability. This API uses a promise to return the result. +Obtains the bundle name of the caller ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -925,7 +927,7 @@ If the distributed file path does not exist, the system will create one and retu | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| +| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path.
If the path does not exist, the system will create one and return the created path.| **Example** @@ -951,7 +953,7 @@ If the distributed file path does not exist, the system will create one and retu | Type | Description | | ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.| +| Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a path will be created.| **Example** @@ -1023,7 +1025,7 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| +| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** @@ -1047,7 +1049,7 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to | Type | Description | | ---------------------------------------- | ------------------ | -| Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| +| Promise\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| **Example** @@ -1119,7 +1121,7 @@ Obtains information about this ability. This API uses an asynchronous callback t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| +| callback | AsyncCallback\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** @@ -1143,7 +1145,7 @@ Obtains information about this ability. This API uses a promise to return the re | Type | Description | | ---------------------------------------- | ------------------ | -| Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.| +| Promise\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Promise used to return the ability information.| **Example** 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 0da1d45efcd3ae56473a37ec28da8e056dbf3def..351d6ad145824d0eba37a3a1eadc846034763c97 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 @@ -1,13 +1,19 @@ # ProcessInfo -The **ProcessInfo** module defines process information. +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. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| processName | string | Yes| No| Process name.| +| pid | number | Yes| No| Process ID.| +| processName | string | Yes| No| Process name.| **Example** ```ts 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 71163a1d857e897306e1c90ed3262943fe898e98..ad4f7e19a9fd40b82684c0acc11a458073bbb16b 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 @@ -8,14 +8,11 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in ## Usage -The ability delegator can be obtained by calling **getAbilityDelegator** in **AbilityDelegatorRegistry**. +An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**. ```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); - +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ## AbilityDelegator @@ -1044,7 +1041,7 @@ abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => { console.info("waitAbilityStageMonitor callback"); }); ``` - + ### waitAbilityStageMonitor9+ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\; 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 97ecb0ed8bf03802ac2a8e1dcab4516d45acc36d..a5f131c3e02071f3d55cbfdc73955ffef42889d3 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 @@ -1,6 +1,6 @@ # AbilityDelegatorArgs -The **AbilityDelegatorArgs** module provides a global register to store the registered **AbilityDelegator** and **AbilityDelegatorArgs** instances during application startup. +The **AbilityDelegatorArgs** module provides APIs to obtain an **AbilityDelegatorArgs** object during the execution of test cases. > **NOTE** > @@ -8,7 +8,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi ## Usage -The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. +An **AbilityDelegatorArgs** object is obtained by calling [getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments) in **AbilityDelegatorRegistry**. ## AbilityDelegatorArgs 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 7aef3303481563008a79f7f8a43be66cbbbfa7fa..d8726205b8caec547f270e8efe6472e37cd99eb4 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 @@ -8,7 +8,7 @@ The **AbilityMonitor** module provides monitors for abilities that meet specifie ## Usage -The ability monitor can be set by calling **addAbilityMonitor** in **abilityDelegator**. +**AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability. ## AbilityMonitor @@ -31,7 +31,6 @@ Describes an ability monitor. ```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; function onAbilityCreateCallback(data) { console.info("onAbilityCreateCallback"); @@ -42,7 +41,7 @@ var monitor = { onAbilityCreate: onAbilityCreateCallback } -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.addAbilityMonitor(monitor, (err : any) => { console.info("addAbilityMonitor callback"); }); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md index 4f553001c63881441b23a3ce42ba429497775b2d..62b1f7e1fae204f2e6b1f6dcdc76521da3c51777 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 @@ -8,7 +8,7 @@ The **AbilityRunningInfo** module defines the running information and state of a ## Usage -The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. +The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**. ## Attributes 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 99a2453d84124b1eee3d7dc6a5aa7c2d8e5b8663..79f750797c12bfd9c323e2f613650c016ea2930b 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 @@ -26,7 +26,7 @@ class MyAbilityStage extends AbilityStage { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| +| currentHapModuleInfo | HapModuleInfo | 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-abilityStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md index b86ba33545181076833461e4a63650290d15be9b..eb539bd981610af81a6e9598bcab3da8dc3f9279 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md @@ -1,33 +1,36 @@ # AbilityStateData -The **AbilityStateData** module defines the ability state information. +The **AbilityStateData** module defines the ability state information, which can be obtained through the **onAbilityStateChanged** lifecycle callback of [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md). The callback can be invoked after a lifecycle change listener is registered through [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8). **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | | pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of an application. | +| bundleName8+ | string | Yes | No | Bundle name. | | abilityName8+ | string | Yes | No | Ability name. | | uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | Ability state. | +| state8+ | number | Yes | No | [Ability state](#ability-states). | | moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | -| abilityType8+ | string | Yes | No | Ability type. | +| abilityType8+ | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.| -**Example** -```ts -import appManager from "@ohos.application.appManager" +#### Ability States -appManager.getForegroundApplications((error, data) => { - for(let i=0; i8+
| string | No | Bundle name of the application. | -| uid8+ | number | No | User ID.| -| state8+ | number | No | Application state.| +| Name | Type | Mandatory | Description | +| ------------------------- | ------ | ---- | --------- | +| bundleName8+ | string | No | Bundle name.| +| uid8+ | number | No | UID of the application. | +| state8+ | number | No | Application state.
**0**: The application is being initialized.
**1**: The application has been initialized and is ready.
**2**: The application is running in the foreground.
**3**: The application is having the focus. (This state is reserved.)
**4**: The application is running in the background.
**5**: The application has exited.| **Example** + ```ts -import appManager from "@ohos.application.appManager" +import appManager from "@ohos.app.ability.appManager" -appManager.getForegroundApplications((error, data) => { - for(let i=0; i { + if (error && error.code) { + 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); + } + }); +} ``` 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 13242ab621b59cba86d896fd2dfadab8dc9ed98c..73b2a329f018d64bf93ac8f64ece86792e4eff59 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 @@ -38,11 +38,11 @@ Registers a listener to monitor the ability lifecycle of the application. **Example** ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var lifecycleId; -export default class MyAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate() { console.log("MyAbility onCreate") let AbilityLifecycleCallback = { @@ -105,11 +105,11 @@ Deregisters the listener that monitors the ability lifecycle of the application. **Example** ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var lifecycleId; -export default class MyAbility extends Ability { +export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); console.log("stage applicationContext: " + JSON.stringify(applicationContext)); @@ -143,11 +143,11 @@ Registers a listener for system environment changes. This API uses an asynchrono **Example** ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var callbackId; -export default class MyAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate() { console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); @@ -155,6 +155,9 @@ export default class MyAbility extends Ability { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); }, + onMemoryLevel(level){ + console.log("onMemoryLevel level:" + level); + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; @@ -183,11 +186,11 @@ Deregisters the listener for system environment changes. This API uses an asynch **Example** ```ts -import Ability from "@ohos.application.Ability"; +import UIAbility from '@ohos.app.ability.UIAbility'; var callbackId; -export default class MyAbility extends Ability { +export default class EntryAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { 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 15925c305ab652b9b4426c169b430af358e89331..e6d3137582ee3b485e4a342a4a5a3b6b5473ed32 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 @@ -1,18 +1,18 @@ # ApplicationStateObserver -The **ApplicationStateObserver** module defines the listener to observe the application state. +The **ApplicationStateObserver** module defines an observer to listen for application state changes. It can be used as an input parameter in [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8) to listen for lifecycle changes of the current application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| onForegroundApplicationChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | -| onAbilityStateChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | -| onProcessCreated8+ | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | -| onProcessDied8+ | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | -| onProcessStateChanged8+ | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | +| Name | | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | ------------------------- | +| onForegroundApplicationChanged8+ | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| onAbilityStateChanged8+ | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| onProcessCreated8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| onProcessDied8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | +| onProcessStateChanged8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | **Example** ```ts 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 24b284ed85986d96e58afba9c2bc4ff75804ebca..3c0e5e3806181cbff0492cfe4faa387f315e516b 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 @@ -1,23 +1,28 @@ # BaseContext -The abstract class **BaseContext** specifies whether its child class **Context** is used for the stage model or FA model. +**BaseContext** is an abstract class that specifies whether a child class **Context** is used for the stage model or FA model. It is the parent class for all types of **Context**. > **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. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | -| stageMode | boolean | Yes | Yes | Whether the context is used for the stage model.| +| stageMode | boolean | Yes | Yes | Whether the child class **Context** is used for the stage model.
**true**: used for the stage model.
**false**: used for the FA model.| **Example** - - ```ts - class MyContext extends BaseContext { - constructor(stageMode) { - this.stageMode = stageMode; - } - } - ``` + +Take the stage model as an example. You can access the **stageMode** field through **UIAbilityContext**. + +```ts +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); + } +} +``` 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 15e249798f9f731427b8b514b020abde8e924053..2a4fe5eaaf05dd8f7e6c907966a8a411382a6daa 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 @@ -1,11 +1,11 @@ # Context -The **Context** module provides context for abilities or applications. It allows access to application-specific resources, as well as permission requests and verification. +The **Context** module provides context for abilities or applications. It allows access to application-specific resources. > **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. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module can be used only in the stage model. ## Attributes @@ -13,8 +13,8 @@ The **Context** module provides context for abilities or applications. It allows | Name | Type | Readable | Writable | Description | | ----------- | ------ | ---- | ---- | ------- | -| resourceManager | resmgr.ResourceManager | Yes | No | Object for resource management. | -| applicationInfo | ApplicationInfo | Yes | No | Application information.| +| resourceManager | resmgr.[ResourceManager](js-apis-resource-manager.md) | Yes | No | Object for resource management. | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information.| | cacheDir | string | Yes | No | Cache directory.| | tempDir | string | Yes | No | Temporary directory.| | filesDir | string | Yes | No | File directory.| @@ -25,20 +25,21 @@ The **Context** module provides context for abilities or applications. It allows | eventHub | string | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| | area | [AreaMode](#areamode) | Yes | No | Area in which the file to be access is located.| - ## Context.createBundleContext createBundleContext(bundleName: string): Context; Creates the context based on the bundle name. +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| **Return value** @@ -46,10 +47,24 @@ Creates the context based on the bundle name. | -------- | -------- | | Context | Context created.| +**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 -let bundleContext = this.context.createBundleContext("com.example.test"); +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)); +} ``` ## Context.createModuleContext @@ -72,10 +87,24 @@ Creates the context based on the module name. | -------- | -------- | | Context | Context created.| +**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 -let moduleContext = this.context.createModuleContext("entry"); +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)); +} ``` createModuleContext(bundleName: string, moduleName: string): Context; @@ -88,7 +117,7 @@ Creates the context based on the bundle name and module name. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name.| | moduleName | string | Yes | Module name.| **Return value** @@ -97,17 +126,31 @@ Creates the context based on the bundle name and module name. | -------- | -------- | | Context | Context created.| +**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 -let moduleContext = this.context.createModuleContext("com.example.test", "entry"); +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)); +} ``` ## Context.getApplicationContext getApplicationContext(): ApplicationContext; -Obtains the application context. +Obtains the context of this application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -115,12 +158,18 @@ Obtains the application context. | Type| Description| | -------- | -------- | -| Context | Application context obtained.| +| [ApplicationContext](js-apis-inner-application-applicationContext.md) | Application context obtained.| **Example** ```ts -let applicationContext = this.context.getApplicationContext(); +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)); +} ``` ## AreaMode @@ -129,7 +178,7 @@ Enumerates the areas in which the file to be access can be located. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| EL1 | 0 | Device-level encryption area.| -| EL2 | 1 | User credential encryption area.| +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md index 93d138db23255a3c312e55a423411cdb29f211e5..b67c612c1b3b6dd82537b6dd5e6e7fcad2d6bdcb 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 @@ -1,37 +1,46 @@ # ContinueCallback -The **ContinueCallback** module defines the callback invoked when the mission continuation is complete. +The **ContinueCallback** module defines the callback function that indicates the result of mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission). + +## ContinueCallback.onContinueDone + +onContinueDone(result: number): void; + +Called when the mission continuation is complete. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -| Name | Type | Readable | Writable | Description | -| --------------------- | -------- | ---- | ---- | ------------------ | -| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. | +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | result | number | No| Mission continuation result.| **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager'; + import distributedMissionManager from '@ohos.distributedMissionManager' let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", - missionId: 123, - wantParam: { - "key":"value" - } + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } }; let continueCallback = { onContinueDone(result) { console.log('onContinueDone, result: ' + JSON.stringify(result)); } - } + }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { - if (error.code != 0) { - console.error('continueMission failed, cause: ' + JSON.stringify(error)) - } - console.info('continueMission finished') + if (error && error.code) { + console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + console.log('continueMission finished'); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md index b42044ef893ebd23f97549ad378f21dcf8067c93..5582132e3f610a76175cbb73796b6283498c4395 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 @@ -1,6 +1,6 @@ # ContinueDeviceInfo -The **ContinueDeviceInfo** module defines the parameters required for mission continuation. +The **ContinueDeviceInfo** module defines the parameters required for initiating mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -14,27 +14,28 @@ The **ContinueDeviceInfo** module defines the parameters required for mission co **Example** ```ts - import distributedMissionManager from '@ohos.distributedMissionManager'; + import distributedMissionManager from '@ohos.distributedMissionManager' let continueDeviceInfo = { - srcDeviceId: "123", - dstDeviceId: "456", - missionId: 123, - wantParam: { - "key":"value" - } + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } }; let continueCallback = { onContinueDone(result) { console.log('onContinueDone, result: ' + JSON.stringify(result)); } - } + }; distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { - if (error.code != 0) { - console.error('continueMission failed, cause: ' + JSON.stringify(error)) - } - console.info('continueMission finished') + if (error && error.code) { + console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + console.log('continueMission finished'); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md index 056a2313dd1aeffdcd69812c491e9e03a77f5f41..271f2697803dde9d0b3f78c3bb661a03d925b95e 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 @@ -1,8 +1,8 @@ # ErrorObserver -The **ErrorObserver** module defines the listener to observe errors. +The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron) to listen for errors that occur in the current application. -## onUnhandledException +## ErrorObserver.onUnhandledException onUnhandledException(errMsg: string): void; @@ -16,15 +16,21 @@ Called when an unhandled exception occurs in the JS runtime. | -------- | -------- | -------- | -------- | | errMsg | string | No| Message and error stack trace about the exception.| -**Example** +**Example** ```ts -import errorManager from '@ohos.application.errorManager'; +import errorManager from '@ohos.app.ability.errorManager' let observer = { onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ' + JSON.stringify(errorMsg)); + console.log('HXW onUnhandledException, errorMsg: ', errorMsg); } } -errorManager.registerErrorObserver(observer) + +try { + errorManager.on("error", observer); +} catch (error) { + console.log('registerErrorObserver' + ' failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md index 9c45684cd9faaf03a8de66ba73541ae75ded9cc3..8b580177c7622b33b0d2c06749a928e825ae84bc 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 @@ -3,22 +3,24 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and trigger events. > **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. +> +> - 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 any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. +Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **UIAbility** instance. ```ts -import Ability from '@ohos.application.Ability'; -export default class MainAbility extends Ability { - func1(){ - console.log("func1 is called"); +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + eventFunc(){ + console.log("eventFunc is called"); } + onForeground() { - this.context.eventHub.on("123", this.func1); + this.context.eventHub.on("myEvent", this.eventFunc); } } ``` @@ -38,34 +40,37 @@ Subscribes to an event. | event | string | Yes| Event name.| | callback | Function | Yes| Callback invoked when the event is triggered.| -**Example** - - ```ts - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", () => { - console.log("call anonymous func 1"); - }); - // Result - // func1 is called - // call anonymous func 1 - this.context.eventHub.emit("123"); - } - func1() { - console.log("func1 is called"); - } - } - ``` +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +export default class EntryAbility extends UIAbility { + onForeground() { + 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"); + }); + // Result + // eventFunc is called + // call anonymous eventFunc + this.context.eventHub.emit("myEvent"); + } + + eventFunc() { + console.log("eventFunc is called"); + } +} +``` ## EventHub.off off(event: string, callback?: Function): void; -Unsubscribes from an event. If **callback** is specified, this API unsubscribes from the specified callback. If **callback** is not specified, this API unsubscribes from all callbacks in the event. +Unsubscribes from an event. + - If **callback** is specified, this API unsubscribes from the given event with the specified callback. + - If **callback** is not specified, this API unsubscribes from the given event with all callbacks. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -74,30 +79,31 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| Event name.| -| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| - -**Example** - - ```ts - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.off("123", this.func1); // Unsubscribe from func1. - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", this.func2); - this.context.eventHub.off("123"); // Unsubscribe from func1 and func2. - } - func1() { - console.log("func1 is called"); - } - func2() { - console.log("func2 is called"); - } - } - ``` +| callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.| + +**Example** + +```ts +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). + } + + eventFunc1() { + console.log("eventFunc1 is called"); + } + eventFunc2() { + console.log("eventFunc2 is called"); + } +} +``` ## EventHub.emit @@ -114,26 +120,27 @@ Triggers an event. | event | string | Yes| Event name.| | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| -**Example** - - ```ts - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - // Result - // func1 is called,undefined,undefined - this.context.eventHub.emit("123"); - // Result - // func1 is called,1,undefined - this.context.eventHub.emit("123", 1); - // Result - // func1 is called,1,2 - this.context.eventHub.emit("123", 1, 2); - } - func1(a, b) { - console.log("func1 is called," + a + "," + b); - } - } - ``` +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc); + // Result + // eventFunc is called,undefined,undefined + this.context.eventHub.emit("myEvent"); + // Result + // eventFunc is called,1,undefined + this.context.eventHub.emit("myEvent", 1); + // Result + // eventFunc is called,1,2 + this.context.eventHub.emit("myEvent", 1, 2); + } + + eventFunc(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 1ed64e2a07cc8e92a7d8310d4fb4d0c42d36ff5b..a855d9577c9ef364caa7436a89983ca58d320d3c 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 @@ -5,7 +5,7 @@ The **ExtensionContext** module, inherited from **Context**, implements the cont This module provides APIs for accessing resources of a specific Extension ability. An Extension ability can use the context directly provided by **ExtensionContext** or that extended from **ExtensionContext**. For example, **ServiceExtension** uses [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md), which extends the capabilities of starting, stopping, binding, and unbinding abilities based on **ExtensionContext**. > **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. @@ -61,10 +61,11 @@ export default class TheServiceExtension extends ServiceExtension { Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. ```ts -import Ability from '@ohos.app.ability.Ability' -export default class MainAbility extends Ability { +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate"); + console.log("[Demo] EntryAbility onCreate"); let wantExt = { deviceId: "", bundleName: "com.example.TheServiceExtension", 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 9184ae6ce0f0b4b8dee355d96a4c28cf84013ef2..9485de9efd0dc76d78a905725fb742225b50340f 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 @@ -1,15 +1,15 @@ # ExtensionRunningInfo -The **ExtensionRunningInfo** module provides running information and states for Extension abilities. +The **ExtensionRunningInfo** module encapsulates ExtensionAbility running information, which can be obtained through [getExtensionRunningInfos](js-apis-app-ability-abilityManager.md#getextensionrunninginfos). > **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 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. +> - This module is marked as @systemapi and not visible to third-party applications. ## Usage -The Extension ability running information is obtained through an **abilityManager** instance. +Import the **abilityManager** module and obtain the ExtensionAbility running information by calling the method in the **abilityManager** module. ## Attributes @@ -17,29 +17,37 @@ The Extension ability running information is obtained through an **abilityManage | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an Extension ability.| +| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes| No| ExtensionAbility information.| | pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| +| uid | number | Yes| No| UID of the application.| | processName | string | Yes| No| Process name.| -| startTime | number | Yes| No| Start time of the Extension ability.| +| startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.| | clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md) | Yes| No| Extension ability type.| +| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes| No| ExtensionAbility type.| **Example** ```ts -import abilityManager from '@ohos.application.abilityManager'; -let upperLimit=1; -abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); - for (let i=0; i { + if (error && error.code) { + console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + + for (let i = 0; i < data.length; i++) { + let extensionRunningInfo = data[i]; + console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension)); + console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid)); + console.log("extensionRunningInfo.uid: " + JSON.stringify(extensionRunningInfo.uid)); + console.log("extensionRunningInfo.processName: " + JSON.stringify(extensionRunningInfo.processName)); + console.log("extensionRunningInfo.startTime: " + JSON.stringify(extensionRunningInfo.startTime)); + console.log("extensionRunningInfo.clientPackage: " + JSON.stringify(extensionRunningInfo.clientPackage)); + console.log("extensionRunningInfo.type: " + JSON.stringify(extensionRunningInfo.type)); + } + }); +} ``` 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 bc9cb28c60e10b88b377cece605e51730cbea3cd..d888ccdc51bef996937e9d2e6ef891980ffe457c 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 @@ -1,8 +1,8 @@ # FormExtensionContext -The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities. +The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for FormExtensionAbilities. -You can use the APIs of this module to start Form Extension abilities. +You can use the APIs of this module to start FormExtensionAbilities. > **NOTE** > @@ -11,21 +11,24 @@ You can use the APIs of this module to start Form Extension abilities. ## Usage -Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtension** instance. +Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtensionAbility** instance. ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; + export default class MyFormExtensionAbility extends FormExtensionAbility { - onAddForm() { - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -} + onAddForm(want) { + let formContext = this.context; // Obtain a FormExtensionContext instance. + // ... + let dataObj1 = { + temperature: "11c", + "time": "11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +}; ``` ## startAbility @@ -48,23 +51,29 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Example** ```ts -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want, (error, data) => { - if (error) { - console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); - } else { - console.log(`FormExtensionContext startAbility success`); - } -}) +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); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "EntryAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want, (error, data) => { + if (error) { + console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + } else { + console.log('FormExtensionContext startAbility success'); + } + }); + } +}; ``` ## startAbility @@ -87,24 +96,30 @@ Starts an ability. This API uses a promise to return the result. | Type | Description | | ------------ | ---------------------------------- | -| Promise<void< | Promise that returns no value.| +| Promise<void> | Promise that returns no value.| **Example** ```ts -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want).then(() => { - console.info("StartAbility Success"); -}).catch((error) => { - console.info("StartAbility failed"); -}); +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); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "EntryAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want).then(() => { + console.info("StartAbility Success"); + }).catch((error) => { + console.info("StartAbility failed"); + }); + } +}; ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md index e56a2a43e4603f1b2f8e0e2a9dfbaf303e938f7b..7ccae03fa363d0850338d07f1318a377f10fc293 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 @@ -1,14 +1,14 @@ -# MissionCallbacks +# MissionCallback -The **MissionCallbacks** module defines the callbacks that can be registered as a mission status listener. +The **MissionCallback** module defines the callbacks invoked after synchronization starts. These callbacks can be used as input parameters in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -| Name | Template | Readable | Writable | Description | -| --------------------- | -------- | ---- | ---- | ------------------ | -| notifyMissionsChanged | function | Yes | No | Callback used to notify the mission change event and return the device ID. | -| notifySnapshot | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID.| -| notifyNetDisconnect | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.| +| Name | Template | Readable| Writable| Description | +| ---------------------------------------------------- | -------- | ---- | ---- | ---------------------------------- | +| notifyMissionsChanged(deviceId: string) | function | Yes | No | Callback used to notify the mission change event and return the device ID. | +| notifySnapshot(deviceId: string, mission: number) | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID. | +| notifyNetDisconnect(deviceId: string, state: number) | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.| **Example** ```ts @@ -21,12 +21,12 @@ let missionCallback = { notifyMissionsChanged: function (deviceId) { console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); }, - notifySnapshot: function (mission, deviceId) { - console.log("notifySnapshot mission: " + JSON.stringify(mission)); + notifySnapshot: function (deviceId, mission) { console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + console.log("notifySnapshot mission: " + JSON.stringify(mission)); }, - notifyNetDisconnect: function (mission, state) { - console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); + notifyNetDisconnect: function (deviceId, state) { + console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId)); console.log("notifyNetDisconnect state: " + JSON.stringify(state)); } }; 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 028e5dafadb2c6b5c63486f82e08acb2e1f601c5..9157fc697346087895870a5bbd6e4a0368d6bde7 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 @@ -1,6 +1,6 @@ # MissionDeviceInfo -The **MissionDeviceInfo** module defines the parameters required for registering a listener. +The **MissionDeviceInfo** module defines the parameters required for registering a listener. It can be used as an input parameter in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission 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 5240d4229fb1222c91bcbddac116b26e23e69dd9..afefb70c5a3e0b0059e4712992c3f736516bc2f7 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 @@ -1,34 +1,45 @@ # MissionInfo -The **MissionInfo** module defines the mission information of an ability. +The **MissionInfo** module defines detailed information about a mission. The information can be obtained through [getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes| Yes| Mission ID.| -| runningState | number | Yes| Yes| Running state of the mission.| -| lockedState | boolean | Yes| Yes| Locked state of the mission.| -| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| -| want | [Want](js-apis-application-want.md) | Yes| Yes| Want information of the mission.| -| label | string | Yes| Yes| Label of the mission.| -| iconPath | string | Yes| Yes| Path of the mission icon.| -| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-application-want.md) | Yes| Yes| Want information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| **Example** ```ts -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.app.ability.missionManager' -missionManager.getMissionInfo("12345", 1, (error, data) => { - console.info('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); - console.info('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); - console.info('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); - console.info('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); - console.info('getMissionInfo want is:' + JSON.stringify(data.want)); - console.info('getMissionInfo label is:' + JSON.stringify(data.label)); - console.info('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); - console.info('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); -}); +try { + 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)); + 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)); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md index 1070334b0107b3e3e84101a287b7966f7e16dcff..a9f9e6cf9540c02ada58ea7e89f76b9c9c297efb 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 @@ -1,6 +1,6 @@ # MissionListener -The **MissionListener** module defines the listeners used to observe the mission status. +The **MissionListener** module defines the listeners used to observe the mission status. The listeners can be registered by using [on](js-apis-app-ability-missionManager.md#missionmanageron). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -16,7 +16,7 @@ The **MissionListener** module defines the listeners used to observe the mission **Example** ```ts -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.app.ability.missionManager' let listener = { onMissionCreated: function (mission) { @@ -38,5 +38,10 @@ let listener = { console.log("onMissionClosed mission: " + JSON.stringify(mission)); } }; -let listenerid = missionManager.registerMissionListener(listener); + +try { + let listenerId = missionManager.on("mission", listener); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md index 5dc8a425524082102b4a554e7b911a1e7a490e8b..9e2e2aa23a6589c0eb80075f8de60f65261e6903 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 @@ -1,6 +1,6 @@ # MissionParameter -The **MissionParameter** module defines the parameters required for mission synchronization. +The **MissionParameter** module defines the parameters required for mission synchronization. It can be used an input parameter in [startSyncRemoteMissions](js-apis-distributedMissionManager.md#distributedmissionmanagerstartsyncremotemissions). **System capability**: SystemCapability.Ability.AbilityRuntime.Mission 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 bac1c9f6c38951f0ba4f5ab25a7e07d7a9441dcd..a97f3b32b71f90078cb03f32fa46262f5cf6b770 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 @@ -1,6 +1,6 @@ # MissionSnapshot -The **MissionSnapshot** module provides the mission snapshot information of an ability. +The **MissionSnapshot** module defines the snapshot of a mission. The snapshot can be obtained through [getMissionSnapShot](js-apis-app-ability-missionManager.md#missionmanagergetmissionsnapshot). > **NOTE** > @@ -11,7 +11,7 @@ The **MissionSnapshot** module provides the mission snapshot information of an a | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | Yes| Yes| Information that matches an ability.| +| ability | ElementName | Yes| Yes| Ability information of the mission.| | snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.| ## How to Use @@ -20,19 +20,33 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** **Example** ```ts -import ElementName from '@ohos.bundle'; -import image from '@ohos.multimedia.image'; -import missionManager from '@ohos.application.missionManager'; - -missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) -}) + import ElementName from '@ohos.bundle'; + import image from '@ohos.multimedia.image'; + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getMissionSnapShot("", id, (err, snapshot) => { + if (err.code) { + console.log("getMissionInfos failed, err.code:" + JSON.stringify(err.code) + + "err.message:" + JSON.stringify(err.message)); + return; + } + + // Carry out normal service processing. + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + } catch (paramError) { + console.log("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 75d7312c7144f725e0d47e6aed6e3bc594ce3989..c6e91944c5ed16800f3a2a7785de5a5e60dc623a 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 @@ -1,6 +1,6 @@ # ProcessData -The **ProcessData** module defines process data. +The **ProcessData** module defines process data. If a lifecycle change listener is registered by calling [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8), the **onProcessCreated** callback in [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) is invoked when the lifecycle of an application or ability changes. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -10,9 +10,10 @@ The **ProcessData** module defines process data. | ----------------------- | ---------| ---- | ---- | ------------------------- | | pid8+ | number | Yes | No | Process ID. | | bundleName8+ | string | Yes | No | Bundle name of the application. | -| uid8+ | number | Yes | No | User ID. | -| isContinuousTask9+ | boolean | Yes | No | Whether the process is a continuous task. | -| isKeepAlive9+ | boolean | Yes | No | Whether the process remains active. | +| uid8+ | number | Yes | No | UID of the application. | +| isContinuousTask9+ | boolean | Yes | No | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. | +| isKeepAlive9+ | boolean | Yes | No | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. | +| state9+ | number | Yes | No | Application state. The value can be **0** (newly created), **2** (foreground), **4** (background), or **5** (terminated). | **Example** ```ts 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 8534ed198099f17a00769d2627349752a38aef62..0652791f728de12c144459146287ecbbb680480e 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 @@ -1,6 +1,6 @@ # ProcessRunningInfo -The **ProcessRunningInfo** module provides process running information. +The **ProcessRunningInfo** module defines the running information of a process. > **NOTE** > - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-inner-application-processRunningInformation.md) instead. @@ -19,12 +19,13 @@ The **ProcessRunningInfo** module provides process running information. ## Usage -The process running information is obtained through [getProcessRunningInfos](js-apis-application-appManager.md##appManager.getProcessRunningInfos(deprecated)). +The process running information is obtained by using [getProcessRunningInfos](js-apis-application-appManager.md#appmanagergetprocessrunninginfosdeprecated) in **appManager**. **Example** ```ts import appManager from '@ohos.application.appManager'; -app.getProcessRunningInfos().then((data) => { + +appManager.getProcessRunningInfos().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md index bae1a6f2761c1f8de4873875d0578819a43ddea2..a376446b2af90c8cc13f6eee80a10a5399dae041 100644 --- a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md @@ -1,6 +1,6 @@ # ProcessRunningInformation -The **ProcessRunningInformation** module provides process running information. +The **ProcessRunningInformation** module defines the running information of a process. > **NOTE** > @@ -8,12 +8,13 @@ The **ProcessRunningInformation** module provides process running information. ## How to Use -The process running information is obtained through [appManager](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9). +The process running information is obtained through [getProcessRunningInformation](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9) in **appManager**. ```ts import appManager from '@ohos.application.appManager'; -appManager.getProcessRunningInformation((error,data) => { - console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data)); + +appManager.getProcessRunningInformation((error, data) => { + console.log("error: " + error.code + " data: " + JSON.stringify(data)); }); ``` @@ -21,9 +22,9 @@ appManager.getProcessRunningInformation((error,data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| 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.| +| pid | number | Yes| No| Process ID.| +| 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.| 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 bfe660ebd6d4f0fb64a0380a3fee7b2470e9a3b3..ae6beb1357d9d25dfcd06cbcd1d65df660fa44bb 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 @@ -1,6 +1,6 @@ # ServiceExtensionContext -The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities. +The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for ServiceExtensionAbilities. You can use the APIs of this module to start, terminate, connect, and disconnect abilities. @@ -17,9 +17,9 @@ Before using the **ServiceExtensionContext** module, you must define a child cla import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; let context = undefined; - class MainAbility extends ServiceExtensionAbility { + class EntryAbility extends ServiceExtensionAbility { onCreate() { - context = this.context; + context = this.context; // Obtain a ServiceExtensionContext instance. } } ``` @@ -36,10 +36,10 @@ Starts an ability. This API uses an asynchronous callback to return the result. **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.| - | callback | AsyncCallback<void> | No| Callback used to return the result.| +| 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.| +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -103,16 +103,16 @@ Starts an ability. This API uses a promise to return the result. **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) | Yes| Parameters used for starting the ability.| +| 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) | Yes| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -214,8 +214,8 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0 @@ -245,6 +245,11 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< 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). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -287,8 +292,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -316,6 +321,11 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca 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). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -359,8 +369,8 @@ Starts an ability with the account ID and start options specified. This API uses ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -392,6 +402,11 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): 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). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -406,9 +421,9 @@ Starts an ability with the account ID specified. This API uses a promise to retu **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -440,8 +455,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -470,7 +485,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -505,8 +520,8 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -531,7 +546,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a new ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -545,9 +560,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -571,8 +586,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -597,9 +612,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +Starts a new 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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -637,8 +652,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -664,9 +679,9 @@ Starts a new Service Extension ability with the account ID specified. This API u startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +Starts a new ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**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 @@ -681,9 +696,9 @@ Starts a new Service Extension ability with the account ID specified. This API u **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -708,8 +723,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -735,7 +750,7 @@ Starts a new Service Extension ability with the account ID specified. This API u stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -767,8 +782,8 @@ Stops a Service Extension ability in the same application. This API uses an asyn ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -793,7 +808,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -807,9 +822,9 @@ Stops a Service Extension ability in the same application. This API uses a promi **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -830,8 +845,8 @@ Stops a Service Extension ability in the same application. This API uses a promi ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -856,9 +871,9 @@ Stops a Service Extension ability in the same application. This API uses a promi stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -892,8 +907,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -919,9 +934,9 @@ Stops a Service Extension ability in the same application with the account ID sp stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -936,9 +951,9 @@ Stops a Service Extension ability in the same application with the account ID sp **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -960,8 +975,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -995,9 +1010,9 @@ Terminates this ability. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -1037,9 +1052,9 @@ Terminates this ability. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -1069,7 +1084,7 @@ Terminates this ability. This API uses a promise to return the result. connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; -Connects this ability to a Service ability. +Connects this ability to a ServiceAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1077,16 +1092,16 @@ Connects this ability to a Service ability. **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 | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| +| 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 | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** - | Type| Description| - | -------- | -------- | - | number | A number, based on which the connection will be interrupted.| +| Type| Description| +| -------- | -------- | +| number | A number, based on which the connection will be interrupted.| **Error codes** @@ -1165,8 +1180,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1189,7 +1204,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback<void>): void; -Disconnects this ability from the Service ability. This API uses an asynchronous callback to return the result. +Disconnects this ability from the ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1197,10 +1212,10 @@ Disconnects this ability from the Service ability. This API uses an asynchronous **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | connection | number | Yes| Number returned after **connectAbility** is called.| - | callback | AsyncCallback<void> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Number returned after **connectAbility** is called.| +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** @@ -1241,7 +1256,7 @@ Disconnects this ability from the Service ability. This API uses an asynchronous disconnectServiceExtensionAbility(connection: number): Promise<void>; -Disconnects this ability from the Service ability. This API uses a promise to return the result. +Disconnects this ability from the ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1249,15 +1264,15 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | connection | number | Yes| Number returned after **connectAbility** is called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Number returned after **connectAbility** is called.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** @@ -1300,6 +1315,11 @@ 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. @@ -1341,7 +1361,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }; @@ -1372,7 +1392,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "", parameters: { "ohos.aafwk.param.callAbilityToForeground": true 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 23c4e8d48a1b3755c829c1a9e775a1eb9bdba908..51b10659d38d55686ced548c624798d77391f102 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 @@ -25,7 +25,7 @@ let cmd = "cmd"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { - console.info("executeShellCommand callback, failed: ", err); - console.info("executeShellCommand callback, success: ", data); + console.info("executeShellCommand callback, result: ", err); + console.info("executeShellCommand callback, data: ", data); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 394f484144b3cf2f5fdf071ea22e2a38fe652739..f8528cc1bf6c8b4468c5c475934fe1c91c70490a 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 @@ -1,8 +1,6 @@ # UIAbilityContext -The **UIAbilityContext** 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. +**UIAbilityContext**, inherited from [Context](js-apis-inner-application-context.md), provides the context environment for [UIAbility](js-apis-app-ability-uiAbility.md). **UIAbilityContext** provides UIAbility-related configuration and APIs for operating UIAbilities and ServiceExtensionAbilities. For example, you can use the APIs to start a UIAbility, terminate a UIAbility to which the UIAbilityContext belongs, and start, terminate, connect to, or disconnect from a ServiceExtensionAbility. > **NOTE** > @@ -15,16 +13,24 @@ This module provides APIs for accessing ability-specific resources. You can use | 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-app-ability-configuration.md) | Yes| No| Configuration information.| +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| UIAbility information.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| HAP information.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| UIAbility configuration, such as the language and color mode.| + +> **NOTE** +> - In the sample code provided in this topic, **this.context** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** capabilities on pages, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). -## AbilityContext.startAbility +## UIAbilityContext.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** @@ -71,7 +77,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. if (error.code) { // Process service logic errors. console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -79,18 +85,22 @@ Starts an ability. This API uses an asynchronous callback to return the result. }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` - -## AbilityContext.startAbility +## UIAbilityContext.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** @@ -103,7 +113,7 @@ Starts an ability with the start options specified. This API uses an asynchronou **Error codes** -| ID| Error Message +| ID| Error Message| | ------- | -------------------------------- | | 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | @@ -130,7 +140,7 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var options = { @@ -142,7 +152,7 @@ Starts an ability with the start options specified. This API uses an asynchronou if (error.code) { // Process service logic errors. console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -150,17 +160,22 @@ Starts an ability with the start options specified. This API uses an asynchronou }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbility +## UIAbilityContext.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** @@ -208,33 +223,37 @@ Starts an ability. This API uses a promise to return the result. abilityName: "MyAbility" }; var options = { - windowMode: 0, + windowMode: 0, }; try { this.context.startAbility(want, options) - .then((data) => { + .then(() => { // Carry out normal service processing. console.log('startAbility succeed'); }) .catch((error) => { // Process service logic errors. console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` - -## AbilityContext.startAbilityForResult +## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +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 @@ -274,7 +293,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; @@ -283,25 +302,29 @@ Starts an ability. This API uses an asynchronous callback to return the result w if (error.code) { // Process service logic errors. console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + - result.resultCode) + 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)); + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResult +## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +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 @@ -342,7 +365,7 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var options = { @@ -354,26 +377,30 @@ Starts an ability with the start options specified. This API uses an asynchronou if (error.code) { // Process service logic errors. console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. - console.log("startAbilityForResult succeed, result.resultCode = " + - result.resultCode) + 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)); + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResult +## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. This API uses a promise to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +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 @@ -419,11 +446,11 @@ Starts an ability. This API uses a promise to return the result when the ability ```ts var want = { - bundleName: "com.example.myapp", - abilityName: "MyAbility" + bundleName: "com.example.myapplication", + abilityName: "MainAbility" }; var options = { - windowMode: 0, + windowMode: 0, }; try { @@ -435,22 +462,27 @@ Starts an ability. This API uses a promise to return the result when the ability .catch((error) => { // Process service logic errors. console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResultWithAccount +## UIAbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -461,8 +493,8 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| 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.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| **Error codes** @@ -494,7 +526,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -504,28 +536,33 @@ Starts an ability. This API uses an asynchronous callback to return the result w if (error.code) { // Process service logic errors. console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + result.resultCode + ' result.want = ' + JSON.stringify(result.want)) }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResultWithAccount +## UIAbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -Starts an ability with the start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +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. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -536,9 +573,9 @@ Starts an ability with the start options specified. This API uses an asynchronou | 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).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\ | Yes| Callback invoked when the ability is terminated.| **Error codes** @@ -570,7 +607,7 @@ Starts an ability with the start options specified. This API uses an asynchronou ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -579,32 +616,36 @@ Starts an ability with the start options specified. This API uses an asynchronou }; try { - this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error) => { if (error.code) { // Process service logic errors. console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. - console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + console.log("startAbilityForResultWithAccount succeed") }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityForResultWithAccount +## UIAbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -Starts an ability with the start options specified. This API uses a promise to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -615,14 +656,14 @@ Starts an ability with the start options specified. This API uses a promise to r | 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).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<AbilityResult> | Promise used to return the result.| +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the ability result when the ability is terminated.| **Error codes** @@ -654,7 +695,7 @@ Starts an ability with the start options specified. This API uses a promise to r ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -667,24 +708,24 @@ Starts an ability with the start options specified. This API uses a promise to r .then((result) => { // Carry out normal service processing. console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - 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)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbility +## UIAbilityContext.startServiceExtensionAbility startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -694,7 +735,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -719,8 +760,8 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { @@ -728,7 +769,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t if (error.code) { // Process service logic errors. console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -736,16 +777,16 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbility +## UIAbilityContext.startServiceExtensionAbility startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -755,7 +796,7 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| **Error codes** @@ -779,35 +820,35 @@ Starts a new Service Extension ability. This API uses a promise to return the re ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { this.context.startServiceExtensionAbility(want) - .then((data) => { + .then(() => { // Carry out normal service processing. console.log('startServiceExtensionAbility succeed'); }) .catch((error) => { // Process service logic errors. console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbilityWithAccount +## UIAbilityContext.startServiceExtensionAbilityWithAccount startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -817,8 +858,8 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -840,8 +881,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -850,7 +891,7 @@ Starts a new Service Extension ability with the account ID specified. This API u if (error.code) { // Process service logic errors. console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -858,18 +899,18 @@ Starts a new Service Extension ability with the account ID specified. This API u }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startServiceExtensionAbilityWithAccount +## UIAbilityContext.startServiceExtensionAbilityWithAccount startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +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 permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -880,7 +921,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| **Error codes** @@ -905,8 +946,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -919,19 +960,19 @@ Starts a new Service Extension ability with the account ID specified. This API u .catch((error) => { // Process service logic errors. console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbility +## UIAbilityContext.stopServiceExtensionAbility stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -941,7 +982,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -963,8 +1004,8 @@ Stops a Service Extension ability in the same application. This API uses an asyn ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { @@ -972,7 +1013,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn if (error.code) { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -980,16 +1021,16 @@ Stops a Service Extension ability in the same application. This API uses an asyn }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbility +## UIAbilityContext.stopServiceExtensionAbility stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -999,7 +1040,7 @@ Stops a Service Extension ability in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| **Error codes** @@ -1020,8 +1061,8 @@ Stops a Service Extension ability in the same application. This API uses a promi ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; try { @@ -1033,22 +1074,22 @@ Stops a Service Extension ability in the same application. This API uses a promi .catch((error) => { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbilityWithAccount +## UIAbilityContext.stopServiceExtensionAbilityWithAccount stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**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 @@ -1058,8 +1099,8 @@ Stops a Service Extension ability in the same application with the account ID sp | 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).| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1082,8 +1123,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -1092,7 +1133,7 @@ Stops a Service Extension ability in the same application with the account ID sp if (error.code) { // Process service logic errors. console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1100,18 +1141,18 @@ Stops a Service Extension ability in the same application with the account ID sp }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.stopServiceExtensionAbilityWithAccount +## UIAbilityContext.stopServiceExtensionAbilityWithAccount stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**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 @@ -1121,8 +1162,8 @@ Stops a Service Extension ability in the same application with the account ID sp | 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).| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| **Error codes** @@ -1144,8 +1185,8 @@ Stops a Service Extension ability in the same application with the account ID sp ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; @@ -1158,16 +1199,16 @@ Stops a Service Extension ability in the same application with the account ID sp .catch((error) => { // Process service logic errors. console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.terminateSelf +## UIAbilityContext.terminateSelf terminateSelf(callback: AsyncCallback<void>): void; @@ -1195,20 +1236,26 @@ Terminates this ability. This API uses an asynchronous callback to return the re **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'); - }); + try { + 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'); + }); + } catch (error) { + // Capture the synchronization parameter error. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } ``` -## AbilityContext.terminateSelf +## UIAbilityContext.terminateSelf terminateSelf(): Promise<void>; @@ -1236,22 +1283,30 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```ts - this.context.terminateSelf().then((data) => { - // Carry out normal service processing. - console.log('terminateSelf succeed'); - }).catch((error) => { - // Process service logic errors. + try { + this.context.terminateSelf() + .then(() => { + // 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)); + }); + } catch (error) { + // Capture the synchronization parameter error. console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - }); + ' error.message: ' + JSON.stringify(error.message)); + } ``` -## AbilityContext.terminateSelfWithResult +## UIAbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1277,8 +1332,8 @@ Terminates this ability. This API uses an asynchronous callback to return the ab ```ts var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" + bundleName: "com.example.myapplication", + abilityName: "MainAbility" } var resultCode = 100; // AbilityResult information returned to the caller. @@ -1292,25 +1347,25 @@ Terminates this ability. This API uses an asynchronous callback to return the ab if (error.code) { // Process service logic errors. console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' 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)); + // Process input parameter errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.terminateSelfWithResult +## UIAbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult): Promise<void>; -Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), 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 @@ -1342,8 +1397,8 @@ Terminates this ability. This API uses a promise to return the ability result in ```ts var want = { - bundleName: "com.extreme.myapplication", - abilityName: "SecondAbility" + bundleName: "com.example.myapplication", + abilityName: "MainAbility" } var resultCode = 100; // AbilityResult information returned to the caller. @@ -1361,20 +1416,20 @@ Terminates this ability. This API uses a promise to return the ability result in .catch((error) => { // Process service logic errors. console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.connectServiceExtensionAbility +## UIAbilityContext.connectServiceExtensionAbility connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability. +Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1384,8 +1439,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | 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) | No| Parameters for the connection.| +| want | [Want](js-apis-application-want.md) | Yes| Want information for connecting to the ServiceExtensionAbility.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.| **Return value** @@ -1410,13 +1465,19 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } + onConnect(elementName, remote) { + console.log('----------- onConnect -----------') + }, + onDisconnect(elementName) { + console.log('----------- onDisconnect -----------') + }, + onFailed(code) { + console.log('----------- onFailed -----------') + } } var connection = null; @@ -1425,18 +1486,18 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.connectServiceExtensionAbilityWithAccount +## UIAbilityContext.connectServiceExtensionAbilityWithAccount connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. +Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template, with the account ID specified. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**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 @@ -1447,8 +1508,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | 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) | No| Parameters for the connection.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.| **Return value** @@ -1474,14 +1535,20 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" }; var accountId = 100; var options = { - onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, - onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, - onFailed(code) { console.log('----------- onFailed -----------') } + onConnect(elementName, remote) { + console.log('----------- onConnect -----------') + }, + onDisconnect(elementName) { + console.log('----------- onDisconnect -----------') + }, + onFailed(code) { + console.log('----------- onFailed -----------') + } } var connection = null; @@ -1490,15 +1557,15 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.disconnectServiceExtensionAbility +## UIAbilityContext.disconnectServiceExtensionAbility disconnectServiceExtensionAbility(connection: number): Promise\; -Disconnects a connection. This API uses a promise to return the result. +Disconnects from a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1508,7 +1575,7 @@ Disconnects a connection. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Result code of the ability connection.| +| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.| **Return value** @@ -1551,11 +1618,11 @@ Disconnects a connection. This API uses a promise to return the result. } ``` -## AbilityContext.disconnectServiceExtensionAbility +## UIAbilityContext.disconnectServiceExtensionAbility disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; -Disconnects a connection. This API uses an asynchronous callback to return the result. +Disconnects from a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1565,7 +1632,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| connection | number | Yes| Result code of the ability connection.| +| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1590,7 +1657,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r if (error.code) { // Process service logic errors. console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1599,16 +1666,21 @@ Disconnects a connection. This API uses an asynchronous callback to return the r } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityByCall +## UIAbilityContext.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 **Parameters** @@ -1632,10 +1704,10 @@ Starts an ability in the foreground or background and obtains the caller object // Start an ability in the background by not passing parameters. var wantBackground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "" + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "" }; try { @@ -1645,14 +1717,14 @@ Starts an ability in the foreground or background and obtains the caller object 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)); - }); + // 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)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1663,13 +1735,13 @@ Starts an ability in the foreground or background and obtains the caller object // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. var wantForeground = { - bundleName: "com.example.myservice", - moduleName: "entry", - abilityName: "MainAbility", - deviceId: "", - parameters: { - "ohos.aafwk.param.callAbilityToForeground": true - } + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "", + parameters: { + "ohos.aafwk.param.callAbilityToForeground": true + } }; try { @@ -1679,24 +1751,29 @@ Starts an ability in the foreground or background and obtains the caller object 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)); - }); + // 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)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityWithAccount +## UIAbilityContext.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. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -1707,7 +1784,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1740,7 +1817,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -1750,7 +1827,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c if (error.code) { // Process service logic errors. console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1759,18 +1836,23 @@ Starts an ability with the account ID specified. This API uses an asynchronous c } catch (paramError) { // Process input parameter errors. console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityWithAccount +## UIAbilityContext.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. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -1781,8 +1863,8 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| 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-app-ability-startOptions.md) | No| Parameters used for starting the ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** @@ -1815,7 +1897,7 @@ Starts an ability with the account ID and start options specified. This API uses ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -1828,7 +1910,7 @@ Starts an ability with the account ID and start options specified. This API uses if (error.code) { // Process service logic errors. console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); return; } // Carry out normal service processing. @@ -1836,19 +1918,24 @@ Starts an ability with the account ID and start options specified. This API uses }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.startAbilityWithAccount +## UIAbilityContext.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. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +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 @@ -1859,7 +1946,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| -| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| **Error codes** @@ -1892,7 +1979,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", + bundleName: "com.example.myapplication", abilityName: "MainAbility" }; var accountId = 100; @@ -1909,75 +1996,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu .catch((error) => { // Process service logic errors. console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); + ' error.message: ' + JSON.stringify(error.message)); }); } catch (paramError) { // Process input parameter errors. - console.log('error.code: ' + JSON.stringify(paramError.code) + - ' error.message: ' + JSON.stringify(paramError.message)); + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } ``` -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Yes| Callback used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md)> | Promise used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - - -## AbilityContext.setMissionLabel +## UIAbilityContext.setMissionLabel setMissionLabel(label: string, callback:AsyncCallback<void>): void; @@ -1995,13 +2023,12 @@ Sets a label for this ability in the mission. This API uses an asynchronous call **Example** ```ts - this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + this.context.setMissionLabel("test", (result) => { + console.log('setMissionLabel:' + JSON.stringify(result)); }); ``` - -## AbilityContext.setMissionLabel +## UIAbilityContext.setMissionLabel setMissionLabel(label: string): Promise<void>; @@ -2025,12 +2052,12 @@ Sets a label for this ability in the mission. This API uses a promise to return ```ts this.context.setMissionLabel("test").then(() => { - console.log('success'); + console.log('success'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + console.log('failed:' + JSON.stringify(error)); }); ``` -## AbilityContext.setMissionIcon +## UIAbilityContext.setMissionIcon setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; @@ -2050,29 +2077,29 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call **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); + 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 +## UIAbilityContext.setMissionIcon setMissionIcon(icon: image.PixelMap): Promise\; @@ -2097,31 +2124,30 @@ Sets an icon for this ability in the mission. This API uses a promise to return **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); - }); + 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 +## UIAbilityContext.restoreWindowStage restoreWindowStage(localStorage: LocalStorage) : void; @@ -2138,11 +2164,11 @@ Restores the window stage data for this ability. **Example** ```ts - var storage = new LocalStorage(); - this.context.restoreWindowStage(storage); + var storage = new LocalStorage(); + this.context.restoreWindowStage(storage); ``` -## AbilityContext.isTerminating +## UIAbilityContext.isTerminating isTerminating(): boolean; diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md index e659a4d80e43f59f06bfe7a8357ab6675886fad6..5ca299f0ad5f9df4f5b460b30e9e34c7dad82d5d 100644 --- a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -1,66 +1,12 @@ # TriggerInfo -The **TriggerInfo** module defines the information required for triggering the WantAgent. +The **TriggerInfo** module defines the information required for triggering the WantAgent. The information is used as an input parameter of [trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger). **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Type | Mandatory| Description | | ---------- | --- |-------------------- | ----------- | -| code | number | Yes | Result code.| +| code | number | Yes | Custom result code provided for the target WantAgent.| | want | Want | No | Want. | | permission | string | No | Permission. | | extraInfo | {[key: string]: any} | No | Extra information. | - -**Example** -```ts -import wantAgent from '@ohos.wantAgent'; - -let wantAgentInfo = { - wants: [ - { - deviceId: "", - bundleName: "com.example.apicoverhaptest", - abilityName: "com.example.apicoverhaptest.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true.true,false}", - parameters: { - myKey0: 2222 - } - } - ], - operationType: wantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], - extraInfo:{ - "key": "value" - } -} - -let triggerInfo = { - code: 0, - want: { - deviceId: "", - bundleName: "com.example.apicoverhaptest", - abilityName: "com.example.apicoverhaptest.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true.true,false}", - parameters: { - myKey0: 2222 - } - }, - permission: "" - extraInfo:{ - "key": "value" - } -} - -wantAgent.trigger(wantAgentInfo, triggerInfo).then((data) =>{ - console.info("trigger data: " + JSON.stringify(data)); -}).catch((err) => { - console.error("trigger err: " + JSON.stringify(err)); -}) -``` 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 6d93123f0ca73a7089b640f2f1cb98cc3df4308c..8facc43fc842570c3eb0ea95a141bdaa77dcf252 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 @@ -1,6 +1,6 @@ # WantAgentInfo -The **WantAgentInfo** module defines the information required for triggering the WantAgent. +The **WantAgentInfo** module defines the information required for triggering a **WantAgent** object. The information can be used as an input parameter in [getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to obtain a specified **WantAgent** object. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -9,38 +9,5 @@ The **WantAgentInfo** module defines the information required for triggering the | wants | Array\ | Yes | Array of all **Want** objects. | | operationType | wantAgent.OperationType | Yes | Operation type. | | requestCode | number | Yes | Request code defined by the user.| -| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-wantAgent.md#WantAgentFlags)> | No | Array of flags for using the **WantAgent** object. | +| 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. | - -**Example** -```ts -import wantAgent from '@ohos.wantAgent'; - -let wantAgentInfo = { - wants: [ - { - deviceId: "", - bundleName: "com.example.apicoverhaptest", - abilityName: "com.example.apicoverhaptest.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true.true,false}", - parameters: { - myKey0: 2222 - } - } - ], - operationType: wantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], - extraInfo:{ - "key": "value" - } -} -wantAgent.getWantAgent(wantAgentInfo).then((data) =>{ - console.info("getWantAgent data: " + JSON.stringify(data)); -}).catch((err) => { - console.error("getWantAgent err: " + JSON.stringify(err)); -}) -``` diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index ef60fdc7decd8dc786ec79ad7bbbc32693509e2a..4de59dd1322f1cc83203ad38bc63746c81d56e8a 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,11 +1,9 @@ -# Input Consumer +# @ohos.multimodalInput.inputConsumer (Input Consumer) -The Input Consumer module implements listening for combination key events. +The **inputConsumer** module implements listening for combination key events. > **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 system APIs. diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 9ed326b92bb458a475f47ee29aeee01f681cf5b4..c131d9bbd3e50790624d4eca0ea41c94d7022dd2 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -1,17 +1,12 @@ -# Input Device +# @ohos.multimodalInput.inputDevice (Input Device) +The **inputDevice** module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. -The Input Device module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. - - -> **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. - ## Modules to Import - ```js import inputDevice from '@ohos.multimodalInput.inputDevice'; ``` @@ -33,7 +28,7 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to ```js try { - inputDevice.getDeviceList((error, ids) => { + inputDevice.getDeviceIds((error, ids) => { if (error) { console.log(`Failed to get device list. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); @@ -65,7 +60,7 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu ```js try { - inputDevice.getDeviceList().then((ids) => { + inputDevice.getDeviceIds().then((ids) => { console.log("The device ID list is: " + ids); }); } catch (error) { @@ -245,10 +240,15 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. **Example** ```js -inputDevice.getDeviceIds((ids)=>{ - console.log("The device ID list is: " + ids); +inputDevice.getDeviceIds((error, ids) => { + if (error) { + console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Device id list: ${JSON.stringify(ids)}`); }); ``` +``` ## inputDevice.getDeviceIds(deprecated) @@ -269,8 +269,8 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. **Example** ```js -inputDevice.getDeviceIds().then((ids)=>{ - console.log("The device ID list is: " + ids); +inputDevice.getDeviceIds().then((ids) => { + console.log(`Device id list: ${JSON.stringify(ids)}`); }); ``` @@ -295,8 +295,12 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ```js // Obtain the name of the device whose ID is 1. -inputDevice.getDevice(1, (inputDevice)=>{ - console.log("The device name is: " + inputDevice.name); +inputDevice.getDevice(1, (error, deviceData) => { + if (error) { + console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); ``` @@ -326,8 +330,8 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ```js // Obtain the name of the device whose ID is 1. -inputDevice.getDevice(1).then((inputDevice)=>{ - console.log("The device name is: " + inputDevice.name); +inputDevice.getDevice(1).then((deviceData) => { + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md index 862c39c608ba76b56c23b675c9ef1da19c43331f..d2d55fa57ee6bd71288d03aa3f42e24bebb80bea 100644 --- a/en/application-dev/reference/apis/js-apis-inputevent.md +++ b/en/application-dev/reference/apis/js-apis-inputevent.md @@ -1,6 +1,6 @@ -# Input Event +# @ohos.multimodalInput.inputEvent (Input Event) -The Input Event module describes basic events reported by an input device. +The **inputEvent** module describes basic events reported by an input 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. diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index f4372d664aafbe2d55d4a35cc30d715b6d3be774..354f10e3802d163343b658bef56ab4e03689d2c3 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,11 +1,9 @@ -# Key Injection +# @ohos.multimodalInput.inputEventClient (Key Event Injection) -The Key Injection module implements injection of key events. +The **inputEventClient** module implements injection of key events. > **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 system APIs. diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md index 6a8cabde0302010e3739f298ba03583325491ef8..d96cd241e7e4c198497712f7fa75c6990b847f6e 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @@ -1,4 +1,4 @@ -# InputMethodExtensionAbility +# @ohos.inputmethodextensionability (InputMethodExtensionAbility) The **InputMethodExtensionAbility** module provides APIs for developing input methods and managing their lifecycles. diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index 7f0868a36b356797f8e4a39c31e13a7c1396d239..b33db13faa840a1660a42e612ef5a4d523241877 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -1,4 +1,4 @@ -# InputMethodExtensionContext +# @ohos.inputmethodextensioncontext (InputMethodExtensionContext) The **InputMethodExtensionContext** module, inherited from **ExtensionContext**, provides context for **InputMethodExtension** abilities. @@ -20,7 +20,7 @@ Before using the **InputMethodExtensionContext** module, you must define a child ```js import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; -class MainAbility extends InputMethodExtensionAbility { +class EntryAbility extends InputMethodExtensionAbility { onCreate() { let context = this.context; } diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md index 61ec49997ccb35b204f860e57b0985793598e071..1b5f9dfb662145fe2220d1d244cb3ac91dce9698 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md @@ -1,4 +1,4 @@ -# @ohos.inputmethodsubtype +# @ohos.inputmethodsubtype (Input Method Subtype) The **inputMethodSubtype** module provides APIs for managing the attributes of input method subtypes. Different attribute settings result in different subtypes. diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 424e48b357711a7ee94eb4b048f107d7ad4c7a3d..e7ff69abcf62ef6957875badde01857b05087659 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,4 +1,4 @@ -# @ohos.inputmethod +# @ohos.inputmethod (Input Method Framework) The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 2c87f74698434a68279b5e1c627e2a7352819a38..f5becc73ca2132e8864c3bd8b8a9830312b96188 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,4 +1,4 @@ -# @ohos.inputmethodengine +# @ohos.inputmethodengine (Input Method Service) The **inputMethodEngine** module streamlines the interaction between input methods and applications. By calling APIs of this module, applications can be bound to input method services to accept text input through the input methods, request the keyboard to display or hide, listen for the input method status, and much more. diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 7bd41f5d0be2922df090f71651b1c4a15aafecb1..304fa76946de0e4279be5095bd1dae46f79c7ca6 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,11 +1,10 @@ -# Input Monitor +# @ohos.multimodalInput.inputMonitor (Input Monitor) -The Input Monitor module implements listening for events of input devices (namely, touchscreen and mouse). +The **inputMonitor** module implements listening for events of input devices (namely, touchscreen and mouse). > **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 provided by this module are system APIs. diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 0c3651fc6add2e830f9a8e3eeb5ccabddb122e2e..3dc9a22442c07759d3b594297f7828cb7d5cc95b 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -1,4 +1,4 @@ -# @ohos.bundle.installer +# @ohos.bundle.installer (installer) The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index e3cb7bbfd684ae315d6d54363183401442f5167a..d4f3449adae43eed9b19236aec0d0308feed89e8 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,20 +1,20 @@ -# Internationalization – Intl +# @ohos.intl (Internationalization) -The Intl module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. - -The [I18N](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. +The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. > **NOTE** -> -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n interfaces defined in ECMA 402. For details about the enhanced i18n capabilities, see [i18n](js-apis-i18n.md). ## Modules to Import -``` +```js import Intl from '@ohos.intl'; ``` - +Importing an incorrect bundle can lead to unexpected API behavior. ## Locale @@ -23,16 +23,16 @@ import Intl from '@ohos.intl'; **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | language | string | Yes | No | Language associated with the locale, for example, **zh**. | | script | string | Yes | No | Script type of the language, for example, **Hans**. | | region | string | Yes | No | Region associated with the locale, for example, **CN**. | | baseName | string | Yes | No | Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**. | | caseFirst | string | Yes | No | Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| -| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| | collation | string | Yes | No | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| +| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, or **h24**.| | numberingSystem | string | Yes | No | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | No | Whether to apply special collation rules for numeric characters. | @@ -41,13 +41,16 @@ import Intl from '@ohos.intl'; constructor() -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var locale = new Intl.Locale(); + ```js + // The default constructor uses the current system locale to create a Locale object. + let locale = new Intl.Locale() + // Return the current system locale. + let localeID = locale.toString() ``` @@ -55,20 +58,22 @@ Creates a Locale object. constructor(locale: string, options?: LocaleOptions) -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------- | ---- | ---------------------------- | -| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| +| options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | **Example** - ``` - var locale = new Intl.Locale("zh-CN"); + ```js + // Create a Locale object named zh-CN. + let locale = new Intl.Locale("zh-CN") + let localeID = locale.toString() // localeID = "zh-CN" ``` @@ -76,20 +81,21 @@ Creates a Locale object. toString(): string -Converts locale information to a string. +Obtains the string representation of a **Locale** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ------ | ----------- | -| string | String containing locale information.| +| string | String representation of the **Locale** object.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.toString(); + ```js + // Create a Locale object named en-GB. + let locale = new Intl.Locale("en-GB"); + let localeID = locale.toString(); // localeID = "en-GB" ``` @@ -101,16 +107,25 @@ Maximizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the maximized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.maximize(); + ```js + // Create a Locale object named zh. + let locale = new Intl.Locale("zh"); + // Complete the script and region of the Locale object. + let maximizedLocale = locale.maximize(); + let localeID = maximizedLocale.toString(); // localeID = "zh-Hans-CN" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Complete the script of the Locale object. + maximizedLocale = locale.maximize(); + localeID = maximizedLocale.toString(); // localeID = "en-Latn-US" ``` @@ -122,30 +137,39 @@ Minimizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the minimized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.minimize(); + ```js + // Create a Locale object named zh-Hans-CN. + let locale = new Intl.Locale("zh-Hans-CN"); + // Remove the script and region of the Locale object. + let minimizedLocale = locale.minimize(); + let localeID = minimizedLocale.toString(); // localeID = "zh" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Remove the region of the Locale object. + minimizedLocale = locale.minimize(); + localeID = minimizedLocale.toString(); // localeID = "en" ``` -## LocaleOptions9+ +## LocaleOptions6+ Represents the locale options. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | -| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| +| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | Yes | Whether to use the 12-hour clock. | | caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| @@ -163,8 +187,9 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var datefmt= new Intl.DateTimeFormat(); + ```js + // Use the current system locale to create a DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(); ``` @@ -178,20 +203,22 @@ Creates a **DateTimeOptions** object for the specified locale. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | **Example** - ``` - var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use locale zh-CN to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + let datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` **Example** - ``` - var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use the locale list ["ban", "zh"] to create a DateTimeFormat object. Because ban is an invalid locale ID, locale zh is used to create the DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -209,17 +236,22 @@ Formats the specified date and time. | ---- | ---- | ---- | ------- | | date | Date | Yes | Date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ------------ | | string | A string containing the formatted date and time.| **Example** - ``` - var date = new Date(2021, 11, 17, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.format(date); + ```js + let date = new Date(2021, 11, 17, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDate = datefmt.format(date); // formattedDate "17/12/2021" + + // Use locale en-GB to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + formattedDate = datefmt.format(date); // formattedDate "Friday, 17 December 2021 at 03:24:00" ``` @@ -238,18 +270,19 @@ Formats the specified date range. | startDate | Date | Yes | Start date and time to be formatted.| | endDate | Date | Yes | End date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | -------------- | | string | A string containing the formatted date and time range.| **Example** - ``` - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + ```js + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDateRange = datefmt.formatRange(startDate, endDate); // formattedDateRange = "17/12/2021-18/12/2021" ``` @@ -261,31 +294,34 @@ Obtains the formatting options for **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| +| Type | Description | +| ------------------------------------ | ----------------------------- | +| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| **Example** - ``` - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.resolvedOptions(); + ```js + let datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + // Obtain the options of the DateTimeFormat object. + let options = datefmt.resolvedOptions(); + let dateStyle = options.dateStyle; // dateStyle = "full" + let timeStyle = options.timeStyle; // timeStyle = "medium" ``` -## DateTimeOptions9+ +## DateTimeOptions6+ Provides the options for the **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | dateStyle | string | Yes | Yes | Date display format. The value can be **long**, **short**, **medium**, or **full**.| | timeStyle | string | Yes | Yes | Time display format. The value can be **long**, **short**, **medium**, or **full**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | timeZone | string | Yes | Yes | Time zone represented by a valid IANA time zone ID. | | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | hour12 | boolean | Yes | Yes | Whether to use the 12-hour clock. | @@ -315,8 +351,9 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var numfmt = new Intl.NumberFormat(); + ```js + // Use the current system locale to create a NumberFormat object. + let numfmt = new Intl.NumberFormat(); ``` @@ -328,15 +365,17 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | **Example** - ``` - var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); + ```js + // Use locale en-GB to create a NumberFormat object. Set style to decimal and notation to scientific. + let numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -354,7 +393,7 @@ Formats a number. | ------ | ------ | ---- | ---- | | number | number | Yes | Number to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | @@ -362,9 +401,10 @@ Formats a number. **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.format(1223); + ```js + // Use locale list ["en-GB", "zh"] to create a NumberFormat object. Because en-GB is a valid locale ID, it is used to create the NumberFormat object. + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + let formattedNumber = numfmt.format(1223); // formattedNumber = 1.223E3 ``` @@ -376,27 +416,30 @@ Obtains the options of the **NumberFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| +| Type | Description | +| -------------------------------- | --------------------------- | +| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.resolvedOptions(); + ```js + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + // Obtain the options of the NumberFormat object. + let options = numfmt.resolvedOptions(); + let style = options.style; // style = decimal + let notation = options.notation // notation = scientific ``` -## NumberOptions9+ +## NumberOptions6+ -Provides the device capability. +Defines the device capability. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | currency | string | Yes | Yes | Currency unit, for example, **EUR**, **CNY**, or **USD**. | @@ -426,13 +469,14 @@ Provides the device capability. constructor() -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var collator = new Intl.Collator(); + ```js + // Use the system locale to create a Collator object. + let collator = new Intl.Collator(); ``` @@ -440,20 +484,21 @@ Creates a Collator object. constructor(locale: string | Array<string>, options?: CollatorOptions) -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | **Example** - ``` - var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); + ```js + // Use locale zh-CN to create a Collator object. Set localeMatcher to lookup and usage to sort. + let collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -472,16 +517,18 @@ Compares two strings based on the sorting policy of the **Collator** object. | first | string | Yes | First string to compare. | | second | string | Yes | Second string to compare.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| **Example** - ``` - var collator = new Intl.Collator("zh-Hans"); - collator.compare("first", "second"); + ```js + // Use locale en-GB to create a Collator object. + let collator = new Intl.Collator("en-GB"); + // Compare the sequence of the first and second strings. + let compareResult = collator.compare("first", "second"); // compareResult = -1 ``` @@ -493,31 +540,33 @@ Returns properties reflecting the locale and collation options of a **Collator** **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| +| Type | Description | +| ------------------------------------ | ----------------- | +| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| **Example** - - ``` - var collator = new Intl.Collator("zh-Hans"); - var options = collator.resolvedOptions(); + ```js + let collator = new Intl.Collator("zh-Hans", { usage: 'sort', ignorePunctuation: true }); + // Obtain the options of the Collator object. + let options = collator.resolvedOptions(); + let usage = options.usage; // usage = "sort" + let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true ``` -## CollatorOptions9+ +## CollatorOptions8+ Represents the properties of a **Collator** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ----------------- | ------- | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | usage | string | Yes | Yes | Whether the comparison is for sorting or for searching. The value can be **sort** or **search**. | -| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| +| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **letiant**.| | ignorePunctuation | boolean | Yes | Yes | Whether punctuation is ignored. The value can be **true** or **false**. | | collation | string | Yes | Yes | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| | numeric | boolean | Yes | Yes | Whether numeric collation is used. The value can be **true** or **false**. | @@ -531,13 +580,14 @@ Represents the properties of a **Collator** object. constructor() -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var pluralRules = new Intl.PluralRules(); + ```js + // Use the system locale to create a PluralRules object. + let pluralRules = new Intl.PluralRules(); ``` @@ -545,19 +595,21 @@ Create a **PluralRules** object. constructor(locale: string | Array<string>, options?: PluralRulesOptions) -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | **Example** - ``` - var pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); + ```js + // Use locale zh-CN to create a PluralRules object. Set localeMatcher to lookup and type to cardinal. + let pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -575,26 +627,33 @@ Obtains a string that represents the singular-plural type of the specified numbe | ---- | ------ | ---- | ------------ | | n | number | Yes | Number for which the singular-plural type is to be obtained.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| **Example** - ``` - var pluralRules = new Intl.PluralRules("zh-Hans"); - pluralRules.select(1); + ```js + // Use locale zh-Hans to create a PluralRules object. + let zhPluralRules = new Intl.PluralRules("zh-Hans"); + // Determine the singular-plural type corresponding to number 1 in locale zh-Hans. + let plural = zhPluralRules.select(1); // plural = other + + // Use locale en-US to create a PluralRules object. + let enPluralRules = new Intl.PluralRules("en-US"); + // Determine the singular-plural type corresponding to number 1 in locale en-US. + plural = enPluralRules.select(1); // plural = one ``` -## PluralRulesOptions9+ +## PluralRulesOptions8+ Represents the properties of a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | type | string | Yes | Yes | Sorting type. The value can be **cardinal** or **ordinal**. | @@ -617,8 +676,9 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat(); + ```js + // Use the system locale to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -632,14 +692,15 @@ Creates a **RelativeTimeFormat** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | **Example** - ``` - var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. Set localeMatcher to lookup, numeric to always, and style to long. + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -658,16 +719,18 @@ Formats the value and unit based on the specified locale and formatting options. | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | | string | Relative time after formatting.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); - relativetimefmt.format(3, "quarter") + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); + // Obtain the localized representation (in unit of quarter) of number 3 in locale zh-CN. + let formatResult = relativetimefmt.format(3, "quarter"); // formatResult = "3 quarters later" ``` @@ -675,7 +738,7 @@ Formats the value and unit based on the specified locale and formatting options. formatToParts(value: number, unit: string): Array<object> -Returns an array of RelativeTimeFormat objects in parts for locale-aware formatting. +Obtains an array of RelativeTimeFormat objects in parts for locale-aware formatting. **System capability**: SystemCapability.Global.I18n @@ -686,16 +749,17 @@ Returns an array of RelativeTimeFormat objects in parts for locale-aware formatt | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------------------- | --------------------------- | | Array<object> | An array of **RelativeTimeFormat** objects in parts.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); - var parts = relativetimefmt.format(10, "seconds"); + ```js + // Use locale en to create a RelativeTimeFormat object. Set numeric to auto. + let relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); + let parts = relativetimefmt.formatToParts(10, "seconds"); // parts = [ {type: "literal", value: "in"}, {type: "integer", value: 10, unit: "second"}, {type: "literal", value: "seconds"} ] ``` @@ -707,39 +771,42 @@ Obtains the formatting options for **RelativeTimeFormat** objects. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ---------------------------------------- | --------------------------------- | | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** - ``` - var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); - relativetimefmt.resolvedOptions(); + ```js + // Use locale en-GB to create a RelativeTimeFormat object. + let relativetimefmt= new Intl.RelativeTimeFormat("en-GB", { style: "short" }); + // Obtain the options of the RelativeTimeFormat object. + let options = relativetimefmt.resolvedOptions(); + let style = options.style; // style = "short" ``` -## RelativeTimeFormatInputOptions9+ +## RelativeTimeFormatInputOptions8+ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | | style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -## RelativeTimeFormatResolvedOptions8+ +## RelativeTimeFormatResolvedOptions8+ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------ | ---- | ---- | ---------------------------------------- | | locale | string | Yes | Yes | A string containing locale information, including the language, optional script, and region. | | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 018046356b3df502c499726928b8b437e98fc81d..e69775942629948eab964f4f91795ddfe7dfeda7 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -1,6 +1,6 @@ -# Keycode +# @ohos.multimodalInput.keyCode (Key Code) -The Keycode module provides keycodes for a key device. +The **keyCode** module provides keycodes for a key device. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 3cfb2440033aa8043801e986ade5b0bd28c475d3..32c18a558572b8f971b8faf6277c3300e86f9649 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,9 +1,8 @@ -# Key Event +# @ohos.multimodalInput.keyEvent (Key Event) -The Key Event module provides key events reported by an input device. +The **keyEvent** module provides key events reported by an input device. -> **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index 1e966a2b659551a35649c3c087330e7d3059e182..89893c1c97d183c69765535141b2012fae9e080a 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -1,12 +1,13 @@ # @ohos.util.LightWeightMap (Nonlinear Container LightWeightMap) > **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. **LightWeightMap** stores key-value (KV) pairs. Each key must be unique and have only one value. -**LightWeightMap** is based on generics and uses a lightweight structure. Keys in the map are searched using hash values, which are stored in an array. +**LightWeightMap** is based on generics and uses a lightweight structure. Its default initial capacity is 8, and it has the capacity doubled in each expansion. + +The keys in such a set are searched using hash values, which are stored in an array. Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, **LightWeightMap** occupies less memory. @@ -44,7 +45,7 @@ A constructor used to create a **LightWeightMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -73,7 +74,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -109,7 +110,7 @@ Checks whether this container contains all elements of the specified **LightWeig **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -149,7 +150,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -159,10 +160,8 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); -let result = lightWeightMap.hasKey; -lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); -let result1 = lightWeightMap.hasKey("squirrel"); +let result = lightWeightMap.hasKey("squirrel"); ``` @@ -188,7 +187,7 @@ Checks whether this container contains the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -214,7 +213,7 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -256,7 +255,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -294,7 +293,7 @@ Obtains the index of the first occurrence of an element with the specified key i **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -332,7 +331,7 @@ Obtains the index of the first occurrence of an element with the specified value **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -370,12 +369,12 @@ Obtains the key of an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getKeyAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -403,7 +402,7 @@ Adds all elements in a **LightWeightMap** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -416,7 +415,7 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); -lightWeightMap.setAll(map); +map.setAll(lightWeightMap); // Add all elements in lightWeightMap to the map. ``` @@ -442,7 +441,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -478,7 +477,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -516,7 +515,7 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -555,12 +554,12 @@ Sets a value for an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -594,12 +593,12 @@ Obtains the value of an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -621,7 +620,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -653,7 +652,7 @@ Obtains an iterator that contains all the keys in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -690,7 +689,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -735,7 +734,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -769,7 +768,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -800,13 +799,13 @@ Concatenates the elements in this container into a string and returns the string **Return value** -| Type| Description| -| -------- | -------- | -| String | String obtained.| + | Type| Description| + | -------- | -------- | + | String | String obtained.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -818,7 +817,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); -let iter = lightWeightMap.toString(); +let result = lightWeightMap.toString(); ``` ### [Symbol.iterator] @@ -837,7 +836,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index 0953c12b1a012870147f5be3481de8cd28f9edd6..25c7950dc4968bc3f9f33ad6b277ecdc68a6ea09 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,7 +1,6 @@ # @ohos.util.LightWeightSet (Nonlinear Container LightWeightSet) > **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. **LightWeightSet** stores a set of values, each of which must be unique. @@ -44,7 +43,7 @@ A constructor used to create a **LightWeightSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -73,7 +72,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -108,7 +107,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -138,7 +137,7 @@ Adds all elements in a **LightWeightSet** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -178,7 +177,7 @@ Checks whether this container contains all elements of the specified **LightWeig **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -218,7 +217,7 @@ Checks whether this container has the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -246,7 +245,7 @@ Checks whether this container contains objects of the same type as the specified | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| obj | Object | Yes| Object to be used for comparison.| +| obj | Object | Yes| **LightWeightSet** instance to be used for comparison.| **Return value** @@ -256,7 +255,7 @@ Checks whether this container contains objects of the same type as the specified **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -289,12 +288,12 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The increaseCapacityTo method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of minimumCapacity is out of range. | **Example** @@ -326,7 +325,7 @@ Obtains the position index of the element with the specified key in this contain **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -364,7 +363,7 @@ Removes an element of the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -402,7 +401,7 @@ Removes the element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -440,7 +439,7 @@ Obtains the value of the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -466,7 +465,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -496,14 +495,6 @@ Obtains a string that contains all elements in this container. | -------- | -------- | | String | String obtained.| -**Error codes** - -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). - -| ID| Error Message| -| -------- | -------- | -| 10200011 | The toString method cannot be bound. | - **Example** ```ts @@ -530,7 +521,7 @@ Obtains an array that contains all objects in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -562,7 +553,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -607,7 +598,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -641,7 +632,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -678,7 +669,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 1eda96e1205a256960c8a03f28ee60080850d22c..0e745d749c0967cd515a91356750f7de0703ace7 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -1,14 +1,13 @@ # @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. -**LinkedList** is less efficient in data access than **[ArrayList](js-apis-arraylist.md)**. +**LinkedList** is more efficient in data insertion than **[ArrayList](js-apis-arraylist.md)**, but less efficient in data access. **Recommended use case**: Use **LinkedList** for frequent insertion and removal operations. @@ -42,7 +41,7 @@ A constructor used to create a **LinkedList** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -78,7 +77,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -113,7 +112,7 @@ Adds an element at the top of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -149,12 +148,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -187,7 +186,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -224,7 +223,7 @@ Obtains an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -266,7 +265,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -308,7 +307,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -350,12 +349,12 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -385,7 +384,7 @@ Removes the first element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -420,7 +419,7 @@ Removes the last element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -461,7 +460,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -500,7 +499,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -540,7 +539,7 @@ Removes the last occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -574,7 +573,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -617,7 +616,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -646,7 +645,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -686,12 +685,12 @@ Replaces an element at the specified position in this container with a given ele **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -720,7 +719,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -752,7 +751,7 @@ Obtains the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -785,7 +784,7 @@ Obtains the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -818,7 +817,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 2c657bc20289e50af9edda35a739f8fd8c3b0896..bd1272f3a7a48a47f30ba689ff9df972932727d6 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -1,7 +1,6 @@ # @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. @@ -16,7 +15,7 @@ This topic uses the following to identify the use of generics: ## Modules to Import ```ts -import List from '@ohos.util.List'; +import List from '@ohos.util.List'; ``` @@ -26,7 +25,7 @@ import List from '@ohos.util.List'; **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | length | number | Yes| No| Number of elements in a list (called container later).| @@ -41,7 +40,7 @@ A constructor used to create a **List** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -76,7 +75,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -112,12 +111,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -150,7 +149,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -187,7 +186,7 @@ Obtains the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -229,7 +228,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -271,7 +270,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -314,7 +313,7 @@ Compares whether a specified object is equal to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -359,12 +358,12 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -400,7 +399,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -443,7 +442,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -478,7 +477,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -491,7 +490,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -533,7 +532,7 @@ comparator **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -547,8 +546,8 @@ list.add(2); list.add(4); list.add(5); list.add(4); -list.sort((a: number, b: number) => a - b); -list.sort((a: number, b: number) => b - a); +list.sort((a: number, b: number) => a - b); // The elements are sorted in ascending order. +list.sort((a: number, b: number) => b - a); // The elements are sorted in descending order. ``` ### getSubList @@ -574,12 +573,12 @@ Obtains elements within a range in this container, including the element at the **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getSubList method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -604,7 +603,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -644,12 +643,12 @@ Replaces an element at the specified position in this container with a given ele **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -678,7 +677,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -711,7 +710,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -744,7 +743,7 @@ Obtains the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -777,7 +776,7 @@ Obtains the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -810,7 +809,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-logs.md b/en/application-dev/reference/apis/js-apis-logs.md index e2d0aff5a5eec1f468b0511a08f1f593a9af3548..48cc7954e1b4315f0e12d9571395decf9592b90d 100644 --- a/en/application-dev/reference/apis/js-apis-logs.md +++ b/en/application-dev/reference/apis/js-apis-logs.md @@ -1,6 +1,6 @@ -# Log +# console (Log) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE**
> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead. ## console.debug diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md index 97dd9e3f982d9f36d5feb6f17d59a40bb57e1a20..057e05ac3fd59f22e9bcea5b0fd6064142e95602 100644 --- a/en/application-dev/reference/apis/js-apis-matrix4.md +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -1,4 +1,4 @@ -# @ohos.matrix4 +# @ohos.matrix4 (Matrix Transformation) The **matrix4** module provides APIs for matrix transformation. You can use these APIs to translate, rotate, and scale images. @@ -145,11 +145,12 @@ Copies this matrix object. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({x:100}) - private matrix2 = this.matrix1.copy().scale({x:2}) + private matrix1 = matrix4.identity().translate({ x: 100 }) + private matrix2 = this.matrix1.copy().scale({ x: 2 }) build() { Column() { @@ -160,7 +161,7 @@ struct Test { Image($r("app.media.bg2")) .width("40%") .height(100) - .margin({top:50}) + .margin({ top: 50 }) .transform(this.matrix2) } } @@ -199,11 +200,12 @@ Combines the effects of two matrices to generate a new matrix object. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({x:200}).copy() - private matrix2 = matrix4.identity().scale({x:2}).copy() + private matrix1 = matrix4.identity().translate({ x: 200 }).copy() + private matrix2 = matrix4.identity().scale({ x: 2 }).copy() build() { Column() { @@ -211,13 +213,13 @@ struct Test { Image($r("app.media.icon")) .width("40%") .height(100) - .margin({top:50}) + .margin({ top: 50 }) // Translate the x-axis by 200px, and then scale it twice to obtain the resultant matrix. Image($r("app.media.icon")) .transform(this.matrix1.combine(this.matrix2)) .width("40%") - .height(100) - .margin({top:50}) + .height(100) + .margin({ top: 50 }) } } } @@ -245,8 +247,9 @@ Inverts this matrix object. ```ts import matrix4 from '@ohos.matrix4' // The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). -let matrix1 = matrix4.identity().scale({x:2}) +let matrix1 = matrix4.identity().scale({ x: 2 }) let matrix2 = matrix1.invert() + @Entry @Component struct Tests { @@ -295,10 +298,11 @@ Translates this matrix object along the x, y, and z axes. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().translate({x:100, y:200, z:30}) + private matrix1 = matrix4.identity().translate({ x: 100, y: 200, z: 30 }) build() { Column() { @@ -346,7 +350,7 @@ import matrix4 from '@ohos.matrix4' @Entry @Component struct Test { - private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) + private matrix1 = matrix4.identity().scale({ x:2, y:3, z:4, centerX:50, centerY:50 }) build() { Column() { @@ -392,17 +396,18 @@ Rotates this matrix object along the x, y, and z axes. ```ts // xxx.ets import matrix4 from '@ohos.matrix4' + @Entry @Component struct Test { - private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) + private matrix1 = matrix4.identity().rotate({ x: 1, y: 1, z: 2, angle: 30 }) build() { Column() { Image($r("app.media.bg1")).transform(this.matrix1) .width("40%") .height(100) - }.width("100%").margin({top:50}) + }.width("100%").margin({ top: 50 }) } } ``` diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 94034c60a39513e8bafa13724c7665f9c1620202..6d395fd5f21b8b041f7930ae96002dc430fd650b 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,7 +1,6 @@ -# Media +# @ohos.multimedia.media (Media) > **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 multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. @@ -1917,12 +1916,12 @@ Sets video recording parameters. This API uses an asynchronous callback to retur For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 201 | Permission denied. Return by callback. | -| 401 | Parameter error. Return by callback. | -| 5400102 | Operate not permit. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operation not allowed. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -1987,12 +1986,12 @@ Sets video recording parameters. This API uses a promise to return the result. For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 201 | Permission denied. Return by promise. | -| 401 | Parameter error. Return by promise. | -| 5400102 | Operate not permit. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operation not allowed. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2051,11 +2050,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2096,11 +2095,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2137,11 +2136,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2178,11 +2177,11 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2217,11 +2216,11 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2258,11 +2257,11 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2295,11 +2294,11 @@ Resumes video recording. This API uses an asynchronous callback to return the re For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2334,11 +2333,11 @@ Resumes video recording. This API uses a promise to return the result. For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2373,11 +2372,11 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | --------------------------------------- | -| 5400102 | Operate not permit. Return by callback. | -| 5400103 | IO error. Return by callback. | -| 5400105 | Service died. Return by callback. | +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | **Example** @@ -2414,11 +2413,11 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). -| ID| Error Message | -| -------- | -------------------------------------- | -| 5400102 | Operate not permit. Return by promise. | -| 5400103 | IO error. Return by promise. | -| 5400105 | Service died. Return by promise. | +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | **Example** @@ -2527,7 +2526,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | --------------------------------- | -| 5400103 | IO error. Return by callback. | +| 5400103 | I/O error. Return by callback. | | 5400105 | Service died. Return by callback. | **Example** @@ -2567,7 +2566,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | -------------------------------- | -| 5400103 | IO error. Return by promise. | +| 5400103 | I/O error. Return by promise. | | 5400105 | Service died. Return by promise. | **Example** @@ -2602,7 +2601,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco | ID| Error Message | | -------- | --------------------------------- | -| 5400103 | IO error. Return by callback. | +| 5400103 | I/O error. Return by callback. | | 5400105 | Service died. Return by callback. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index df70808165f275b456e591af48145d1e635ebfcd..8298770c17f71299078a9bc1e541abef94cd6d0b 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -202,7 +202,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| | callback | Callback<void> | Yes | Void callback. | **Example** @@ -224,7 +224,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| | callback | Callback<void> | No | Void callback. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index 4176338c0957632f67df2a74c73cd51a8ab1d48d..eb17dcdd6d568a442bae781edbd20bf9c8554c91 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -1,4 +1,4 @@ -# Media Query +# @ohos.mediaquery (Media Query) The **mediaquery** module provides different styles for different media types. @@ -14,64 +14,64 @@ import mediaquery from '@ohos.mediaquery' ``` -## Required Permissions - -None. - - ## mediaquery.matchMediaSync matchMediaSync(condition: string): MediaQueryListener -Sets the media query criteria and returns the corresponding listening handle. +Sets the media query condition. This API returns the corresponding media query listener. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | -| condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| +| condition | string | Yes | Media query condition. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| **Return value** + | Type | Description | | ------------------ | ---------------------- | -| MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.| +| MediaQueryListener | Media query listener, which is used to register or deregister the listening callback.| **Example** - ```js + +```js let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. - ``` +``` ## MediaQueryListener -Media query handle, including the first query result when the handle is applied for. +Implements the media query listener, including the first query result when the listener is applied for. **System capability**: SystemCapability.ArkUI.ArkUI.Full ### Attributes -| Name | Type | Readable | Writable | Description | -| ------- | ------- | ---- | ---- | ---------- | -| matches | boolean | Yes | No | Whether the match condition is met. | -| media | string | Yes | No | Matching condition of a media event.| +| Name | Type | Readable| Writable| Description | +| ------- | ------- | ---- | ---- | -------------------- | +| matches | boolean | Yes | No | Whether the media query condition is met. | +| media | string | Yes | No | Media query condition.| ### on on(type: 'change', callback: Callback<MediaQueryResult>): void -Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. +Registers the media query listener. The callback is triggered when the media attributes change. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | ---------------- | -| type | string | Yes | Must enter the string **change**.| +| type | string | Yes | Listener type. The value is fixed at **'change'**.| | callback | Callback<MediaQueryResult> | Yes | Callback registered with media query. | **Example** + For details, see [off Example](#off). @@ -79,17 +79,19 @@ Registers a callback with the corresponding query condition by using the handle. off(type: 'change', callback?: Callback<MediaQueryResult>): void -Deregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. +Deregisters the media query listener, so that no callback is triggered when the media attributes change. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | ---- | ----------------------------- | -| type | boolean | Yes | Must enter the string **change**. | -| callback | Callback<MediaQueryResult> | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.| + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ---------------------------------------------------------- | +| type | string | Yes | Listener type. The value is fixed at **'change'**. | +| callback | Callback<MediaQueryResult> | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.| **Example** + ```js import mediaquery from '@ohos.mediaquery' @@ -101,20 +103,23 @@ Deregisters a callback with the corresponding query condition by using the handl // do something here } } - listener.on('change', onPortrait) // Register a callback. - listener.off('change', onPortrait) // Deregister a callback. + listener.on('change', onPortrait) // Register the media query listener. + listener.off('change', onPortrait) // Deregister the media query listener. ``` - ## MediaQueryResult +Provides the media query result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + ### Attributes -| Name | Type | Readable | Writable | Description | -| ------- | ------- | ---- | ---- | ---------- | -| matches | boolean | Yes | No | Whether the match condition is met. | -| media | string | Yes | No | Matching condition of a media event.| +| Name | Type | Readable| Writable| Description | +| ------- | ------- | ---- | ---- | -------------------- | +| matches | boolean | Yes | No | Whether the media query condition is met. | +| media | string | Yes | No | Media query condition.| ### Example diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md index d3d9e4c05e44c68bc7bc58caa5267ddb851cd9bb..92935d6f31e788eb0b71ec6529fbc94264e3d8d1 100644 --- a/en/application-dev/reference/apis/js-apis-mouseevent.md +++ b/en/application-dev/reference/apis/js-apis-mouseevent.md @@ -1,14 +1,14 @@ -# Mouse Event +# @ohos.multimodalInput.mouseEvent (Mouse Event) -Represents mouse events reported by an input device. +The **mouseEvent** module provides mouse events reported by an input device. -> **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. ## Modules to Import ```js -import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mouseEvent'; +import { Action, Button, Axis, AxisValue, MouseEvent } from '@ohos.multimodalInput.mouseEvent'; ``` ## Action diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 2fbe0e1c1d90b155fc52702d1dc69982e511c140..d5a5f1585a5ae153694833b611861cc49325c4e7 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,9 +1,8 @@ -# Network Connection Management +# @ohos.net.connection (Network Connection Management) -The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. +The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. -> **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. ## Modules to Import @@ -61,7 +60,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## connection.getDefaultNetSync +## connection.getDefaultNetSync9+ getDefaultNetSync(): NetHandle; @@ -303,6 +302,55 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` +## connection.isDefaultNetMetered9+ + +isDefaultNetMetered(callback: AsyncCallback\): void + +Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.| + +**Example**: + +```js +connection.isDefaultNetMetered(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +## connection.isDefaultNetMetered9+ + +isDefaultNetMetered(): Promise\ + +Checks whether the data traffic usage on the current network is metered. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ----------------- | ----------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** indicates the data traffic usage is metered.| + +**Example**: + +```js +connection.isDefaultNetMetered().then(function (has) { + console.log('has: ' + has) +}) +``` + ## connection.reportNetConnected reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void @@ -495,7 +543,7 @@ enableAirplaneMode(callback: AsyncCallback\): void Enables the airplane mode. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -519,7 +567,7 @@ enableAirplaneMode(): Promise\ Enables the airplane mode. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -543,7 +591,7 @@ disableAirplaneMode(callback: AsyncCallback\): void Disables the airplane mode. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -567,7 +615,7 @@ disableAirplaneMode(): Promise\ Disables the airplane mode. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -823,7 +871,7 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** | ------ | ------ | ------------------------- | | netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| -### bindSocket +### bindSocket9+ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; @@ -1091,10 +1139,10 @@ Provides an instance that bears data network capabilities. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | -| netCapabilities | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network. | -| bearerPrivateIdentifier | string | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | +| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| ## NetCapabilities @@ -1102,12 +1150,12 @@ Defines the network capability set. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| --------------------- | ---------------------------------- | ------------------------ | -| linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.| -| linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.| -| networkCap | Array<[NetCap](#netcap)> | Network capability. | -| bearerTypes | Array<[NetBearType](#netbeartype)> | Network type. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| linkUpBandwidthKbps | number | No | Uplink (from the device to the network) bandwidth.| +| linkDownBandwidthKbps | number | No | Downlink (from the network to the device) bandwidth.| +| networkCap | Array<[NetCap](#netcap)> | No | Network capability. | +| bearerTypes | Array<[NetBearType](#netbeartype)> | Yes | Network type. | ## NetCap @@ -1141,14 +1189,14 @@ Defines the network connection properties. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ------------- | ---------------------------------- | ---------------- | -| interfaceName | string | NIC card name. | -| domains | string | Domain. The default value is **""**.| -| linkAddresses | Array<[LinkAddress](#linkaddress)> | Link information. | -| routes | Array<[RouteInfo](#routeinfo)> | Route information. | -| dnses | Array<[NetAddress](#netaddress)> | Network address. For details, see [NetAddress](#netaddress).| -| mtu | number | Maximum transmission unit (MTU). | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| interfaceName | string | Yes | NIC card name. | +| domains | string | Yes | Domain. The default value is **""**.| +| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. | +| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. | +| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).| +| mtu | number | Yes | Maximum transmission unit (MTU). | ## LinkAddress @@ -1156,10 +1204,10 @@ Network link information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ------------ | ------------------------- | -------------------- | -| address | [NetAddress](#netaddress) | Link address. | -| prefixLength | number | Length of the link address prefix.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| address | [NetAddress](#netaddress) | Yes | Link address. | +| prefixLength | number | Yes | Length of the link address prefix.| ## RouteInfo @@ -1167,13 +1215,13 @@ Network route information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| -------------- | --------------------------- | ---------------- | -| interface | string | NIC card name. | -| destination | [LinkAddress](#linkaddress) | Destination IP address. | -| gateway | [NetAddress](#netaddress) | Gateway address. | -| hasGateway | boolean | Whether a gateway is present. | -| isDefaultRoute | boolean | Whether the route is the default route.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| interface | string | Yes | NIC card name. | +| destination | [LinkAddress](#linkaddress) | Yes | Destination IP address. | +| gateway | [NetAddress](#netaddress) | Yes | Gateway address. | +| hasGateway | boolean | Yes | Whether a gateway is present. | +| isDefaultRoute | boolean | Yes | Whether the route is the default route.| ## NetAddress @@ -1181,8 +1229,8 @@ Defines the network address. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ------- | ------ | ------------------------------ | -| address | string | Network address. | -| family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| -| port | number | Port number. The value ranges from **0** to **65535**. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| address | string | Yes | Network address. | +| family | number | Yes | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| +| port | number | No | Port number. The value ranges from **0** to **65535**. | diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index bf132f3c63710fc83b04a3411eb2477f2fe8b855..d41845ec1859507bb96a071dff2a57e16f4cf12b 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,9 +1,8 @@ -# Ethernet Connection Management +# @ohos.net.ethernet (Ethernet Connection Management) -The Ethernet Connection Management module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. +The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. -> **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. ## Modules to Import @@ -14,7 +13,7 @@ import ethernet from '@ohos.net.ethernet' ## ethernet.setIfaceConfig -setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void; +setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void Sets the network interface configuration. This API uses an asynchronous callback to return the result. @@ -46,7 +45,7 @@ ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", ro ## ethernet.setIfaceConfig -setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\; +setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ Sets the network interface configuration. This API uses a promise to return the result. @@ -80,7 +79,7 @@ ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", ro ## ethernet.getIfaceConfig -getIfaceConfig(iface: string, callback: AsyncCallback\): void; +getIfaceConfig(iface: string, callback: AsyncCallback\): void Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. @@ -115,7 +114,7 @@ ethernet.getIfaceConfig("eth0", (error, value) => { ## ethernet.getIfaceConfig -getIfaceConfig(iface: string): Promise\; +getIfaceConfig(iface: string): Promise\ Obtains the configuration of a network interface. This API uses a promise to return the result. @@ -153,7 +152,7 @@ ethernet.getIfaceConfig("eth0").then((data) => { ## ethernet.isIfaceActive -isIfaceActive(iface?: string, callback: AsyncCallback\): void; +isIfaceActive(iface?: string, callback: AsyncCallback\): void Checks whether a network interface is active. This API uses an asynchronous callback to return the result. @@ -165,7 +164,7 @@ Checks whether a network interface is active. This API uses an asynchronous call | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | -------------------------------------------------- | -| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | +| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | | callback | AsyncCallback\ | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| **Example** @@ -182,7 +181,7 @@ ethernet.isIfaceActive("eth0", (error, value) => { ## ethernet.isIfaceActive -isIfaceActive(iface?: string): Promise\; +isIfaceActive(iface: string): Promise\ Checks whether a network interface is active. This API uses a promise to return the result. @@ -194,7 +193,7 @@ Checks whether a network interface is active. This API uses a promise to return | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| +| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| **Return value** @@ -214,7 +213,7 @@ ethernet.isIfaceActive("eth0").then((data) => { ## ethernet.getAllActiveIfaces -getAllActiveIfaces(callback: AsyncCallback\>): void; +getAllActiveIfaces(callback: AsyncCallback\>): void Obtains all active network interfaces. This API uses an asynchronous callback to return the result. @@ -245,7 +244,7 @@ ethernet.getAllActiveIfaces((error, value) => { ## ethernet.getAllActiveIfaces -getAllActiveIfaces(): Promise\>; +getAllActiveIfaces(): Promise\> Obtains all active network interfaces. This API uses a promise to return the result. @@ -280,14 +279,14 @@ Defines the network configuration for the Ethernet connection. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | -| mode | [IPSetMode](#ipsetmode) | Configuration mode of the Ethernet connection.| -| ipAddr | string | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| -| route | string | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| gateway | string | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| netMask | string | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| -| dnsServers | string | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.| +| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| +| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| ## IPSetMode diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index c63c09c5a84bbec34b5b2274d3089fad4fbb603b..144ffa9c6e2d405c83e7cf14fdb7278c616759d3 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,9 +1,8 @@ -# Network Sharing Management +# @ohos.net.sharing (Network Sharing) -The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, and Bluetooth sharing. It also allows you to query the network sharing state and shared mobile data volume. +The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. -> **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. ## Modules to Import @@ -18,9 +17,11 @@ isSharingSupported(callback: AsyncCallback\): void Checks whether network sharing is supported. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -43,9 +44,11 @@ isSharingSupported(): Promise\ Checks whether network sharing is supported. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -69,9 +72,11 @@ isSharing(callback: AsyncCallback\): void Checks whether network sharing is in progress. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -96,7 +101,9 @@ Checks whether network sharing is in progress. This API uses a promise to return **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -122,7 +129,9 @@ Starts network sharing of a specified type. This API uses an asynchronous callba **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -146,9 +155,11 @@ startSharing(type: SharingIfaceType): Promise\ Starts network sharing of a specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -179,9 +190,11 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void Stops network sharing of a specified type. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -205,9 +218,11 @@ stopSharing(type: SharingIfaceType): Promise\ Stops network sharing of a specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -238,9 +253,11 @@ getStatsRxBytes(callback: AsyncCallback\): void Obtains the volume of mobile data traffic received via network sharing. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -263,9 +280,11 @@ getStatsRxBytes(): Promise\ Obtains the volume of mobile data traffic received via network sharing. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -289,9 +308,11 @@ getStatsTxBytes(callback: AsyncCallback\): void Obtains the volume of mobile data traffic sent via network sharing. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -314,9 +335,11 @@ getStatsTxBytes(): Promise\ Obtains the volume of mobile data traffic sent via network sharing. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -340,9 +363,11 @@ getStatsTotalBytes(callback: AsyncCallback\): void Obtains the volume of mobile data traffic sent and received via network sharing. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -365,9 +390,11 @@ getStatsTotalBytes(): Promise\ Obtains the volume of mobile data traffic sent and received via network sharing. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -391,15 +418,17 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\> | Yes | Callback used to return an array of NIC names.| **Example** @@ -418,15 +447,17 @@ getSharingIfaces(state: SharingIfaceState): Promise\> Obtains the names of NICs in the specified network sharing state. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| **Return value** @@ -451,9 +482,11 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\ Obtains the network sharing state of the specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -511,9 +546,11 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\> Obtains regular expressions of NICs of a specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -571,9 +610,11 @@ on(type: 'sharingStateChange', callback: Callback\): void Subscribes to network sharing state changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -597,9 +638,11 @@ off(type: 'sharingStateChange', callback?: Callback\): void Unsubscribes from network sharing state changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -623,9 +666,11 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -649,15 +694,17 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| type | string | No | Event name.| +| type | string | Yes | Event name.| | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| **Example** @@ -675,9 +722,11 @@ on(type: 'sharingUpstreamChange', callback: Callback\): void Subscribes to upstream network changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -701,9 +750,11 @@ off(type: 'sharingUpstreamChange', callback?: Callback\): void Unsubscribes from upstream network changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -725,7 +776,9 @@ sharing.off('sharingUpstreamChange', (error, data) => { Enumerates the network sharing states of an NIC. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing | Name | Value | Description | | ------------------------ | ---- | ---------------------- | @@ -737,7 +790,9 @@ Enumerates the network sharing states of an NIC. Enumerates the network sharing types of an NIC. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing | Name | Value | Description | | ------------------------ | ---- | ---------------------- | diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 91ef73c07db34721d0cc0f964bb992ce37669ae3..704b9084ff4f3ebecf2720f6c40ebeb98f5dc775 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -242,7 +242,7 @@ For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode ## tag.getMifareClassic9+ -getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. @@ -258,7 +258,7 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use | **Type**| **Description** | | ----------------- | ------------------------| -| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| +| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) | **MifareClassicTag** object obtained.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index ad7d19b4ab7a3cfa6593c81f2c70b52f403aa4d1..ae5b7999bd7e579179920a73fcaea6116890ff70 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -1,6 +1,6 @@ -# Observer +# @ohos.telephony.observer (Observer) -The observer module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. +The **observer** module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index ee53667d0158343624ab086abe598a8baa9608c0..d1d554f677aca7fcb21d1e74cd6fb502f6e90032 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -1,4 +1,4 @@ -# Pasteboard +# @ohos.pasteboard (Pasteboard) The **pasteboard** module provides the copy and paste support for the system pasteboard. You can use the APIs of this module to operate pasteboard content of the plain text, HTML, URI, Want, pixel map, and other types. @@ -120,11 +120,11 @@ Enumerates the paste options of data. **System capability**: SystemCapability.MiscServices.Pasteboard -| Name | Description | -| ----- | ----------------------- | -| InApp |Only intra-application pasting is allowed.| -| LocalDevice |Paste is allowed in any application on the local device.| -| CrossDevice |Paste is allowed in any application across devices.| +| Name| Value| Description | +| ---- |---|-------------------| +| InApp | 0 | Only intra-application pasting is allowed. | +| LocalDevice | 1 | Paste is allowed in any application on the local device.| +| CrossDevice | 2 | Paste is allowed in any application across devices. | ## pasteboard.createHtmlData(deprecated) @@ -418,7 +418,7 @@ Forcibly converts the content in a **PasteData** object to text. This API uses a **Example** ```js -let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +let record = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); record.convertToTextV9((err, data) => { if (err) { console.error(`Failed to convert to text. Cause: ${err.message}`); @@ -445,7 +445,7 @@ Forcibly converts the content in a **PasteData** object to text. This API uses a **Example** ```js -let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +let record = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); record.convertToTextV9().then((data) => { console.info(`Succeeded in converting to text. Data: ${data}`); }).catch((err) => { @@ -536,7 +536,7 @@ Obtains the plain text of the primary record. **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let plainText = pasteData.getPrimaryText(); ``` @@ -558,7 +558,7 @@ Obtains the HTML content of the primary record. ```js let html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -let pasteData = pasteboard.createHtmlData(html); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_HTML, html); let htmlText = pasteData.getPrimaryHtml(); ``` @@ -583,7 +583,7 @@ let object = { bundleName: "com.example.aafwk.test", abilityName: "com.example.aafwk.test.TwoAbility" }; -let pasteData = pasteboard.createWantData(object); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_WANT, object); let want = pasteData.getPrimaryWant(); ``` @@ -604,7 +604,7 @@ Obtains the URI of the primary record. **Example** ```js -let pasteData = pasteboard.createUriData('dataability:///com.example.myapplication1/user.txt'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); let uri = pasteData.getPrimaryUri(); ``` @@ -636,7 +636,7 @@ let opt = { scaleMode: 1 }; image.createPixelMap(buffer, opt).then((pixelMap) => { - let pasteData = pasteboard.createData('app/xml',pixelMap); + let pasteData = pasteboard.createData(MIMETYPE_PIXELMAP, pixelMap); let PixelMap = pasteData.getPrimaryPixelMap(); }); ``` @@ -660,10 +660,10 @@ The pasteboard supports a maximum number of 512 data records. **Example** ```js -let pasteData = pasteboard.createUriData('dataability:///com.example.myapplication1/user.txt'); -let textRecord = pasteboard.createPlainTextRecord('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); +let textRecord = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -let htmlRecord = pasteboard.createHtmlTextRecord(html); +let htmlRecord = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_HTML, html); pasteData.addRecord(textRecord); pasteData.addRecord(htmlRecord); ``` @@ -695,7 +695,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er **Example** ```js - let pasteData = pasteboard.createUriData('dataability:///com.example.myapplication1/user.txt'); + let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); let dataXml = new ArrayBuffer(256); pasteData.addRecord('app/xml', dataXml); ``` @@ -717,7 +717,7 @@ Obtains a list of **mimeTypes** objects in [PasteDataProperty](#pastedatapropert **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let types = pasteData.getMimeTypes(); ``` @@ -738,7 +738,7 @@ Obtains the data type of the primary record in this pasteboard. **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let type = pasteData.getPrimaryMimeType(); ``` @@ -759,7 +759,7 @@ Obtains the property of the pasteboard data. **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let property = pasteData.getProperty(); ``` @@ -780,7 +780,7 @@ Sets the property (attributes) for the pasteboard data. Currently, only the **sh **Example** ```js -let pasteData = pasteboard.createHtmlData('application/xml'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_HTML, 'application/xml'); let prop = pasteData.getProperty(); prop.shareOption = pasteboard.ShareOption.InApp; pasteData.setProperty(prop); @@ -817,7 +817,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let record = pasteData.getRecord(0); ``` @@ -838,7 +838,7 @@ Obtains the number of records in the pasteboard. **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let count = pasteData.getRecordCount(); ``` @@ -859,7 +859,7 @@ Obtains the custom tag from the pasteboard. If no custom tag is set, null is ret **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let tag = pasteData.getTag(); ``` @@ -886,7 +886,7 @@ Checks whether the pasteboard contains data of the specified type. **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); let hasType = pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN); ``` @@ -915,7 +915,7 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); pasteData.removeRecord(0); ``` @@ -945,8 +945,8 @@ For details about the error codes, see [Pasteboard Error Codes](../errorcodes/er **Example** ```js -let pasteData = pasteboard.createPlainTextData('hello'); -let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, 'hello'); +let record = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_URI, 'dataability:///com.example.myapplication1/user.txt'); pasteData.replaceRecord(0, record); ``` ### addHtmlRecord(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md new file mode 100644 index 0000000000000000000000000000000000000000..03e049e9a1bb1076f770bd2d89dc25455c453ee6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -0,0 +1,40 @@ +# PermissionRequestResult + +The **PermissionRequestResult** module defines the result of a permission request. The result is returned when [requestPermissionsFromUser](js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called to request permissions. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Attributes + +**System capability**: SystemCapability.Security.AccessToken + +| 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.| + +## Usage + +The permission request result is obtained through an **atManager** instance. + +**Example** +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }).catch((err) => { + console.info("data:" + JSON.stringify(err)); + }) +} catch(err) { + 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 dfc05166987a87d07bc1499fbcb980b45f08f2e8..8ccc7d7fb4bc1a5f876b8da75c181f8547e32f51 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -1,7 +1,6 @@ # @ohos.util.PlainArray (Nonlinear Container PlainArray) > **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. **PlainArray** stores key-value (KV) pairs. Each key must be unique, be of the number type, and have only one value. @@ -21,6 +20,8 @@ This topic uses the following to identify the use of generics: import PlainArray from '@ohos.util.PlainArray'; ``` + + ## PlainArray ### Attributes @@ -42,7 +43,7 @@ A constructor used to create a **PlainArray** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -71,7 +72,7 @@ Checks whether this container is empty. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -107,7 +108,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -145,7 +146,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -183,7 +184,7 @@ Obtains the index of the first occurrence of an element with the specified key i **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -221,7 +222,7 @@ Obtains the index of the first occurrence of an element with the specified value **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -259,7 +260,7 @@ Obtains the key of the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -284,24 +285,24 @@ Obtains the value of 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 | Returns the value of the element if obtained; returns **undefined** otherwise.| + | Type| Description| + | -------- | -------- | + | T | Returns the value of the element if obtained; returns **undefined** otherwise.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -328,7 +329,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -361,7 +362,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -397,7 +398,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -435,7 +436,7 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -474,12 +475,12 @@ Removes elements in a specified range from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeRangeFrom method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -508,12 +509,12 @@ Sets a value for an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The parameter value is out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -541,7 +542,7 @@ Obtains a string that contains all elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -567,7 +568,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -607,7 +608,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -641,7 +642,7 @@ Obtains an iterator object that contains key-value pairs, where the key is of th **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index ed71da2336509844e7baa5eea49f8a026e969eba..fc74447111636244fb54e604dba5c458a6e6e061 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -1,9 +1,8 @@ -# Mouse Pointer +# @ohos.multimodalInput.pointer (Mouse Pointer) -The mouse pointer module provides APIs related to pointer attribute management. +The **pointer** module provides APIs related to pointer attribute management. -> **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. ## Modules to Import @@ -122,9 +121,13 @@ Checks the visible status of the mouse pointer. This API uses a promise to retur **Example** ```js -pointer.isPointerVisible().then((visible) => { - console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); -}); +try { + pointer.isPointerVisible().then((visible) => { + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); + }); +} catch (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` ## pointer.setPointerSpeed9+ @@ -276,7 +279,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -319,7 +322,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -358,7 +361,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -396,7 +399,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index 1c78452681d08db91a4aa3ee4cf2aea785072191..4dc07d44197a78f01cb3e9018293cc1da88bea38 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,8 +1,8 @@ -# Power Manager +# @ohos.power (System Power Management) -The Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status. +The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -87,7 +87,7 @@ try { isActive(): boolean -Checks whether the current device is active. +Checks whether the current device is active. In the active state, the screen is on if the device has a screen and the device is not in sleep state if the device does not have a screen. **System capability:** SystemCapability.PowerManager.PowerManager.Core diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index cf518ed93a2aea668985ae96031b12d48e284811..c7da8609952d245b53e82aead09f57f97eeeedf1 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,4 +1,4 @@ -# Privacy Management +# @ohos.privacyManager (Privacy Management) The **privacyManager** module provides APIs for privacy management, such as management of permission usage records. @@ -42,11 +42,14 @@ The permission usage record includes the application identity (token ID) of the **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -89,11 +92,14 @@ The permission usage record includes the application identity (token ID) of the **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -139,11 +145,14 @@ Obtains historical permission usage records. This API uses a promise to return t **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. the value of flag in request is invalid. | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -191,11 +200,14 @@ Obtains historical permission usage records. This API uses an asynchronous callb **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. the value of flag in request is invalid. | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -251,12 +263,15 @@ Starts to use a permission and flushes the permission usage record. This API is **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -296,12 +311,15 @@ Starts to use a permission and flushes the permission usage record. This API is **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -324,7 +342,7 @@ try { ## privacyManager.stopUsingPermission -stopUsingPermission(tokenID: number, permissionName: string): Promise<void> +stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<void> Stops using a permission. This API is called by a system application and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. This API uses a promise to return the result. @@ -348,12 +366,15 @@ Stops using a permission. This API is called by a system application and uses a **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -393,12 +414,15 @@ Stops using a permission. This API is called by a system application and uses a **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -434,26 +458,29 @@ Subscribes to the permission usage status changes of the specified permissions. | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | No | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | +| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in the permission usage.| **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100004 | The interface is not used together. | -| 12100005 | The number of listeners exceeds the limit. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100004 | The interface is called repeatedly with the same input. | +| 12100005 | The registration time has exceeded the limitation. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList = []; try { - atManager.on('activeStateChange', permissionNameList, (data) => { + privacyManager.on('activeStateChange', permissionNameList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); }); } catch(err) { @@ -476,23 +503,26 @@ Unsubscribes from the permission usage status changes of the specified permissio | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | No | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| +| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The permissionName in list is all invalid or the list size is larger than 1024. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList = []; try { privacyManager.off('activeStateChange', permissionNameList); }catch(err) { @@ -589,7 +619,7 @@ Enumerates the permission usage statuses. **System capability**: SystemCapability.Security.AccessToken -| Name | Default Value| Description | +| Name | Value | Description | | ------------------------- | ------ | ---------------- | | PERM_INACTIVE | 0 | The permission is not used. | | PERM_ACTIVE_IN_FOREGROUND | 1 | The permission is being used by an application running in the foreground.| diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 1fd0357783d6cf3ead6913cfc07a0e4b4e1c3c82..a7ba5ea9bd9420837a3b204c98aa36835634a681 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,4 +1,4 @@ -# Prompt +# @ohos.prompt (Prompt) The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. @@ -146,11 +146,11 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the dialog box. | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Text body. | -| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Text body. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -158,9 +158,9 @@ Describes the dialog box response result. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Description | -| ----- | ------ | ------------------- | -| index | number | Index of the selected button in the **buttons** array.| +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------- | +| index | number | No | Index of the selected button in the **buttons** array.| ## prompt.showActionMenu @@ -255,10 +255,10 @@ Describes the options for showing the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | -| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?] | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md index 268673b046bbb5f775dfffe3986105718319d009..2d01a8db31a0a0f01f62ce4747ef2d6449b348e3 100644 --- a/en/application-dev/reference/apis/js-apis-promptAction.md +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -1,4 +1,4 @@ -# Prompt +# @ohos.promptAction (Prompt) The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. @@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -181,11 +181,11 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | -| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Text body. | -| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Text body. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -193,9 +193,9 @@ Describes the dialog box response result. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Description | -| ----- | ------ | ------------------- | -| index | number | Index of the selected button in the **buttons** array.| +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------- | +| index | number | No | Index of the selected button in the **buttons** array.| ## promptAction.showActionMenu @@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -314,10 +314,10 @@ Describes the options for showing the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | -| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?] | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 57ce3f7b301c42167b6af3830e39949afd76f719..e4adf559e862ddc954b7e75c3253fb8aa95b6b2a 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -1,7 +1,6 @@ # @ohos.util.Queue (Linear Container Queue) > **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. **Queue** follows the principle of First In First Out (FIFO). It supports insertion of elements at the end and removal from the front of the queue. **Queue** is implemented based on the queue data structure. @@ -41,7 +40,7 @@ A constructor used to create a **Queue** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -76,7 +75,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -110,7 +109,7 @@ Removes the first element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -144,7 +143,7 @@ Obtains the first element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -187,7 +186,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -222,7 +221,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 91c6be9cd7d076dbb72a502e64363d729668972f..dfb1dd75061b1bb272170b5dbd7c202d320ce304 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1,6 +1,6 @@ -# Radio +# @ohos.telephony.radio (Network Search) -The radio module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. +The **radio** module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 81717b6ebd1ed56470b9992e1f2fc69b546c035a..29b20c42950323df2346d817922f178d71d11a80 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,8 +1,8 @@ -# reminderAgent +# @ohos.reminderAgent (reminderAgent) The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. -You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. > **NOTE** > @@ -13,14 +13,16 @@ You can set your application to use the reminder agent APIs to create scheduled ## Modules to Import -```js +```ts import reminderAgent from'@ohos.reminderAgent'; ``` ## reminderAgent.publishReminder -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void +```ts +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void +``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -33,14 +35,15 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Example** -```js +```ts let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + reminderAgent.publishReminder(timer, (err, reminderId) => { console.log("callback, reminderId = " + reminderId); }); @@ -49,7 +52,9 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ## reminderAgent.publishReminder -publishReminder(reminderReq: ReminderRequest): Promise<number> +```ts +publishReminder(reminderReq: ReminderRequest): Promise +``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -65,14 +70,15 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Example** -```js +```ts let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + reminderAgent.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); }); @@ -81,7 +87,9 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ## reminderAgent.cancelReminder -cancelReminder(reminderId: number, callback: AsyncCallback<void>): void +```ts +cancelReminder(reminderId: number, callback: AsyncCallback): void +``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -92,11 +100,11 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts reminderAgent.cancelReminder(1, (err, data) => { console.log("cancelReminder callback"); }); @@ -105,7 +113,9 @@ reminderAgent.cancelReminder(1, (err, data) => { ## reminderAgent.cancelReminder -cancelReminder(reminderId: number): Promise<void> +```ts +cancelReminder(reminderId: number): Promise +``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -121,20 +131,21 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts reminderAgent.cancelReminder(1).then(() => { console.log("cancelReminder promise"); }); ``` - ## reminderAgent.getValidReminders -getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void +```ts +getValidReminders(callback: AsyncCallback>): void +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. @@ -144,11 +155,11 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| **Example** -```js +```ts reminderAgent.getValidReminders((err, reminders) => { console.log("callback, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -178,7 +189,9 @@ reminderAgent.getValidReminders((err, reminders) => { ## reminderAgent.getValidReminders -getValidReminders(): Promise<Array<ReminderRequest>> +```ts +getValidReminders(): Promise> +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -188,11 +201,11 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| **Example** -```js +```ts reminderAgent.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -222,7 +235,9 @@ reminderAgent.getValidReminders().then((reminders) => { ## reminderAgent.cancelAllReminders -cancelAllReminders(callback: AsyncCallback<void>): void +```ts +cancelAllReminders(callback: AsyncCallback): void +``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -232,11 +247,11 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts reminderAgent.cancelAllReminders((err, data) =>{ console.log("cancelAllReminders callback") }) @@ -245,7 +260,9 @@ reminderAgent.cancelAllReminders((err, data) =>{ ## reminderAgent.cancelAllReminders -cancelAllReminders(): Promise<void> +```ts +cancelAllReminders(): Promise +``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -255,20 +272,21 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts reminderAgent.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") }) ``` - ## reminderAgent.addNotificationSlot -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void +```ts +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void +``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -279,11 +297,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -297,7 +315,9 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ## reminderAgent.addNotificationSlot -addNotificationSlot(slot: NotificationSlot): Promise<void> +```ts +addNotificationSlot(slot: NotificationSlot): Promise +``` Adds a notification slot. This API uses a promise to return the result. @@ -313,11 +333,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -331,7 +351,9 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void +```ts +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -341,12 +363,12 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { @@ -357,7 +379,9 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType): Promise<void> +```ts +removeNotificationSlot(slotType: notification.SlotType): Promise +``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -367,17 +391,17 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { @@ -392,7 +416,7 @@ Enumerates button types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | ACTION_BUTTON_TYPE_CLOSE | 0 | Button for closing the reminder.| | ACTION_BUTTON_TYPE_SNOOZE | 1 | Button for snoozing the reminder.| @@ -404,7 +428,7 @@ Enumerates reminder types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | REMINDER_TYPE_TIMER | 0 | Countdown reminder.| | REMINDER_TYPE_CALENDAR | 1 | Calendar reminder.| @@ -431,7 +455,7 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| pkgName | string | Yes| Name of the HAP that is redirected to when the reminder notification is clicked.| | abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| @@ -443,7 +467,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the HAP that is automatically started when the reminder arrives and the device is not in use.| | abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| @@ -459,9 +483,9 @@ Defines the reminder to publish. | actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| -| ringDuration | number | No| Ringing duration.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval.| +| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| +| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| +| timeInterval | number | No| Reminder snooze interval, in seconds. The default value is **0**.| | title | string | No| Reminder title.| | content | string | No| Reminder content.| | expiredContent | string | No| Content to be displayed after the reminder expires.| @@ -481,8 +505,8 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array<number> | No| Month in which the reminder repeats.| -| repeatDays | Array<number> | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm @@ -497,7 +521,7 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats.| +| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| ## ReminderRequestTimer diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 7886c278e8870986e83535886e680cd1d631d302..ab3d0f116871392e6cdbf0c004b9c418c5660e16 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,8 +1,8 @@ -# reminderAgentManager +# @ohos.reminderAgentManager (reminderAgentManager) The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. -You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. > **NOTE** > @@ -11,14 +11,16 @@ You can set your application to use the reminder agent APIs to create scheduled ## Modules to Import -``` +```ts import reminderAgentManager from'@ohos.reminderAgentManager'; ``` ## reminderAgentManager.publishReminder -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void +```ts +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void +``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -31,7 +33,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Error codes** @@ -43,11 +45,12 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | 1700002 | The number of reminders exceeds the limit. | **Example** -```js +```ts let timer = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + try { reminderAgentManager.publishReminder(timer, (err, reminderId) => { if (err) { @@ -64,7 +67,9 @@ try { ## reminderAgentManager.publishReminder -publishReminder(reminderReq: ReminderRequest): Promise<number> +```ts +publishReminder(reminderReq: ReminderRequest): Promise +``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -80,7 +85,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Error codes** @@ -92,11 +97,12 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | 1700002 | The number of reminders exceeds the limit. | **Example** -```js +```ts let timer = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + try { reminderAgentManager.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); @@ -111,7 +117,9 @@ try { ## reminderAgentManager.cancelReminder -cancelReminder(reminderId: number, callback: AsyncCallback<void>): void +```ts +cancelReminder(reminderId: number, callback: AsyncCallback): void +``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -122,7 +130,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Error codes** @@ -135,7 +143,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelReminder(1, (err, data) => { if (err) { @@ -152,7 +160,9 @@ try { ## reminderAgentManager.cancelReminder -cancelReminder(reminderId: number): Promise<void> +```ts +cancelReminder(reminderId: number): Promise +``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -168,7 +178,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -181,7 +191,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelReminder(1).then(() => { console.log("cancelReminder promise"); @@ -193,10 +203,12 @@ try { }; ``` - ## reminderAgentManager.getValidReminders -getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void +```ts +getValidReminders(callback: AsyncCallback>): void + +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. @@ -206,7 +218,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| **Error codes** @@ -218,7 +230,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.getValidReminders((err, reminders) => { if (err) { @@ -253,10 +265,11 @@ try { }; ``` - ## reminderAgentManager.getValidReminders -getValidReminders(): Promise<Array<ReminderRequest>> +```ts +getValidReminders(): Promise> +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -266,7 +279,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| **Error codes** @@ -278,7 +291,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); @@ -314,7 +327,9 @@ try { ## reminderAgentManager.cancelAllReminders -cancelAllReminders(callback: AsyncCallback<void>): void +```ts +cancelAllReminders(callback: AsyncCallback): void +``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -324,7 +339,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Error codes** @@ -336,7 +351,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelAllReminders((err, data) =>{ if (err) { @@ -353,7 +368,9 @@ try { ## reminderAgentManager.cancelAllReminders -cancelAllReminders(): Promise<void> +```ts +cancelAllReminders(): Promise +``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -363,7 +380,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -375,7 +392,7 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err **Example** -```js +```ts try { reminderAgentManager.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") @@ -390,7 +407,9 @@ try { ## reminderAgentManager.addNotificationSlot -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void +```ts +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void +``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -401,11 +420,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -427,7 +446,9 @@ try { ## reminderAgentManager.addNotificationSlot -addNotificationSlot(slot: NotificationSlot): Promise<void> +```ts +addNotificationSlot(slot: NotificationSlot): Promise +``` Adds a notification slot. This API uses a promise to return the result. @@ -443,11 +464,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -467,7 +488,9 @@ try { ## reminderAgentManager.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void +```ts +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -478,11 +501,11 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' try { @@ -501,7 +524,9 @@ try { ## reminderAgentManager.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType): Promise<void> +```ts +removeNotificationSlot(slotType: notification.SlotType): Promise +``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -517,11 +542,11 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' try { @@ -580,7 +605,7 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| pkgName | string | Yes| Name of the HAP that is redirected to when the reminder notification is clicked.| | abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| @@ -592,7 +617,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the HAP that is automatically started when the reminder arrives and the device is not in use.| | abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| @@ -608,9 +633,9 @@ Defines the reminder to publish. | actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| -| ringDuration | number | No| Ringing duration, in seconds.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval, in seconds.| +| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| +| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| +| timeInterval | number | No| Reminder snooze interval, in seconds. The default value is **0**.| | title | string | No| Reminder title.| | content | string | No| Reminder content.| | expiredContent | string | No| Content to be displayed after the reminder expires.| @@ -630,8 +655,8 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array<number> | No| Month in which the reminder repeats.| -| repeatDays | Array<number> | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm @@ -646,7 +671,7 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| +| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| ## ReminderRequestTimer diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 5cf97609d706bcf49319962f204635c04ca23663..d3a0eeb30ea75a3109b6917d50b7b1d24cdd2fb4 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,9 +1,8 @@ -# @ohos.request +# @ohos.request (Upload and Download) The **request** module provides applications with basic upload, download, and background transmission agent capabilities. -> **NOTE** -> +> **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. diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 865f1104386664ce5b4cafede20ec54ffab711a6..7dc343709c19421175b4f99e6308c1c0ad90e5dd 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,4 +1,4 @@ -# Resource Manager +# @ohos.resourceManager (Resource Manager) The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density. @@ -15,10 +15,8 @@ import resourceManager from '@ohos.resourceManager'; ## Instruction -Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object. - -For details about how to reference **context** in the stage model, see Context in the Stage Model. - +Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. +For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). ```ts import Ability from '@ohos.application.Ability'; diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index 03645ac62b8ec51c616fbfd6e923aef203a52ad6..d5daa5d41e299d368b7d38af4428856bf343c516 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -236,7 +236,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba | --------- | ---------------------------------- | ---- | ---------------------------------------- | | 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).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -256,7 +256,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; @@ -268,13 +268,13 @@ function callback(error, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -310,7 +310,7 @@ Requests a continuous task from the system. This API uses a promise to return th | --------- | ---------------------------------- | ---- | ---------------------------------------- | | 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).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** @@ -335,17 +335,17 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -401,7 +401,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; function callback(error, data) { @@ -412,7 +412,7 @@ function callback(error, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context, callback); @@ -462,10 +462,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 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 b423c712999053c8a00d0b8503525cd03ce1cdf8..1e243a9881594c4acf692110cfe2a2e7a363b945 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -219,8 +219,8 @@ Queries the application usage duration statistics based on the specified start t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<[BundleStatsMap](#bundlestatsmap)> | Yes | Callback used to return the application usage duration statistics.| **Error codes** @@ -274,8 +274,8 @@ Queries the application usage duration statistics based on the specified start t | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -333,8 +333,8 @@ Queries the application usage duration statistics in the specified time frame at | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried. | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleStatsInfo](#bundlestatsinfo)>> | Yes | Callback used to return the application usage duration statistics.| **Error codes** @@ -387,8 +387,8 @@ Queries the application usage duration statistics in the specified time frame at | Name | Type | Mandatory | Description | | ---------- | ----------------------------- | ---- | ----- | | byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried.| -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -443,8 +443,8 @@ Queries events of all applications based on the specified start time and end tim | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleEvents](#bundleevents)>> | Yes | Callback used to return the events obtained.| **Error codes** @@ -496,8 +496,8 @@ Queries events of all applications based on the specified start time and end tim | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -548,8 +548,8 @@ Queries events of this application based on the specified start time and end tim | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleEvents](#bundleevents)>> | Yes | Callback used to return the events obtained.| **Error codes** @@ -597,8 +597,8 @@ Queries events of this application based on the specified start time and end tim | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1276,8 +1276,8 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1329,8 +1329,8 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback<Arr | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[DeviceEventStats](#deviceeventstats)>> | Yes | Callback used to return the result. | **Error codes** @@ -1379,8 +1379,8 @@ Queries the number of notifications from all applications based on the specified | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1432,8 +1432,8 @@ Queries the number of notifications from all applications based on the specified | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[DeviceEventStats](#deviceeventstats)>> | Yes | Callback used to return the result. | **Error codes** @@ -1476,7 +1476,7 @@ Provides the information about the FA usage. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ----------------------------- | | deviceId | string | No | ID of the device to which the FA belongs. | -| bundleName | string | Yes | Name of the application bundle to which the FA belongs. | +| bundleName | string | Yes | Name of the bundle to which the FA belongs. | | moduleName | string | Yes | Name of the module to which the FA belongs. | | abilityName | string | No | **MainAbility** name of the FA. | | appLabelId | number | No | Application label ID of the FA. | 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 77638dbfe38acf986f1b632349253c9ceb9496ed..70f20b743d5ee09f2c79877ab626d76fdaeb0d95 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,4 +1,4 @@ -# @ohos.resourceschedule.workScheduler +# @ohos.resourceschedule.workScheduler (workScheduler) The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 75d75ddb09e5c9e7d5d7028b02295cf24e8cf57e..80451d894a244a7cd2c1f91e4d4fed86cf1f898e 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -1,4 +1,4 @@ -# @ohos.router +# @ohos.router (Page Routing) The **Router** module provides APIs to access pages through URLs. You can use the APIs to navigate to a specified page in an application, replace the current page with another one in an application, and return to the previous page or a specified page. @@ -804,7 +804,7 @@ router.replace({ }); ``` - ## router.replace(deprecated) +## router.replace(deprecated) replace(options: RouterOptions, mode: RouterMode): void diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 94757432a9c16fa471fb98629b63387594542e65..8fc776d5508dccfd04155a3952936743de8e711c 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,6 +1,6 @@ -# @ohos.rpc +# @ohos.rpc (RPC) -The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. +The **rpc** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index e3718c5878ccae3e63f8bdfae8b37061599fffda..ee70e09ca874602bf8e41f3d4001b61caa5a0344 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,8 +1,8 @@ -# RunningLock +# @ohos.runningLock (Runninglock) -The RunningLock module provides APIs for creating, querying, holding, and releasing running locks. +The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks. -> **NOTE** +> **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index 9dcef8737df6eec61080fdbc7569ed7d4eb4a238..c726ec7c8fdd4cd6f16d71f5a6892bc565b66cf6 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,4 +1,4 @@ -# @ohos.screenLock +# @ohos.screenLock (Screenlock) The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set. diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 0f5d909e9b038c65bcd353afae633495a9bd2c4b..22f25f8f0185b954270c2169fc657f0676244623 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,4 +1,4 @@ -# Screen +# @ohos.screen (Screen) The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md index d61e7c1b5a08c7dcdb841742a8359bac5e12ad69..65a4ac2a29a971ba15f88ea4597189024c2877fd 100644 --- a/en/application-dev/reference/apis/js-apis-securityLabel.md +++ b/en/application-dev/reference/apis/js-apis-securityLabel.md @@ -1,8 +1,8 @@ -# Security Label +# @ohos.securityLabel (Data Label) The **secuityLabel** module provides APIs to manage file data security levels, including obtaining and setting file data security levels. -> **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 6fdc718f8df4868cb7e7f9c12f2346b36032b953..69845e5552e2c21cb49852513e837c7976dcb8b3 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1,8 +1,9 @@ -# Sensor +# @ohos.sensor (Sensor) The **Sensor** module provides APIs for obtaining the sensor list and subscribing to sensor data. It also provides some common sensor algorithms. > **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. @@ -3495,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/s2.| -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| +| 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 @@ -3509,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/s2.| -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| +| 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 @@ -3523,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/s2. | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | +| 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 @@ -3540,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/s2.| -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| +| 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 diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 5972e0cd9a278dcc49b634b6d05e8d76f3fa0a1d..9b846b7edd04be33c3513017821c5977b3fc336b 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,4 +1,4 @@ -# @ohos.settings +# @ohos.settings (Data Item Settings) The **settings** module provides APIs for setting data items. diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 7c415cc718aa72b7d1d098483a73399fc431d7af..eb88ca8c05459fca0ba2ecd4dfcab60d49677aae 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,6 +1,6 @@ -# SIM Management +# @ohos.telephony.sim (SIM Management) -The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. +The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. >**NOTE** > @@ -2934,6 +2934,37 @@ Enumerates contact types. **System capability**: SystemCapability.Telephony.CoreService | Name | Value | Description | -| :-------------- | ---- | ---------- | +| -------------- | ---- | ---------- | | GENERAL_CONTACT | 1 | Common contact number.| | FIXED_DIALING | 2 | Fixed dialing number. | + +## OperatorConfigKey9+ + +Enumerates carrier configuration keys. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ------------------------------------------------------- | ---------------------------------------------------- | -------------------- | +| KEY_VOICE_MAIL_NUMBER_STRING | "voice_mail_number_string" | Voice mailbox number. | +| KEY_IMS_SWITCH_ON_BY_DEFAULT_BOOL | "ims_switch_on_by_default_bool" | Fixed dialing number. | +| KEY_HIDE_IMS_SWITCH_BOOL | "hide_ims_switch_bool" | Whether to hide the IMS switch. | +| KEY_VOLTE_SUPPORTED_BOOL | "volte_supported_bool" | Whether to support VoLTE. | +| KEY_NR_MODE_SUPPORTED_LIST_INT_ARRAY | "nr_mode_supported_list_int_array" | List of supported NR modes. | +| KEY_VOLTE_PROVISIONING_SUPPORTED_BOOL | "volte_provisioning_supported_bool" | Whether to support VoLTE provisioning. | +| KEY_SS_OVER_UT_SUPPORTED_BOOL | "ss_over_ut_supported_bool" | Whether SS over UT is supported. | +| KEY_IMS_GBA_REQUIRED_BOOL | "ims_gba_required_bool" | Whether GBA is required for IMS. | +| KEY_UT_PROVISIONING_SUPPORTED_BOOL | "ut_provisioning_supported_bool" | Whether to support UT provisioning. | +| KEY_IMS_PREFER_FOR_EMERGENCY_BOOL | "ims_prefer_for_emergency_bool" | IMS preferences for emergency. | +| KEY_CALL_WAITING_SERVICE_CLASS_INT | "call_waiting_service_class_int" | Call waiting service. | +| KEY_CALL_TRANSFER_VISIBILITY_BOOL | "call_transfer_visibility_bool" | Call transfer visibility. | +| KEY_IMS_CALL_DISCONNECT_REASONINFO_MAPPING_STRING_ARRAY | "ims_call_disconnect_reasoninfo_mapping_string_array" | List of IMS call disconnection reasons.| +| KEY_FORCE_VOLTE_SWITCH_ON_BOOL | "force_volte_switch_on_bool" | Whether to forcibly turn on VoLTE. | +| KEY_ENABLE_OPERATOR_NAME_CUST_BOOL | "enable_operator_name_cust_bool" | Whether to display the carrier name.| +| KEY_OPERATOR_NAME_CUST_STRING | "operator_name_cust_string" | Carrier name. | +| KEY_SPN_DISPLAY_CONDITION_CUST_INT | "spn_display_condition_cust_int" | SPN display rule. | +| KEY_PNN_CUST_STRING_ARRAY | "pnn_cust_string_array" | PLMN name | +| KEY_OPL_CUST_STRING_ARRAY | "opl_cust_string_array" | PLMN information of the carrier. | +| KEY_EMERGENCY_CALL_STRING_ARRAY | "emergency_call_string_array" | Emergency call list. | diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index e9e32416426bf852590ed7d7a7f9c5e086a89480..901e3b258b7aa73530935baa81a6366f7aa50e65 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -1,6 +1,6 @@ -# SMS +# @ohos.telephony.sms (SMS) -The SMS module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. +The **sms** module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. >**NOTE** > @@ -870,7 +870,7 @@ promise.then(data => { ## sms.isImsSmsSupported8+ -isImsSmsSupported(callback: AsyncCallback): void +isImsSmsSupported(slotId: number, callback: AsyncCallback): void Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result. @@ -882,12 +882,14 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ---------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| **Example** ```js -sms.isImsSmsSupported((err, data) => { +let slotId = 0; +sms.isImsSmsSupported(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -895,7 +897,7 @@ sms.isImsSmsSupported((err, data) => { ## sms.isImsSmsSupported8+ -isImsSmsSupported(): Promise +isImsSmsSupported(slotId: number): Promise Checks whether SMS is supported on IMS. This API uses a promise to return the result. @@ -903,6 +905,12 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re **System capability**: SystemCapability.Telephony.SmsMms +**Parameters** + +| Name| Type | Mandatory | Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + **Return value** | Type | Description | @@ -912,7 +920,8 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re **Example** ```js -let promise = sms.isImsSmsSupported(); +let slotId = 0; +let promise = sms.isImsSmsSupported(slotId); promise.then(data => { console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`); }).catch(err => { diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 1344f4c6ec574ebb464c844350f331d40804cce8..bd14137464ce195f5c61b9d6a53ce6ef79cd3f10 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,7 +1,8 @@ -# Socket Connection +# @ohos.net.socket (Socket Connection) -> **NOTE** -> +The **socket** module implements socket connection management and operation. + +> **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -21,7 +22,7 @@ Creates a **UDPSocket** object. **Return value** | Type | Description | -| :--------------------------------- | :---------------------- | +| --------------------------------- | ---------------------- | | [UDPSocket](#udpsocket) | **UDPSocket** object.| @@ -87,7 +88,7 @@ Binds the IP address and port number. The port number can be specified or random **Return value** | Type | Description | -| :-------------- | :----------------------------------------- | +| -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -164,7 +165,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p **Return value** | Type | Description | -| :-------------- | :--------------------------------------------- | +| -------------- | --------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -230,7 +231,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result. **Return value** | Type | Description | -| :-------------- | :----------------------------------------- | +| -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -252,7 +253,7 @@ getState\(callback: AsyncCallback\): void Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -292,7 +293,7 @@ getState\(\): Promise Obtains the status of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -302,7 +303,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| :----------------------------------------------- | :----------------------------------------- | +| ----------------------------------------------- | ----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| **Example** @@ -331,7 +332,7 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): voi Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -379,7 +380,7 @@ setExtraOptions\(options: UDPExtraOptions\): Promise Sets other properties of the UDPSocket connection. This API uses a promise to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -395,7 +396,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| :-------------- | :--------------------------------------------------- | +| -------------- | --------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -454,7 +455,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -514,7 +515,7 @@ off\(type: 'listening' | 'close', callback?: Callback\): void Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -579,7 +580,7 @@ off\(type: 'error', callback?: ErrorCallback\): void Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -678,7 +679,7 @@ Creates a **TCPSocket** object. **Return value** | Type | Description | - | :--------------------------------- | :---------------------- | + | --------------------------------- | ---------------------- | | [TCPSocket](#tcpsocket) | **TCPSocket** object.| **Example** @@ -743,7 +744,7 @@ Binds the IP address and port number. The port number can be specified or random **Return value** | Type | Description | -| :-------------- | :------------------------------------------------------- | +| -------------- | ------------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -809,7 +810,7 @@ Sets up a connection to the specified IP address and port number. This API uses **Return value** | Type | Description | -| :-------------- | :--------------------------------------------------------- | +| -------------- | --------------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -831,7 +832,7 @@ send\(options: TCPSendOptions, callback: AsyncCallback\): void Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -873,7 +874,7 @@ send\(options: TCPSendOptions\): Promise Sends data over a TCPSocket connection. This API uses a promise to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -889,7 +890,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re **Return value** | Type | Description | -| :-------------- | :------------------------------------------------- | +| -------------- | ------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -957,7 +958,7 @@ Closes a TCPSocket connection. This API uses a promise to return the result. **Return value** | Type | Description | -| :-------------- | :----------------------------------------- | +| -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -979,7 +980,7 @@ getRemoteAddress\(callback: AsyncCallback\): void Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1018,7 +1019,7 @@ getRemoteAddress\(\): Promise Obtains the remote address of a socket connection. This API uses a promise to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1028,7 +1029,7 @@ Obtains the remote address of a socket connection. This API uses a promise to re **Return value** | Type | Description | -| :------------------------------------------ | :------------------------------------------ | +| ------------------------------------------ | ------------------------------------------ | | Promise<[NetAddress](#netaddress)> | Promise used to return the result.| **Example** @@ -1056,7 +1057,7 @@ getState\(callback: AsyncCallback\): void Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1096,7 +1097,7 @@ getState\(\): Promise Obtains the status of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1106,7 +1107,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| :----------------------------------------------- | :----------------------------------------- | +| ----------------------------------------------- | ----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| @@ -1135,7 +1136,7 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): voi Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1184,7 +1185,7 @@ setExtraOptions\(options: TCPExtraOptions\): Promise Sets other properties of the TCPSocket connection. This API uses a promise to return the result. ->**NOTE** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. **Required permissions**: ohos.permission.INTERNET @@ -1200,7 +1201,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re **Return value** | Type | Description | -| :-------------- | :--------------------------------------------------- | +| -------------- | --------------------------------------------------- | | Promise\ | Promise used to return the result.| @@ -1263,7 +1264,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1324,7 +1325,7 @@ off\(type: 'connect' | 'close', callback?: Callback\): void Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1388,7 +1389,7 @@ off\(type: 'error', callback?: ErrorCallback\): void Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->**NOTE** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1464,7 +1465,7 @@ Creates a **TLSSocket** object. **Return value** | Type | Description | -| :--------------------------------- | :---------------------- | +| --------------------------------- | ---------------------- | | [TLSSocket](#tlssocket9) | **TLSSocket** object.| **Example** @@ -1534,7 +1535,7 @@ Binds the IP address and port number. This API uses a promise to return the resu **Return value** | Type | Description | -| :-------------- | :------------------------------------------------------- | +| -------------- | ------------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1608,7 +1609,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur **Return value** | Type | Description | -| :----------------------------------------------- | :----------------------------------------- | +| ----------------------------------------------- | ----------------------------------------- | | Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1705,7 +1706,7 @@ Sets other properties of the TCPSocket connection after successful binding of th **Return value** | Type | Description | -| :-------------- | :--------------------------------------------------- | +| -------------- | --------------------------------------------------- | | Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -1984,7 +1985,7 @@ Obtains the remote address of a TLSSocket connection. This API uses a promise to **Return value** | Type | Description | -| :------------------------------------------ | :------------------------------------------ | +| ------------------------------------------ | ------------------------------------------ | | Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| **Error codes** @@ -2049,7 +2050,7 @@ Obtains the local digital certificate after a TLSSocket connection is establishe **Return value** -| Type | Description | +| Type | Description | | -------------- | -------------------- | | Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| @@ -2490,7 +2491,7 @@ Defines TLS connection options. | -------------- | ------------------------------------- | --- |-------------- | | address | [NetAddress](#netaddress) | Yes | Gateway address. | | secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| -| ALPNProtocols | Array\ | No| Application Layer Protocol Negotiation (ALPN) protocols. | +| ALPNProtocols | Array\ | Yes| Application Layer Protocol Negotiation (ALPN) protocols. | ## TLSSecureOptions9+ diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index d7c5dcb66c511aa8ade7ad6e4fa94041162f2380..ff8551cad86f3f4c448e08d267548657305c5c9d 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -1,7 +1,6 @@ # @ohos.util.Stack (Linear Container Stack) > **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. **Stack** is implemented based on the array data structure. It follows the principle Last Out First In (LOFI) and supports data insertion and removal at one end. @@ -40,7 +39,7 @@ A constructor used to create a **Stack** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -75,7 +74,7 @@ Adds an element at the top of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -109,7 +108,7 @@ Removes the top element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -143,7 +142,7 @@ Obtains the top element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -182,7 +181,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -225,7 +224,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -260,7 +259,7 @@ Checks whether this container is empty (contains no elements). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -293,7 +292,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md index b9cf5106d4369769056d0ad19ed0b4a37a75f553..59647b01e2595656e49753a120157ab0e0cae153 100644 --- a/en/application-dev/reference/apis/js-apis-statfs.md +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -1,8 +1,9 @@ -# statfs +# @ohos.statfs (statfs) -The statfs module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. +The **statfs** module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. -> **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 86675315d63423d728d2db90afd6b049614ee80a..d4e334afce241aba6a763a0050b7d22897753a4d 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,4 +1,4 @@ -# App Storage Statistics +# @ohos.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. @@ -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 | callback: AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| **Example** @@ -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 | callback: AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| + | callback | AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| **Example** @@ -173,7 +173,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| + | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the space information obtained.| **Example** @@ -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 | callback: AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| + | callback | AsyncCallback<[Bundlestats](#bundlestats9)> | Yes | Callback invoked to return the space information obtained.| **Example** @@ -229,7 +229,7 @@ Asynchronously obtains space information of the current third-party application. | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | + | Promise<[Bundlestats](#bundlestats9)> | Promise used to return the space information obtained. | **Example** @@ -250,7 +250,7 @@ Asynchronously obtains space information of the current third-party application. | Name | Type | Mandatory | Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback: AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | + | callback | AsyncCallback<[BundleStats](#bundlestats9)> | Yes | Callback invoked to return the space information obtained. | **Example** @@ -270,11 +270,11 @@ Asynchronously obtains space information of the current third-party application. This is a system API and cannot be called by third-party applications. -| Name | Type | Description | -| --------- | ------ | -------------- | -| appSize | number | Size of the application. | -| cacheSize | number | Cache size of the application. | -| dataSize | number | Total data size of the application.| +| 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.| ## storageStatistics.getTotalSize9+ @@ -322,7 +322,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory | Description | | -------- | ------------------------------------ | ---- | ------------------------ | - | callback | 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 total space of the built-in memory card.| **Example** @@ -380,7 +380,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------- | - | callback | 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 memory card.| **Example** @@ -439,7 +439,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | - | callback | callback: AsyncCallback<number> | Yes | Callback used to return the system space obtained.| + | callback | AsyncCallback<number> | Yes | Callback used to return the system space obtained.| **Example** @@ -452,7 +452,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getUserStorageStats9+ -getUserStorageStats(userId? : number): Promise<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. @@ -474,7 +474,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | --------------------- | ---------------- | - | Promise<[StorageStats](#storagestats)> | Promise used to return the information obtained.| + | Promise<[StorageStats](#storagestats9)> | Promise used to return the information obtained.| **Example** @@ -489,7 +489,7 @@ 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. @@ -506,7 +506,7 @@ This is a system API and cannot be called by third-party applications. | 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. | - | callback | callback: AsyncCallback<[StorageStats](#storagestats)> | Yes | Callback invoked to return the information obtained.| + | callback | AsyncCallback<[StorageStats](#storagestats9)> | Yes | Callback invoked to return the information obtained.| **Example** @@ -528,11 +528,11 @@ 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. -| Name | Type | Description | -| --------- | ------ | -------------- | -| total | number | Total space of the built-in memory card. | -| audio | number | Space occupied by audio data. | -| video | number | Space occupied by video data.| -| image | number | Space occupied by image data. | -| file | number | Space occupied by files. | -| app | number | Space occupied by application data.| +| 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.| diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md index e0cf8d10a1e79872dc6d59a908281610fd01ba23..b48e4a8f6233b11ffdef0361280dba6322c9f959 100644 --- a/en/application-dev/reference/apis/js-apis-system-app.md +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -1,6 +1,6 @@ -# Application Context +# @system.app (Application Context) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** > - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -9,8 +9,8 @@ ## Modules to Import -``` -import app from '@system.app'; +```ts +import app from '@system.app' ``` @@ -20,7 +20,9 @@ getInfo(): AppResponse Obtains the declared information in the **config.json** file of an application. -> **Note: ** [`@ohos.bundle`](js-apis-Bundle.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.bundle](js-apis-Bundle.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Lite @@ -32,13 +34,13 @@ Obtains the declared information in the **config.json** file of an application. **Example** - ``` - export default { - getInfo(){ - var info = app.getInfo(); - console.log(JSON.stringify(info)); - } + ```ts +export default { + getInfo() { + let info = app.getInfo() + console.log(JSON.stringify(info)) } +} ``` ## app.terminate @@ -47,17 +49,20 @@ terminate(): void Terminates the current ability. -> **Note: ** [`@ohos.ability.featureAbility`](js-apis-featureAbility.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.ability.featureAbility](js-apis-ability-featureAbility.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Lite **Example** - ``` - export default { - terminate(){ - app.terminate(); - }} + ```ts +export default { + terminate() { + app.terminate() + } +} ``` ## app.requestFullWindow @@ -67,7 +72,9 @@ Requests the application to run in full window. You can call this API when the F This is a system API and cannot be called by third-party applications. -> **Note: ** [`@ohos.window`](js-apis-window.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.window](js-apis-window.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -78,13 +85,14 @@ This is a system API and cannot be called by third-party applications. **Example** - ``` - export default { - requestFullWindow(){ - app.requestFullWindow({ - duration: 200}); - } + ```ts +export default { + requestFullWindow() { + app.requestFullWindow({ + duration: 200 + }) } +} ``` ## app.setImageCacheCount7+ @@ -102,19 +110,19 @@ Sets the maximum number of decoded images that can be cached in the memory to sp **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## app.setImageRawDataCacheSize7+ @@ -132,20 +140,20 @@ Sets the maximum size (in bytes) of the image data cached in the memory before d **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageRawDataCacheSize(104857600) - // Set the upper limit of the memory for caching image data before decoding to 100 MB. (100 x 1024 x 1024 B =104857600 B = 100 MB). - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageRawDataCacheSize(104857600) + // Set the upper limit of the memory for caching image data before decoding to 100 MB. (100 x 1024 x 1024 B =104857600 B = 100 MB). + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## app.setImageFileCacheSize7+ @@ -163,20 +171,20 @@ Sets the maximum size of the image file cache (in bytes) to speed up the loading **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageFileCacheSize(209715200) - // Set the upper limit of the image file cache to 200 MB. (200 x 1024 x 1024 B= 209715200 B = 200 MB). - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageFileCacheSize(209715200) + // Set the upper limit of the image file cache to 200 MB. (200 x 1024 x 1024 B= 209715200 B = 200 MB). + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## AppResponse @@ -213,4 +221,4 @@ Defines the options of the **RequestFullWindow** API. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| duration | number | Yes| Number of animation options.| +| duration | number | Yes| Duration of an animation, in milliseconds.| diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 31959da80f23b90f54ea10883417eec202152d1a..d673a500027654075ff330c916cd22add25abaf6 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,6 +1,6 @@ -# Battery Info +# @system.battery (Battery Information) -This module allows you to query the charging status and remaining power of a device. +The **battery** module allows you to query the charging status and remaining power of a device. > **NOTE** > - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 2773c74397046c44784b65cc458be75eef8c21ea..939e7d7021bc8f93ad7359004de58f525feeee05 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,6 +1,6 @@ -# Screen Brightness +# @system.brightness (Screen Brightness) -This module provides APIs for querying and adjusting the screen brightness and mode. +The **brightness** module provides APIs for querying and adjusting the screen brightness and mode. > **NOTE** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-system-capability.md b/en/application-dev/reference/apis/js-apis-system-capability.md new file mode 100644 index 0000000000000000000000000000000000000000..7949bae9880af5a8e428e62440595a4a6e990da7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-capability.md @@ -0,0 +1,79 @@ +# @ohos.systemCapability (SystemCapability) + +System capability (SysCap) refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. This module provides APIs for querying the set of system capabilities. + +> **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. + + +## Modules to Import + +```ts +import systemcapability from '@ohos.systemCapability' +``` + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(callback: AsyncCallback): void; + +Queries system capabilities. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Developtools.Syscap + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback | Yes| Callback invoked to return the result.| + + +**Example** + +```ts +try { + systemcapability.querySystemCapabilities(function (err, data) { + if (err == undefined) { + console.log("get system capabilities:" + data) + } else { + console.log(" get system capabilities err:" + err.code) + }}); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(): Promise<string> + +Queries system capabilities. This API uses a promise to return the result. + +**System capability**: SystemCapability.Startup.SystemInfo + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the result.| + +**Example** + +```ts +try { + var p = systemcapability.querySystemCapabilities(); + p.then(function (value) { + console.log("get system capabilities: " + value); + }).catch(function (err) { + console.log("get system capabilities error: " + err.code); + }); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +> **NOTE** +> - The system capabilities returned by the preceding APIs are in the form of an encoded numeric string. diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index 6812d87828d55851d375eadba9dab6b2de55560a..dddb6a685f00a8a5a1829e489d43af4a198bdffa 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,6 +1,6 @@ -# Encryption Algorithm +# @system.cipher (Cipher Algorithm) -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -31,7 +31,7 @@ Defines the input parameters of **cipher.rsa()**. | Name | Type | Mandatory| Description | | -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| -| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length.
For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding. | | key | string | Yes | RSA key. It is a public key in encryption and a private key in decryption. | | transformation | string | No | RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | diff --git a/en/application-dev/reference/apis/js-apis-system-date-time.md b/en/application-dev/reference/apis/js-apis-system-date-time.md new file mode 100644 index 0000000000000000000000000000000000000000..b7ea33fa58a283e44810a1a453dc4a01f44f2678 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-date-time.md @@ -0,0 +1,665 @@ +# @ohos.systemDateTime (System Time and Time Zone) + +The **systemDateTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import systemDateTime from '@ohos.systemDateTime'; +``` + +## systemDateTime.setTime + +setTime(time : number, callback : AsyncCallback<void>) : void + +Sets the system time. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ---------------- | +| time | number | Yes | Timestamp to set, in milliseconds. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +// Set the system time to 2021-01-20 02:36:25. +let time = 1611081385000; +try { + systemDateTime.setTime(time, (error) => { + if (error) { + console.info(`Failed to set time. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in setting time`); + }); +} catch(e) { + console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.setTime + +setTime(time : number) : Promise<void> + +Sets the system time. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| time | number | Yes | Timestamp to set, in milliseconds.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +// Set the system time to 2021-01-20 02:36:25. +let time = 1611081385000; +try { + systemDateTime.setTime(time).then(() => { + console.info(`Succeeded in setting time.`); + }).catch((error) => { + console.info(`Failed to set time. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ------------------ | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | + +**Example** + +```js +try { + systemDateTime.getCurrentTime(true, (error, time) => { + if (error) { + console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ---------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | + +**Example** + +```js +try { + systemDateTime.getCurrentTime((error, time) => { + if (error) { + console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since the Unix epoch. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<number> | Promise used to return the time elapsed since the Unix epoch.| + +**Example** + +```js +try { + systemDateTime.getCurrentTime().then((time) => { + console.info(`Succeeded in getting currentTime : ${time}`); + }).catch((error) => { + console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------- | ---- | -------------------------- | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime(true, (error, time) => { + if (error) { + console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | --------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime((error, time) => { + if (error) { + console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| -------------- | -------------------------------- | +| Promise<number> | Promise used to return the time elapsed since system startup, excluding the deep sleep time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime().then((time) => { + console.info(`Succeeded in getting real active time : ${time}`); + }).catch((error) => { + console.info(`Failed to get real active time. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getRealTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ------------------------------- | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + +```js +try { + systemDateTime.getRealTime(true, (error, time) => { + if (error) { + console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getRealTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------- | ---- | --------------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + +```js +try { + systemDateTime.getRealTime((error, time) => { + if (error) { + console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getRealTime + +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. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the time elapsed since system startup, including the deep sleep time.| + +**Example** + +```js +try { + systemDateTime.getRealTime().then((time) => { + console.info(`Succeeded in getting real time : ${time}`); + }).catch((error) => { + console.info(`Failed to get real time. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.setDate + +setDate(date: Date, callback: AsyncCallback<void>): void + +Sets the system date. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------------- | +| date | Date | Yes | Target date to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +let date = new Date(); +try { + systemDateTime.setDate(date, (error) => { + if (error) { + console.info(`Failed to set date. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in setting date.`); + }); +} catch(e) { + console.info(`Failed to set date. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.setDate + +setDate(date: Date): Promise<void> + +Sets the system date. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------- | +| date | Date | Yes | Target date to set.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let date = new Date(); +try { + systemDateTime.setDate(date).then(() => { + console.info(`Succeeded in setting date.`); + }).catch((error) => { + console.info(`Failed to set date. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to set date. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getDate + +getDate(callback: AsyncCallback<Date>): void + +Obtains the current system date. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | --------------------- | +| callback | AsyncCallback<Date> | Yes | Callback used to return the current system date.| + +**Example** + +```js +try { + systemDateTime.getDate((error, date) => { + if (error) { + console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting date : ${date}`);; + }); +} catch(e) { + console.info(`Failed to get date. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getDate + +getDate(): Promise<Date> + +Obtains the current system date. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------------- | +| Promise<Date> | Promise used to return the current system date.| + +**Example** + +```js +try { + systemDateTime.getDate().then((date) => { + console.info(`Succeeded in getting date : ${date}`); + }).catch((error) => { + console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get date. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.setTimezone + +setTimezone(timezone: string, callback: AsyncCallback<void>): void + +Sets the system time zone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | -------------------------- | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + systemDateTime.setTimezone('Asia/Shanghai', (error) => { + if (error) { + console.info(`Failed to set timezone. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in setting timezone.`); + }); +} catch(e) { + console.info(`Failed to set timezone. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.setTimezone + +setTimezone(timezone: string): Promise<void> + +Sets the system time zone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +try { + systemDateTime.setTimezone('Asia/Shanghai').then(() => { + console.info(`Succeeded in setting timezone.`); + }).catch((error) => { + console.info(`Failed to set timezone. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to set timezone. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getTimezone + +getTimezone(callback: AsyncCallback<string>): void + +Obtains the system time zone. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------- | ---- | ------------------------ | +| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Example** + +```js +try { + systemDateTime.getTimezone((error, data) => { + if (error) { + console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in get timezone : ${data}`);; + }); +} catch(e) { + console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`); +} +``` + +## systemDateTime.getTimezone + +getTimezone(): Promise<string> + +Obtains the system time zone. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------- | +| Promise<string> | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Example** + +```js +try { + systemDateTime.getTimezone().then((data) => { + console.info(`Succeeded in getting timezone: ${data}`); + }).catch((error) => { + console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`); +} +``` + +## Supported System Time Zones + +The following table lists the supported system time zones and the respective offset (unit: h) between each time zone and time zone 0. + +| Time Zone | Offset | +| ------------------------------ | --------------------- | +| Antarctica/McMurdo | 12 | +| America/Argentina/Buenos_Aires | -3 | +| Australia/Sydney | 10 | +| America/Noronha | -2 | +| America/St_Johns | -3 | +| Africa/Kinshasa | 1 | +| America/Santiago | -3 | +| Asia/Shanghai | 8 | +| Asia/Nicosia | 3 | +| Europe/Berlin | 2 | +| America/Guayaquil | -5 | +| Europe/Madrid | 2 | +| Pacific/Pohnpei | 11 | +| America/Godthab | -2 | +| Asia/Jakarta | 7 | +| Pacific/Tarawa | 12 | +| Asia/Almaty | 6 | +| Pacific/Majuro | 12 | +| Asia/Ulaanbaatar | 8 | +| America/Mexico_City | -5 | +| Asia/Kuala_Lumpur | 8 | +| Pacific/Auckland | 12 | +| Pacific/Tahiti | -10 | +| Pacific/Port_Moresby | 10 | +| Asia/Gaza | 3 | +| Europe/Lisbon | 1 | +| Europe/Moscow | 3 | +| Europe/Kiev | 3 | +| Pacific/Wake | 12 | +| America/New_York | -4 | +| Asia/Tashkent | 5 | diff --git a/en/application-dev/reference/apis/js-apis-system-device.md b/en/application-dev/reference/apis/js-apis-system-device.md index 6da9ae481fe8ef4aeb440090f478fb1069596882..bb56a0899e3f3646d6138e8acb21fbae0244070f 100644 --- a/en/application-dev/reference/apis/js-apis-system-device.md +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -1,4 +1,4 @@ -# @system.device +# @system.device (Device Information) The **device** module provides APIs for checking information about the current device. diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index fd4fba8512b1cdecae82339ef31a4b293f022aef..f1ada5f0f2e7df99e3aa9889889d66eece5b2b3f 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -1,6 +1,7 @@ # Geographic Location > **NOTE** +> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.geolocation`](js-apis-geolocation.md). > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-mediaquery.md b/en/application-dev/reference/apis/js-apis-system-mediaquery.md index 841cebeb1da0380128d3704650a0aaf9ef095d5f..bc415bc3375ebfd278dd218bdec4ab48f0f51694 100644 --- a/en/application-dev/reference/apis/js-apis-system-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-system-mediaquery.md @@ -1,4 +1,4 @@ -# Media Query +# @system.mediaquery (Media Query) The **mediaquery** module provides different styles for different media types. @@ -12,7 +12,7 @@ The **mediaquery** module provides different styles for different media types. ## Modules to Import -``` +```ts import mediaquery from '@system.mediaquery'; ``` @@ -39,8 +39,8 @@ Creates a **MediaQueryList** object based on the query condition. **Example** -``` -var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); +```ts +let mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); ``` ## MediaQueryEvent @@ -97,7 +97,7 @@ Adds a listener for this **MediaQueryList** object. The listener must be added b **Example** -``` +```ts function maxWidthMatch(e){ if(e.matches){ // do something @@ -123,7 +123,7 @@ Removes the listener for this **MediaQueryList** object. **Example** -``` +```ts function maxWidthMatch(e){ if(e.matches){ // do something diff --git a/en/application-dev/reference/apis/js-apis-system-network.md b/en/application-dev/reference/apis/js-apis-system-network.md index 1bf121889896276a676f177300f341da5fb327fe..a0b69a4dba4644451020ec49368117bcb1e98f91 100644 --- a/en/application-dev/reference/apis/js-apis-system-network.md +++ b/en/application-dev/reference/apis/js-apis-system-network.md @@ -1,8 +1,8 @@ -# Network State +# @system.network (Network State) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. +> **NOTE** > +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index ab3ae31887d1a2c55eb94c0164573834321e96c0..db74b6b6c4e725c68f47419997bbecb1362da435 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -1,4 +1,4 @@ -# @ohos.systemParameter +# @ohos.systemParameter (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 diff --git a/en/application-dev/reference/apis/js-apis-system-parameterV9.md b/en/application-dev/reference/apis/js-apis-system-parameterV9.md index 23ad27a04596da4b52bc254c931670845f39fb5f..97e9b165f31c640c52593ae8d1c8d8969862b8e8 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameterV9.md +++ b/en/application-dev/reference/apis/js-apis-system-parameterV9.md @@ -1,4 +1,4 @@ -# SystemParameter +# SystemParameter (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 diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md index e37601dbfa3ec72d13a7722fb4dc56a8b3fe6fef..5f33952a9d0d8401ae69f683f0cd4f1eb7dd43f4 100644 --- a/en/application-dev/reference/apis/js-apis-system-prompt.md +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -1,4 +1,6 @@ -# Prompt +# @system.prompt (Prompt) + +The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-system-request.md b/en/application-dev/reference/apis/js-apis-system-request.md index a2b939bf7d0983a25202fe11b7c5dd4ddd9d3665..82ba741d0964faa44066b5d43568b4fa25316f87 100644 --- a/en/application-dev/reference/apis/js-apis-system-request.md +++ b/en/application-dev/reference/apis/js-apis-system-request.md @@ -1,10 +1,10 @@ -# @system.request +# @system.request (Upload and Download) The **system.request** module provides applications with basic upload and download capabilities. > **NOTE** -> - The APIs of this module are deprecated since API version 9. You are advised to use [`@ohos.request`](js-apis-request.md) instead. > +> - The APIs of this module are deprecated since API version 9. You are advised to use [`@ohos.request`](js-apis-request.md) instead. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index 60e999026e58bb6510a24540609f9c6bc44aa55d..6e45d6c012ee2ba4ff6664e1f68ffcd38f9d7570 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -1,4 +1,4 @@ -# Page Routing +# @system.router (Page Routing) The **Router** module provides APIs to access pages through URIs. @@ -43,8 +43,8 @@ export default { data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }); } } @@ -67,7 +67,8 @@ export default { } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The page routing stack supports a maximum of 32 pages. @@ -94,8 +95,8 @@ export default { router.replace({ uri: 'pages/detail/detail', params: { - data1: 'message', - }, + data1: 'message' + } }); } } @@ -135,7 +136,7 @@ Returns to the previous page or a specified page. export default { indexPushPage() { router.push({ - uri: 'pages/detail/detail', + uri: 'pages/detail/detail' }); } } @@ -147,7 +148,7 @@ export default { export default { detailPushPage() { router.push({ - uri: 'pages/mall/mall', + uri: 'pages/mall/mall' }); } } @@ -183,7 +184,8 @@ export default { } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. ## router.getParams @@ -237,7 +239,7 @@ Obtains the number of pages in the current stack. ```js export default { getLength() { - var size = router.getLength(); + let size = router.getLength(); console.log('pages stack size = ' + size); } } @@ -262,7 +264,7 @@ Obtains state information about the current page. ```js export default { getState() { - var page = router.getState(); + let page = router.getState(); console.log('current index = ' + page.index); console.log('current name = ' + page.name); console.log('current path = ' + page.path); @@ -296,7 +298,7 @@ export default { }, cancel: function() { console.log('cancel'); - }, + } }); } } @@ -327,7 +329,7 @@ export default { }, cancel: function() { console.log('cancel'); - }, + } }); } } @@ -339,10 +341,10 @@ Defines the page routing parameters. **System capability**: SystemCapability.ArkUI.ArkUI.Lite -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| +| Name | Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| +| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| ## BackRouterOptions @@ -351,10 +353,10 @@ Defines the parameters for routing back. **System capability**: The items in the table below require different system capabilities. For details, see the table. -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| -| params | Object | No | Data that needs to be passed to the target page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| Name | Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| params | object | No | Data that needs to be passed to the target page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| ## RouterState diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index 7df5f6675bb53168935ada36ca1d0675e49da978..30bfc60e3339b8102fbe6f4a6c5fc1202015da11 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -1,4 +1,4 @@ -# Sensor +# @system.sensor (Sensor) The **Sensor** module provides APIs for querying the sensor list, subscribing to or unsubscribing from sensor data, and executing control commands. @@ -21,9 +21,9 @@ import sensor from '@system.sensor'; ## Error Codes -| Error Code | Description | -| ---------- | ---------------------------------------- | -| 900 | The current device does not support the corresponding sensor. | +| Error Code | Description | +| ---- | -------------- | +| 900 | The current device does not support the corresponding sensor.| ## sensor.subscribeAccelerometer @@ -37,19 +37,19 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the acceleration sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the acceleration sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | --------------------------- | -| x | number | Acceleration on the x-axis. | -| y | number | Acceleration on the y-axis. | -| z | number | Acceleration on the z-axis. | +| Name | Type | Description | +| ---- | ------ | ------- | +| x | number | Acceleration on the x-axis.| +| y | number | Acceleration on the y-axis.| +| z | number | Acceleration on the z-axis.| **Example** @@ -68,7 +68,6 @@ sensor.subscribeAccelerometer({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeAccelerometer @@ -97,16 +96,16 @@ Subscribes to data changes of the compass sensor. If this API is called multiple **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the compass sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | --------------- | +| success | Function | Yes | Called when the compass sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------------------------------ | -| direction | number | Direction of the device, in degrees. | +| Name | Type | Description | +| --------- | ------ | ---------- | +| direction | number | Direction of the device, in degrees.| **Example** @@ -122,7 +121,6 @@ sensor.subscribeCompass({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeCompass @@ -149,16 +147,16 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the proximity sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ----------------- | +| success | Function | Yes | Called when the proximity sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | ---------------------------------------- | -| distance | number | Distance between a visible object and the device screen. | +| Name | Type | Description | +| -------- | ------ | --------------------- | +| distance | number | Distance between a visible object and the device screen.| **Example** @@ -174,7 +172,6 @@ sensor.subscribeProximity({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeProximity @@ -201,16 +198,16 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the ambient light sensor data changes | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | --------------- | +| success | Function | Yes | Called when the ambient light sensor data changes| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------------------ | -| intensity | number | Light intensity, in lux. | +| Name | Type | Description | +| --------- | ------ | ------------ | +| intensity | number | Light intensity, in lux.| **Example** @@ -226,7 +223,6 @@ sensor.subscribeLight({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeLight @@ -255,16 +251,16 @@ Subscribes to data changes of the step counter sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the step counter sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ---------------- | +| success | Function | Yes | Called when the step counter sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------ | ---------------------------------------- | -| steps | number | Number of counted steps after the sensor is restarted.
| +| Name | Type | Description | +| ----- | ------ | --------------------- | +| steps | number | Number of counted steps after the sensor is restarted.
| **Example** @@ -280,7 +276,6 @@ sensor.subscribeStepCounter({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeStepCounter @@ -310,16 +305,16 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the barometer sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ---------------- | +| success | Function | Yes | Called when the barometer sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | -------------------- | -| pressure | number | Pressure, in pascal. | +| Name | Type | Description | +| -------- | ------ | ----------- | +| pressure | number | Pressure, in pascal.| **Example** @@ -335,7 +330,6 @@ sensor.subscribeBarometer({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. @@ -366,16 +360,16 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ------------------------- | +| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ----------- | -| heartRate | number | Heart rate. | +| Name | Type | Description | +| --------- | ------ | ---- | +| heartRate | number | Heart rate.| **Example** @@ -391,7 +385,6 @@ sensor.subscribeHeartRate({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. @@ -421,16 +414,16 @@ Subscribes to changes of the wearing state of a wearable device. If this API is **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | -------------------------------------- | -| success | Function | Yes | Called when the wearing state changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ------------- | +| success | Function | Yes | Called when the wearing state changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------------------------------------ | -| value | boolean | Whether the wearable device is worn. | +| Name | Type | Description | +| ----- | ------- | ------ | +| value | boolean | Whether the wearable device is worn.| **Example** @@ -446,7 +439,6 @@ sensor.subscribeOnBodyState({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeOnBodyState @@ -473,17 +465,17 @@ Obtains the wearing state of a wearable device. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | -------------------------------------- | -| success | Function | No | Callback upon success. | -| fail | Function | No | Callback upon failure. | -| complete | Function | No | Called when the execution is complete. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ------------ | +| success | Function | No | Callback upon success.| +| fail | Function | No | Callback upon failure.| +| complete | Function | No | Called when the execution is complete.| Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------------------------------------ | -| value | boolean | Whether the wearable device is worn. | +| Name | Type | Description | +| ----- | ------- | ------ | +| value | boolean | Whether the wearable device is worn.| **Example** @@ -510,18 +502,18 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the device orientation sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the device orientation sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | +| Name | Type | Description | | ----- | ------ | ---------------------------------------- | -| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth. | -| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth. | -| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth. | +| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| +| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| +| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| **Example** @@ -540,7 +532,6 @@ sensor.subscribeDeviceOrientation({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeDeviceOrientation6+ @@ -571,19 +562,19 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the gyroscope sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the gyroscope sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | ---------------------------------------- | -| x | number | Rotation angular velocity of the X axis. | -| y | number | Rotation angular velocity of the Y axis. | -| z | number | Rotation angular velocity of the Z axis. | +| Name | Type | Description | +| ---- | ------ | --------- | +| x | number | Rotation angular velocity of the X axis.| +| y | number | Rotation angular velocity of the Y axis.| +| z | number | Rotation angular velocity of the Z axis.| **Example** @@ -602,7 +593,6 @@ sensor.subscribeGyroscope({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeGyroscope6+ 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 4ce32e28d400e7fb0c954c1a99fed88e5f625dd2..c8e93e0f8b84dafe4e52ce939d2cad5012762f36 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,4 +1,4 @@ -# System Time and Time Zone +# @ohos.systemTime (System Time and Time Zone) The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. @@ -12,7 +12,7 @@ The **systemTime** module provides system time and time zone features. You can u import systemTime from '@ohos.systemTime'; ``` -## systemTime.setTime +## systemTime.setTime(deprecated) setTime(time : number, callback : AsyncCallback<void>) : void @@ -29,21 +29,33 @@ Sets the system time. This API uses an asynchronous callback to return the resul | time | number | Yes | Timestamp to set, in milliseconds. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **Example** ```js // Set the system time to 2021-01-20 02:36:25. let time = 1611081385000; -systemTime.setTime(time, (error, data) => { +try { + systemTime.setTime(time, (error) => { if (error) { - console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to setting time. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); -}); + }console.info(`Succeeded in setting time`); + }); +} catch(e) { + console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.setTime +## systemTime.setTime(deprecated) setTime(time : number) : Promise<void> @@ -65,51 +77,83 @@ Sets the system time. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **Example** ```js // Set the system time to 2021-01-20 02:36:25. let time = 1611081385000; -systemTime.setTime(time).then((data) => { - console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.setTime(time).then(() => { + console.info(`Succeeded in setting time.`); + }).catch((error) => { + console.info(`Failed to setting time. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) 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** | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | ------------------ | -| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| | callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getCurrentTime(true, (error, data) => { +try { + systemTime.getCurrentTime(true, (error, time) => { if (error) { - console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in getting currentTime: ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) 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** @@ -118,31 +162,47 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal | -------- | ----------- | ---- | ---------------------------------- | | callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getCurrentTime((error, data) => { +try { + systemTime.getCurrentTime((error, time) => { if (error) { - console.error(`Succeeded in getting systemTime. Data:` + JSON.stringify(error)); - return; + console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Failed to get systemTime. Cause:` + JSON.stringify(data)); -}); + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) 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** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| **Return value** @@ -150,49 +210,81 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return | --------------------- | --------------------------- | | Promise<number> | Promise used to return the time elapsed since the Unix epoch.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getCurrentTime().then((data) => { - console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getCurrentTime().then((time) => { + console.info(`Succeeded in getting currentTime : ${time}`); + }).catch((error) => { + console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) 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** | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | -------------------------- | -| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| | callback | AsyncCallback<number> | Yes | Callback used to return the time.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getRealActiveTime(true, (error, data) => { +try { + systemTime.getRealActiveTime(true, (error, time) => { if (error) { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to getting real active time. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) 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** @@ -201,31 +293,47 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | -------- | -------------- | ---- | --------------------- | | callback | AsyncCallback<number> | Yes | Callback used to return the time.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getRealActiveTime((error, data) => { +try { + systemTime.getRealActiveTime((error, time) => { if (error) { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to getting real active time. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) 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** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| **Return value** @@ -233,49 +341,81 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th | -------------- | -------------------------------- | | Promise<number> | Promise used to return the time elapsed since system startup, excluding the deep sleep time.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getRealActiveTime().then((data) => { - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getRealActiveTime().then((time) => { + console.info(`Succeeded in getting real active time : ${time}`); + }).catch((error) => { + console.info(`Failed to getting real active time. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) 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** | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------- | -| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| | callback | AsyncCallback<number> | Yes | Callback used to return the time. | +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getRealTime(true, (error, data) => { +try { + systemTime.getRealTime(true, (error, time) => { if (error) { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to getting real time. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) 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** @@ -284,31 +424,47 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th | -------- | --------- | ---- | --------------------------- | | callback | AsyncCallback<number> | Yes | Callback used to return the time. | +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getRealTime((error, data) => { +try { + systemTime.getRealTime((error, time) => { if (error) { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to getting real time. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) 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** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.<
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds.| **Return value** @@ -316,17 +472,29 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th | --------------------- | ------------------------------- | | Promise<number> | Promise used to return the time elapsed since system startup, including the deep sleep time.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getRealTime().then((data) => { - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getRealTime().then((time) => { + console.info(`Succeeded in getting real time : ${time}`); + }).catch((error) => { + console.info(`Failed to getting real time. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.setDate +## systemTime.setDate(deprecated) setDate(date: Date, callback: AsyncCallback<void>): void @@ -343,20 +511,32 @@ Sets the system date. This API uses an asynchronous callback to return the resul | date | Date | Yes | Target date to set. | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **Example** ```js -let data = new Date(); -systemTime.setDate(data,(error, data) => { - if (error) { - console.error('Failed to set system date. Cause:' + JSON.stringify(error)); - return; -} - console.info('Succeeded in setting system date. Data:' + JSON.stringify(data)); -}); +let date = new Date(); +try { + systemTime.setDate(date, (error) => { + if (error) { + console.info(`Failed to setting date. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in setting date.`); + }); +} catch(e) { + console.info(`Failed to set date. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.setDate +## systemTime.setDate(deprecated) setDate(date: Date): Promise<void> @@ -378,23 +558,39 @@ Sets the system date. This API uses a promise to return the result. | ------------------- | -------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **Example** ```js -let data = new Date(); -systemTime.setDate(data).then((value) => { - console.log(`Succeeded in setting system date. Data:` + JSON.stringify(value)); -}).catch((error) => { - console.error(`Failed to set system date. Cause:` + JSON.stringify(error)); -}); +let date = new Date(); +try { + systemTime.setDate(date).then(() => { + console.info(`Succeeded in setting date.`); + }).catch((error) => { + console.info(`Failed to setting date. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to set date. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getDate8+ +## systemTime.getDate(deprecated) 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** @@ -403,24 +599,40 @@ Obtains the current system date. This API uses an asynchronous callback to retur | -------- | -------------- | ---- | --------------------- | | callback | AsyncCallback<Date> | Yes | Callback used to return the current system date.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getDate((error, data) => { +try { + systemTime.getDate((error, date) => { if (error) { - console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in get date : ${date}`);; + }); +} catch(e) { + console.info(`Failed to get date. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getDate8+ +## systemTime.getDate(deprecated) 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** @@ -429,17 +641,29 @@ Obtains the current system date. This API uses a promise to return the result. | ------------------- | ----------------------------------------- | | Promise<Date> | Promise used to return the current system date.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getDate().then((data) => { - console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getDate().then((date) => { + console.info(`Succeeded in getting date : ${date}`); + }).catch((error) => { + console.info(`Failed to getting date. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get date. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.setTimezone +## systemTime.setTimezone(deprecated) setTimezone(timezone: string, callback: AsyncCallback<void>): void @@ -456,19 +680,31 @@ Sets the system time zone. This API uses an asynchronous callback to return the | timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **Example** ```js -systemTime.setTimezone('Asia/Shanghai', (error, data) => { - if (error) { - console.error('Failed to set system time zone. Cause:' + JSON.stringify(error)); - return; - } - console.info('Succeeded in setting system time zone. Data:' + JSON.stringify(data)); -}); +try { + systemTime.setTimezone('Asia/Shanghai', (error) => { + if (error) { + console.info(`Failed to setting timezone. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in setting timezone.`); + }); +} catch(e) { + console.info(`Failed to set timezone. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.setTimezone +## systemTime.setTimezone(deprecated) setTimezone(timezone: string): Promise<void> @@ -490,22 +726,38 @@ Sets the system time zone. This API uses a promise to return the result. | ------------------- | -------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| -1 | The parameter check failed or permission denied or system error. | + **Example** ```js -systemTime.setTimezone('Asia/Shanghai').then((data) => { - console.log(`Succeeded in setting system time zone. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to set system time zone. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.setTimezone('Asia/Shanghai').then(() => { + console.info(`Succeeded in setting timezone.`); + }).catch((error) => { + console.info(`Failed to setting timezone. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to set timezone. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getTimezone8+ +## systemTime.getTimezone(deprecated) 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** @@ -514,24 +766,40 @@ Obtains the system time zone. This API uses an asynchronous callback to return t | -------- | --------- | ---- | ------------------------ | | callback | AsyncCallback<string> | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getTimezone((error, data) => { +try { + systemTime.getTimezone((error, data) => { if (error) { - console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); - return; + console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`); + return; } - console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); -}); + console.info(`Succeeded in get timezone : ${data}`);; + }); +} catch(e) { + console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`); +} ``` -## systemTime.getTimezone8+ +## systemTime.getTimezone(deprecated) 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** @@ -540,14 +808,26 @@ Obtains the system time zone. This API uses a promise to return the result. | --------------------- | ------------------------------------- | | Promise<string> | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| +**Error codes** + +For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md). + +| ID| Error Message | +| -------- | ------------------------------------------- | +| -1 | The parameter check failed or system error. | + **Example** ```js -systemTime.getTimezone().then((data) => { - console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getTimezone().then((data) => { + console.info(`Succeeded in getting timezone: ${data}`); + }).catch((error) => { + console.info(`Failed to getting timezone. message: ${error.message}, code: ${error.code}`); + }); +} catch(e) { + console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`); +} ``` ## Supported System Time Zones diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index b83ed0e104931c657ff9117719f28bea0d50856a..cc15e7f85a4dec87d1d23f0bc10fab0514d7df5d 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -1,4 +1,4 @@ -# System Timer +# @ohos.systemTimer (System Timer) The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. @@ -33,13 +33,13 @@ Defines the initialization options for **createTimer**. **System capability**: SystemCapability.MiscServices.Time -| Name | Type | Mandatory| Description | -| --------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| type | number | Yes | Timer type.
**1**: CPU time type. The start time of the timer cannot be later than the current system time.
**2**: wakeup type.
**4**: exact type.
**5**: idle type (not supported currently).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| -| wantAgent | [WantAgent](js-apis-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| -| callback | number | Yes | Callback used to return the timer ID. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | number | Yes | Timer type.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type.
**8**: idle type (not supported currently).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| +| callback | number | Yes | Callback used to return the timer ID. | ## systemTimer.createTimer @@ -48,6 +48,8 @@ createTimer(options: TimerOptions, callback: AsyncCallback<number>): void Creates a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -61,19 +63,23 @@ Creates a timer. This API uses an asynchronous callback to return the result. ```js export default { - systemTimer () { - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat: false - }; - systemTimer.createTimer(options, (error, data) => { - if (error) { - console.error(`Failed to create timer. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in creating timer. Data:` + JSON.stringify(data)); - }); + systemTimer () { + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat: false + }; + try { + systemTimer.createTimer(options, (error, timerId) => { + if (error) { + console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in creating timer. timerId: ${timerId}`); + }); + } catch(e) { + console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`); } + } } ``` @@ -83,6 +89,8 @@ createTimer(options: TimerOptions): Promise<number> Creates a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -101,17 +109,21 @@ Creates a timer. This API uses a promise to return the result. ```js export default { - systemTimer () { - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - }; - systemTimer.createTimer(options).then((data) => { - console.log(`Succeeded in creating timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to create timer. Cause:` + JSON.stringify(error)); - }); + systemTimer () { + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + }; + try { + systemTimer.createTimer(options).then((timerId) => { + console.info(`Succeeded in creating timer. timerId: ${timerId}`); + }).catch((error) => { + console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`); + }); + } catch(e) { + console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`); } + } } ``` @@ -121,6 +133,8 @@ startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void&g Starts a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -135,21 +149,26 @@ Starts a timer. This API uses an asynchronous callback to return the result. ```js export default { - async systemTimer () { - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 + async systemTimer () { + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = await systemTimer.createTimer(options); + let triggerTime = new Date().getTime(); + triggerTime += 3000; + try { systemTimer.startTimer(timerId, triggerTime, (error) => { - if (error) { - console.error(`Failed to start timer. Cause:` + JSON.stringify(error)); - return; - } + if (error) { + console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in starting timer.`); }); + } catch(e) { + console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`); } + } } ``` @@ -159,6 +178,8 @@ startTimer(timer: number, triggerTime: number): Promise<void> Starts a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -178,20 +199,24 @@ Starts a timer. This API uses a promise to return the result. ```js export default { - async systemTimer (){ - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime).then((data) => { - console.log(`Succeeded in startting timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to start timer. Cause:` + JSON.stringify(error)); - }); + async systemTimer (){ + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false } + let timerId = await systemTimer.createTimer(options); + let triggerTime = new Date().getTime(); + triggerTime += 3000; + try { + systemTimer.startTimer(timerId, triggerTime).then(() => { + console.info(`Succeeded in starting timer.`); + }).catch((error) => { + console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`); + }); + } catch(e) { + console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`); + } + } } ``` @@ -201,6 +226,8 @@ stopTimer(timer: number, callback: AsyncCallback<void>): void Stops a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -215,20 +242,25 @@ Stops a timer. This API uses an asynchronous callback to return the result. ```js export default { async systemTimer () { - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime) + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = await systemTimer.createTimer(options); + let triggerTime = new Date().getTime(); + triggerTime += 3000; + systemTimer.startTimer(timerId, triggerTime); + try { systemTimer.stopTimer(timerId, (error) => { - if (error) { - console.error(`Failed to stop timer. Cause:` + JSON.stringify(error)); - return; - } + if (error) { + console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in stopping timer.`); }); + } catch(e) { + console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`); + } } } ``` @@ -239,6 +271,8 @@ stopTimer(timer: number): Promise<void> Stops a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -258,19 +292,23 @@ Stops a timer. This API uses a promise to return the result. ```js export default { async systemTimer (){ - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime) - systemTimer.stopTimer(timerId).then((data) => { - console.log(`Succeeded in stopping timer. Data:` + JSON.stringify(data)); + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = await systemTimer.createTimer(options); + let triggerTime = new Date().getTime(); + triggerTime += 3000; + systemTimer.startTimer(timerId, triggerTime); + try { + systemTimer.stopTimer(timerId).then(() => { + console.info(`Succeeded in stopping timer.`); }).catch((error) => { - console.error(`Failed to stop timer. Cause:` + JSON.stringify(error)); + console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`); }); + } catch(e) { + console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`); + } } } ``` @@ -281,6 +319,8 @@ destroyTimer(timer: number, callback: AsyncCallback<void>): void Destroys a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -294,23 +334,28 @@ Destroys a timer. This API uses an asynchronous callback to return the result. ```js export default { - async systemTimer () { - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false + async systemTimer () { + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = await systemTimer.createTimer(options); + let triggerTime = new Date().getTime(); + triggerTime += 3000; + systemTimer.startTimer(timerId, triggerTime); + systemTimer.stopTimer(timerId); + try { + systemTimer.destroyTimer(timerId, (error) => { + if (error) { + console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`); + return; } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime) - systemTimer.stopTimer(timerId) - systemTimer.destroyTimer(timerId, (error) => { - if (error) { - console.error(`Failed to destroy timer. Cause:` + JSON.stringify(error)); - return; - } - }); + console.info(`Succeeded in destroying timer.`); + }); + } catch(e) { + console.info(`Failed to destroying timer. message: ${e.message}, code: ${e.code}`); } + } } ``` @@ -320,6 +365,8 @@ destroyTimer(timer: number): Promise<void> Destroys a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -338,21 +385,25 @@ Destroys a timer. This API uses a promise to return the result. ```js export default { - async systemTimer (){ - let options = { - type: systemTimer.TIMER_TYPE_REALTIME, - repeat:false - } - let timerId = await systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime) - systemTimer.stopTimer(timerId) - systemTimer.destroyTimer(timerId).then((data) => { - console.log(`Succeeded in destroying timer. Data:` + JSON.stringify(data)); - }).catch((error) => { - console.error(`Failed to destroy timer. Cause:` + JSON.stringify(error)); - }); + async systemTimer (){ + let options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false } + let timerId = await systemTimer.createTimer(options); + let triggerTime = new Date().getTime(); + triggerTime += 3000; + systemTimer.startTimer(timerId, triggerTime); + systemTimer.stopTimer(timerId); + try { + systemTimer.destroyTimer(timerId).then(() => { + console.info(`Succeeded in destroying timer.`); + }).catch((error) => { + console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`); + }); + } catch(e) { + console.info(`Failed to destroying timer. message: ${e.message}, code: ${e.code}`); + } + } } ``` diff --git a/en/application-dev/reference/apis/js-apis-system-vibrate.md b/en/application-dev/reference/apis/js-apis-system-vibrate.md index 86f474bce1a013f32bb351bfc6a0a44b658cbba5..90dc19e2ffb0c8817f7cc2096dc792d252f8996f 100644 --- a/en/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/en/application-dev/reference/apis/js-apis-system-vibrate.md @@ -1,6 +1,7 @@ -# Vibrator +# @system.vibrator (Vibrator) -The **Vibrate** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. + +The **Vibrator** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. Misc devices refer to LED lights and vibrators on devices. LED lights are mainly used for indication (for example, indicating the charging state) and blinking (such as tri-colored lights). Vibrators are mainly used in scenarios such as the alarm clock, power-on/off, and incoming call vibration. diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index e9b54c774d2bc1e43de0dd7edb55e47bcf9c3b57..f1c9ad362175bd709d27bc4c7aec0059b413221e 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,6 +1,6 @@ -# Cellular Data +# @ohos.telephony.data (Cellular Data) -The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. +The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index e0d809d06ab24702e5eaf67eb6b1b841a7944ffc..514e7062cd649d8bf5b92261bceeb7cbed870166 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,8 +1,8 @@ -# Thermal Manager +# @ohos.thermal (Thermal Management) -This module provides thermal level-related callback and query APIs to obtain the information required for thermal control. +The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control. -> **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md index 0b52b8721ba891eacb099b86907458d72064dd9a..ae49b428e00c4c22ed126ecc539290a692b69696 100644 --- a/en/application-dev/reference/apis/js-apis-touchevent.md +++ b/en/application-dev/reference/apis/js-apis-touchevent.md @@ -1,6 +1,6 @@ -# Touch Event +# @ohos.multimodalInput.touchEvent (Touch Event) -Represents touch events reported by an input device. +The **touchEvent** module provides touch events reported by an input 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. diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index 573732b5474552added2d9918986e2add3982b01..eb874f0abd94f72f56f0e1e13a23883e1ae14ce8 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -1,7 +1,6 @@ # @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. @@ -49,7 +48,7 @@ A constructor used to create a **TreeMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -78,7 +77,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -114,7 +113,7 @@ Checks whether this container has the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -152,7 +151,7 @@ Checks whether this container has the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -190,7 +189,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -222,7 +221,7 @@ Obtains the first key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -254,7 +253,7 @@ Obtains the last key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -282,11 +281,11 @@ Adds all elements in a **TreeMap** instance to this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| map | TreeMap | Yes| **TreeMap** instance whose elements are to be added to the current container.| +| map | TreeMap | Yes| **TreeMap** object to be added to the container.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -299,7 +298,11 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let map = new TreeMap(); -treeMap.setAll(map); +map.set("demo", 12); +map.setAll(treeMap); // Add all elements in the treeMap to the map. +map.forEach((value, key) => { + console.log("test" + value, key); // Print result: 12 demo, 356 sparrow, and 123 squirrel +}) ``` @@ -326,7 +329,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -362,7 +365,7 @@ Removes the element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -400,7 +403,7 @@ Obtains the key that is placed in front of the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -439,7 +442,7 @@ Obtains the key that is placed next to the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -478,7 +481,7 @@ Replaces an element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -503,7 +506,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -535,7 +538,7 @@ Obtains an iterator that contains all the keys in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -572,7 +575,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -617,7 +620,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -651,7 +654,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -688,7 +691,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index bc6f1272452fd35d0458b6232f7c03a1bd19ce9b..4aaaac1861ceffdfda3d7adc53b16181c42cc9c3 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -1,7 +1,6 @@ # @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. @@ -46,7 +45,7 @@ A constructor used to create a **TreeSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -75,7 +74,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -111,7 +110,7 @@ Checks whether this container has the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -143,7 +142,7 @@ Obtains the value of the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -175,7 +174,7 @@ Obtains the value of the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -213,7 +212,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -249,7 +248,7 @@ Removes the element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -287,7 +286,7 @@ Obtains the value that is placed in front of the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -326,7 +325,7 @@ Obtains the value that is placed next to the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -359,7 +358,7 @@ Removes the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -391,7 +390,7 @@ Removes the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -417,7 +416,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -449,7 +448,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -494,7 +493,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -528,7 +527,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -566,7 +565,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index d4b84b0d938725bb069cc482b29ce94c9c3c3bd4..8c229cc5ec06e1bef82452420848b8175a02c22c 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -1,4 +1,4 @@ -# @ohos.uitest +# @ohos.uitest (UiTest) The **UiTest** module provides APIs that you can use to simulate UI actions during testing, such as clicks, double-clicks, long-clicks, and swipes. diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 2a6fa561c6e21b85bfb07ee7b82223c42deff765..ffb07ba4f21cc5f154bcf25062f86845c97577dc 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1,6 +1,6 @@ -# Update +# @ohos.update (Update) -The Update module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. +The **update** module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. There are two types of updates: SD card update and over the air (OTA) update. @@ -8,10 +8,8 @@ There are two types of updates: SD card update and over the air (OTA) update. - The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer. > **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 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 diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index 6bad7dde783939b10243f10824e98ef991235499..00bf51656958f8ca58b926cb54ad9fd1d82a8e53 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -29,6 +29,70 @@ import uri from '@ohos.uri' | authority | string | Yes| No| Authority part in the URI.| | ssp | string | Yes| No| Scheme-specific part in the URI.| +### Naming Rules + +Naming format: + +A standard URI consists of the following parts: +[scheme:]scheme-specific-part[#fragment] +- Scheme: scheme component, which is mandatory. Example values: **http**, **https**, **ftp**, **datashare**, and **dataability**. +- scheme-specific-part: specific part of the URI decoding scheme. The value consists of [//][authority][path][?query]. Set this parameter as required. + - authority: decoding authority component of the URI. The value consists of [userinfo@]host[:port]. Set this parameter as required. + - userinfo: user information. Set this parameter as required. + - host: host name of the server. This parameter is mandatory when authority exists. + - port: port number of the server. Set this parameter as required. + - path: path information. Set this parameter as required. + - query: query component. Set this parameter as required. +- fragment: fragment component. Set this parameter as required. + +**Example URIs** + +```js +const result1 = new uri.URI("ftp://ftp.aaa.bbb.ccc/dddd/eee.txt"); +console.log(result1.host) // ftp.aaa.bbb.ccc +console.log(result1.fragment) // null +console.log(result1.path) // /dddd/eee.txt +console.log(result1.scheme) // ftp +console.log(result1.userInfo) // null +console.log(result1.port) // -1 +console.log(result1.query) // null + +const result2 = new uri.URI("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#fragment"); +console.log(result2.host) // spinaltap.micro.umn.edu +console.log(result2.fragment) // fragment +console.log(result2.path) // /dddd/eee.txt +console.log(result2.scheme) // ftp +console.log(result2.userInfo) // null +console.log(result2.port) //-1 +console.log(result2.query) // null + +const result3 = new uri.URI("datashare:///com.samples.datasharetest.DataShare/DB00/TBL00"); +console.log(result3.host) // null +console.log(result3.fragment) // null +console.log(result3.path) // /com.samples.datasharetest.DataShare/DB00/TBL00 +console.log(result3.scheme) // datashare +console.log(result3.userInfo) // null +console.log(result3.port) // -1 +console.log(result3.query) // null + +const result4 = new uri.URI("https://username:password@host:8080/directory/file?foo=1&bar=2#fragment"); +console.log(result4.host) // host +console.log(result4.fragment) // fragment +console.log(result4.path) // /directory/file +console.log(result4.scheme) // https +console.log(result4.userInfo) // username:password +console.log(result4.port) // 8080 +console.log(result4.query) // foo=1&bar=2 + +const result5 = new uri.URI("dataability:///com.example.DataAbility"); +console.log(result5.host) // null +console.log(result5.fragment) // null +console.log(result5.path) // /com.example.DataAbility: +console.log(result5.scheme) // dataability +console.log(result5.userInfo) // null +console.log(result5.port) // -1 +console.log(result5.query) // null +``` ### constructor @@ -44,6 +108,14 @@ A constructor used to create a URI instance. | -------- | -------- | -------- | -------- | | uri | string | Yes| Input object.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid uri string. | + **Example** ```js @@ -79,14 +151,14 @@ result.toString() ### equals(deprecated) -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. - equals(other: URI): boolean Checks whether this URI is the same as another URI object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -105,7 +177,7 @@ Checks whether this URI is the same as another URI object. ```js const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); uriInstance.equals(uriInstance1); ``` ### equalsTo9+ @@ -132,7 +204,7 @@ Checks whether this URI is the same as another URI object. ```js const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); uriInstance.equalsTo(uriInstance1); ``` @@ -148,7 +220,7 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the URI is an absolute URI; returns **false** otherwise.| +| boolean | If the URI is an absolute URI, **true** is returned. Otherwise, **false** is returned.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 442c62ee76cf48b60361ee939c0f116bf98fb1fa..8a972e121d32b041e1ff7f8319c4e26261afb2f5 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -11,7 +11,6 @@ import Url from '@ohos.url' ``` ## URLParams9+ - ### constructor9+ constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) @@ -32,7 +31,7 @@ A constructor used to create a **URLParams** instance. let objectParams = new Url.URLParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); let objectParams1 = new Url.URLParams({"fod" : '1' , "bard" : '2'}); let objectParams2 = new Url.URLParams('?fod=1&bard=2'); -let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.mozilla.org/?fod=1&bard=2'); let params = new Url.URLParams(urlObject.search); ``` @@ -55,7 +54,7 @@ Appends a key-value pair into the query string. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.append('fod', '3'); ``` @@ -78,9 +77,9 @@ Deletes key-value pairs of the specified key. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsobject = new Url.URLParams(urlObject.search.slice(1)); -paramsobject.delete('fod'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.delete('fod'); ``` @@ -88,7 +87,7 @@ paramsobject.delete('fod'); getAll(name: string): string[] -Obtains all the key-value pairs based on the specified key. +Obtains all the key-value pairs based on the specified name. **System capability**: SystemCapability.Utils.Lang @@ -102,12 +101,12 @@ Obtains all the key-value pairs based on the specified key. | Type| Description| | -------- | -------- | -| string[] | All key-value pairs matching the specified key.| +| string[] | Key-value pairs obtained.| **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLParams(urlObject.search.slice(1)); params.append('fod', '3'); // Add a second value for the fod parameter. console.log(params.getAll('fod').toString()) // Output ["1","3"]. @@ -132,7 +131,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js let searchParamsObject = new Url.URLParams("keyName1=valueName1&keyName2=valueName2"); -for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs +for (var pair of searchParamsObject.entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } ``` @@ -164,9 +163,9 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal **Example** ```js -const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -myURLObject.searchParams.forEach((value, name, searchParams) => { - console.log(name, value, myURLObject.searchParams === searchParams); +const myURLObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); +myURLObject.params.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.params === searchParams); }); ``` @@ -224,7 +223,7 @@ Checks whether a key has a value. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.has('bard') === true; ``` @@ -248,7 +247,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.set('baz', '3'); // Add a third parameter. ``` @@ -360,7 +359,7 @@ Obtains search parameters that are serialized as a string and, if necessary, per **Example** ```js -let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let url = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLParams(url.search.slice(1)); params.append('fod', '3'); console.log(params.toString()); @@ -384,20 +383,20 @@ console.log(params.toString()); | port | string | Yes| Yes| Port in a URL.| | protocol | string | Yes| Yes| Protocol in a URL.| | search | string | Yes| Yes| Serialized query string in a URL.| -| searchParams | URLSearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| -| URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| +| searchParams(deprecated) | [URLSearchParams](#urlsearchparamsdeprecated) | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.
- **NOTE**: This attribute is supported since API version 7 and is deprecated since API version 9. You are advised to use params9+ instead.| +| params9+ | [URLParams](#urlparams9) | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| | username | string | Yes| Yes| Username in a URL.| ### constructor(deprecated) -constructor(url: string, base?: string | URL) - -Creates a URL. - > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. +constructor(url: string, base?: string | URL) + +Creates a URL. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -410,13 +409,13 @@ Creates a URL. **Example** ```js -let mm = 'http://username:password@host:8080'; -let a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; -let b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; -new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -let c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; +let mm = 'https://username:password@host:8080'; +let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/'; +let b = new Url.URL(mm); // Output 'https://username:password@host:8080/'; +new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +let c = new Url.URL('/path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1'; new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL @@ -424,8 +423,16 @@ new Url.URL('https://www.example.com', ); // Output https://www.example.com/ new Url.URL('https://www.example.com', b); // Output https://www.example.com/ ``` -### parseURL9+ +### constructor9+ + +constructor() + +A no-argument constructor used to create a URL. It returns a **URL** object after **parseURL** is called. It is not used independently. + +**System capability**: SystemCapability.Utils.Lang +### parseURL9+ + static parseURL(url : string, base?: string | URL): URL Parses a URL. @@ -447,11 +454,13 @@ For details about the error codes, see [Utils Error Codes](../errorcodes/errorco | -------- | -------- | | 10200002 | Invalid url string. | + **Example** ```js -let mm = 'http://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +let mm = 'https://username:password@host:8080'; +let url = Url.URL.parseURL(mm); +url.toString(); // Output 'https://username:password@host:8080/'; ``` ### tostring @@ -471,11 +480,10 @@ Converts the parsed URL into a string. **Example** ```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toString(); ``` - ### toJSON toJSON(): string @@ -492,7 +500,7 @@ Converts the parsed URL into a JSON string. **Example** ```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON(); ``` @@ -634,7 +642,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js let searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); -for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs +for (var pair of searchParamsObject.entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } ``` @@ -657,7 +665,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value to use when **callbackFn** is invoked.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| **Table 1** callbackFn parameter description @@ -902,126 +910,4 @@ let params = new Url.URLSearchParams(url.search.slice(1)); params.append('fod', '3'); console.log(params.toString()); ``` - -## URL - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| -| host | string | Yes| Yes| Host information in a URL.| -| hostname | string | Yes| Yes| Hostname (without the port) in a URL.| -| href | string | Yes| Yes| String that contains the whole URL.| -| origin | string | Yes| No| Read-only string that contains the Unicode serialization of the origin of the represented URL.| -| password | string | Yes| Yes| Password in a URL.| -| pathname | string | Yes| Yes| Path in a URL.| -| port | string | Yes| Yes| Port in a URL.| -| protocol | string | Yes| Yes| Protocol in a URL.| -| search | string | Yes| Yes| Serialized query string in a URL.| -| searchParams | URLSearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| -| URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| -| username | string | Yes| Yes| Username in a URL.| - -### constructor(deprecated) - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. - -constructor(url: string, base?: string | URL) - -Creates a URL. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| - -**Example** - -```js -let mm = 'https://username:password@host:8080'; -let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/'; -let b = new Url.URL(mm); // Output 'https://username:password@host:8080/'; -new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1'; -let c = new Url.URL('/path/path1', b); // Output 'https://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 -new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL -new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL -new Url.URL('https://www.example.com', ); // Output https://www.example.com/ -new Url.URL('https://www.example.com', b); // Output https://www.example.com/ -``` - -### parseURL9+ - -static parseURL(url : string, base?: string | URL): URL - -Parses a URL. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| - -**Example** - -```js -let mm = 'https://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'https://username:password@host:8080/'; -``` - -### tostring - -toString(): string - -Converts the parsed URL into a string. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Website address in a serialized string.| - -**Example** - -```js -const url = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString(); -``` - - -### toJSON - -toJSON(): string - -Converts the parsed URL into a JSON string. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Website address in a serialized string.| - -**Example** -```js -const url = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toJSON(); -``` diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md index b3be9875df2554c6df5b8c358c9243d734d87874..68a127a08bdfd1df0ca558866dc3cde577e2b25a 100644 --- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -1,8 +1,8 @@ -# USB +# @ohos.usb (USB Management) -The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. -> **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. diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 3e1c5b919c881ef5c0d0619a5b35e791c48c46cb..9035d2d040209f44a019fb69b3da6edc49b481b3 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,9 +1,8 @@ -# USB +# @ohos.usbV9 (USB Management) -The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. -> **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. ## Modules to Import @@ -87,7 +86,7 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); connectDevice(device: USBDevice): Readonly<USBDevicePipe> -Connects to a USB device. +Connects to a USB device based on the device list obtained by using **getDevices()**. Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission. @@ -134,6 +133,8 @@ hasRight(deviceName: string): boolean Checks whether the application has the permission to access the device. +The value **true** is returned if the device access permission is available; the value **false** is returned otherwise. + **System capability**: SystemCapability.USB.USBManager **Parameters** @@ -187,7 +188,7 @@ usb.requestRight(devicesName).then((ret) => { ## usb.removeRight -removeRight(deviceName: string): boolean; +removeRight(deviceName: string): boolean Removes the permission for the application to access a USB device. @@ -216,7 +217,7 @@ if (usb.removeRight(devicesName) { ## usb.addRight -addRight(bundleName: string, deviceName: string): boolean; +addRight(bundleName: string, deviceName: string): boolean Adds the permission for the application to access a USB device. diff --git a/en/application-dev/reference/apis/js-apis-userFileManager.md b/en/application-dev/reference/apis/js-apis-userFileManager.md new file mode 100644 index 0000000000000000000000000000000000000000..79f05bcde81ed652af7c750d69365168b815c520 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-userFileManager.md @@ -0,0 +1,2471 @@ +# @ohos.filemanagement.userFileManager (User Data Management) + +The **userFileManager** module provides user data management capabilities, including accessing and modifying user media data (audio and video clips, images, and files). + +> **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. + +## Modules to Import + +```ts +import userFileManager from '@ohos.filemanagement.userFileManager'; +``` + +## userFileManager.getUserFileMgr + +getUserFileMgr(context: Context): UserFileManager + +Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video clips, images, and files). + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| context | [Context](js-apis-inner-app-context.md) | Yes | Context of the ability instance.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| + +**Example** + +```ts +const context = getContext(this); +let mgr = userFileManager.getUserFileMgr(context); +``` + +## UserFileManager + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + + +Obtains image and video assets. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchResult fail' + err); + } + }); +} +``` + + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +Obtains image and video assets. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ---------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise used to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getPhotoAssets(fetchOptions); + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } + } catch (err) { + console.info('getPhotoAssets failed, message = ', err); + } +} +``` +### createPhotoAsset + +createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; + +Creates an image or video asset. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | Yes | File name of the image or video to create. | +| albumUri | string | Yes | URI of the album where the image or video is located. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the image or video created.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('createPhotoAssetDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + predicates: predicates + }; + let albums = await mgr.getPhotoAlbums(fetchOptions); + let album = await albums.getFirstObject(); + let testFileName = "testFile" + Date.now() + ".jpg"; + mgr.createPhotoAsset(testFileName, album.albumUri, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }); +} +``` + +### createPhotoAsset + +createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): void; + +Creates an image or video asset. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | Yes | File name of the image or video to create. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the image or video created.| + +**Example** + +```ts +async function example() { + console.info('createPhotoAssetDemo'); + let testFileName = "testFile" + Date.now() + ".jpg"; + mgr.createPhotoAsset(testFileName, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }); +} +``` + +### createPhotoAsset + +createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset>; + +Creates an image or video asset. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | Yes | File name of the image or video to create. | +| albumUri | string | No | URI of the album where the image or video is located. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the image or video created.| + +**Example** + +```ts +async function example() { + console.info('createPhotoAssetDemo'); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ', err); + } +} +``` + +### getPhotoAlbums + +getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; + + +Obtains image and video albums. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | Yes | Options for fetching the albums. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | Yes | Callback invoked to return the albums obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAlbumsDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + + mgr.getPhotoAlbums(albumFetchOptions, (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('albums.count = ' + fetchResult.getCount()); + fetchResult.getFirstObject((err, album) => { + if (album != undefined) { + console.info('first album.albumName = ' + album.albumName); + } else { + console.info('album is undefined, err = ', err); + } + }); + } else { + console.info('getPhotoAlbums fail, message = ', err); + } + }); +} +``` + +### getPhotoAlbums + +getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>>; + +Obtains image and video albums. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | Yes | Options for fetching the albums. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise used to return the albums obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAlbumsDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + let fetchResult = await mgr.getPhotoAlbums(albumFetchOptions); + console.info('album.count = ' + fetchResult.getCount()); + const album = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + album.albumName); + } catch (err) { + console.info('getPhotoAlbums fail, message = ' + err); + } +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; + + +Obtains the system album. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | Yes | Type of the album to obtain. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Yes | Callback invoked to return the album obtained.| + +**Example** + +```ts +async function example() { + console.info('getPrivateAlbumDemo'); + mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { + if (fetchResult != undefined) { + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } else { + console.info('getPrivateAlbum failed. message = ', err); + } + }); +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum>>; + + +Obtains the system album. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | Yes | Type of the album to obtain. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Promise used to return the album obtained.| + +**Example** + +```ts +async function example() { + console.info('getPrivateAlbumDemo'); + try { + var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } catch (err) { + console.info('getPrivateAlbum failed. message = ', err); + } +} +``` + +### getAudioAssets + +getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + + +Obtains audio assets. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_AUDIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the audio assets. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the audio assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getAudioAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchFileResult fail' + err); + } + }); +} +``` + +### getAudioAssets + +getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + + +Obtains audio assets. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_AUDIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the audio assets. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise used to return the audio assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getAudioAssets(fetchOptions); + } catch (err) { + console.info('getAudioAssets failed, message = ', err); + } + + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } +} +``` +### delete + +delete(uri: string, callback: AsyncCallback<void>): void; + +Deletes a media file. This API uses an asynchronous callback to return the result. The deleted file is moved to the recycle bin. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | URI of the media file to delete.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('deleteAssetDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err); + } + + if (asset == undefined) { + console.error('asset not exist'); + return; + } + mgr.delete(asset.uri, (err) => { + if (err == undefined) { + console.info("delete successfully"); + } else { + console.info("delete failed with error:" + err); + } + }); +} +``` +### delete + +delete(uri: string): Promise<void>; + +Deletes a media file. This API uses a promise to return the result. The deleted file is moved to the recycle bin. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | URI of the media file to delete.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('deleteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err); + } + + if (asset == undefined) { + console.error('asset not exist'); + return; + } + try { + await mgr.delete(asset.uri); + console.info("delete successfully"); + } catch (err) { + console.info("delete failed with error:" + err); + } +} +``` + +### on + +on(type: ChangeEvent, callback: Callback<void>): void + +Subscribes to changes of the file management library. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | Yes | Type of event to subscribe to.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | Yes | Callback that returns no value. | + +**Example** + +```ts +async function example() { + console.info('onDemo'); + let count = 0; + mgr.on('imageChange', () => { + count++; + // Image file changed. Do something. + }); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ' + err); + } + //sleep 1s + if (count > 0) { + console.info("onDemo success"); + } else { + console.info("onDemo fail"); + } + mgr.off('imageChange', () => { + // Unsubscription succeeds. + }); +} +``` + +### off + +off(type: ChangeEvent, callback?: Callback<void>): void + +Unsubscribes from changes of the file management library. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | Yes | Type of event to subscribe to.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | No | Callback that returns no value. | + +**Example** + +```ts +async function example() { + console.info('offDemo'); + let count = 0; + mgr.on('imageChange', () => { + count++; + // Image file changed. Do something. + }); + + mgr.off('imageChange', () => { + // Unsubscription succeeds. + }); + + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ' + err); + } + //sleep 1s + if (count == 0) { + console.info("offDemo success"); + } else { + console.info("offDemo fail"); + } +} +``` + +### getActivePeers + +getActivePeers(callback: AsyncCallback<Array<PeerInfo>>): void; + +Obtains information about online peer devices. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | Yes | Callback invoked to return the online peer device list.| + +**Example** + +```ts +async function example() { + console.info('getActivePeersDemo'); + mgr.getActivePeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.'); + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getActivePeers failed. message = ', err); + } + }); +} +``` + +### getActivePeers + +getActivePeers(): Promise<Array<PeerInfo>>; + +Obtains information about online peer devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Return value** + +| Type | Description | +| --------------------------- | ----------------------------- | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise used to return the online device list.| + +**Example** + +```ts +async function example() { + console.info('getActivePeersDemo'); + try { + var devicesInfo = await mgr.getActivePeers(); + } catch (err) { + console.info('getActivePeers failed. message = ', err); + } + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.'); + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail'); + } +} +``` + +### getAllPeers + +getAllPeers(callback: AsyncCallback<Array<PeerInfo>>): void; + +Obtains information about all peer devices. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | Yes | Callback invoked to return the online peer device list.| + +**Example** + +```ts +async function example() { + console.info('getAllPeersDemo'); + mgr.getAllPeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.'); + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getAllPeers failed. message = ', err); + } + }); +} +``` + +### getAllPeers + +getAllPeers(): Promise<Array<PeerInfo>>; + +Obtains information about all peer devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Return value** + +| Type | Description | +| --------------------------- | ----------------------------- | +| Promise<Array<[PeerInfo](#peerinfo)>> | Promise used to return the peer device list.| + +**Example** + +```ts +async function example() { + console.info('getAllPeersDemo'); + try { + var devicesInfo = await mgr.getAllPeers(); + } catch (err) { + console.info('getAllPeers failed. message = ', err); + } + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.'); + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail'); + } +} +``` + +### release + +release(callback: AsyncCallback<void>): void + +Releases this **UserFileManager** instance. This API uses an asynchronous callback to return the result. +Call this API when the APIs in the **UserFileManager** instance are no longer used. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +async function example() { + console.info('releaseDemo'); + mgr.release((err) => { + if (err != undefined) { + console.info('release failed. message = ', err); + } else { + console.info('release ok.'); + } + }); +} +``` + +### release + +release(): Promise<void> + +Releases this **UserFileManager** instance. This API uses a promise to return the result. +Call this API when the APIs in the **UserFileManager** instance are no longer used. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | --------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +async function example() { + console.info('releaseDemo'); + try { + await mgr.release(); + console.info('release ok.'); + } catch (err) { + console.info('release failed. message = ', err); + } +} +``` + +## FileAsset + +Provides APIs for encapsulating file asset attributes. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | +| uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. | +| fileType | [FileType](#filetype) | Yes | No | Type of the file. | +| displayName | string | Yes | Yes | File name, including the file name extension, to display. | + + +### get + +get(member: string): MemberType; + +Obtains the value of a **FileAsset** parameter. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| member | string | Yes | Name of the parameter to obtain, for example, **ImageVideoKey.URI**.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('fileAssetGetDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } +} +``` + +### set + +set(member: string, value: string): void; + +Sets a **FileAsset** parameter. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| member | string | Yes | Name of the parameter to set, for example, **ImageVideoKey.URI**.| +| value | string | Yes | Value to set. Only the value of **ImageVideoKey.TITLE** can be changed.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('fileAssetSetDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + fileAsset.set(title.toString(), "newTitle"); + } catch (err) { + console.info('release failed. message = ', err); + } +} +``` + +### commitModify + +commitModify(callback: AsyncCallback<void>): void + +Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('commitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle"); + fileAsset.commitModify((err) => { + if (err == undefined) { + let newFileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } else { + console.info('commitModify failed, message =', err); + } + }); +} +``` + +### commitModify + +commitModify(): Promise<void> + +Commits the modification on the file metadata to the database. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('commitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle"); + try { + await fileAsset.commitModify(); + let newFileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } +} +``` + +### open + +open(mode: string, callback: AsyncCallback<number>): void + +Opens this file asset. This API uses an asynchronous callback to return the result. + +>**NOTE** +> +>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_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO + + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| +| callback | AsyncCallback<number> | Yes | Callback used to return the file handle. | + +**Example** + +```ts +async function example() { + console.info('openDemo'); + let testFileName = "testFile" + Date.now() + ".jpg"; + const fileAsset = await mgr.createPhotoAsset(testFileName); + fileAsset.open('rw', (err, fd) => { + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd); + } else { + console.info('File err' + err); + } + }); +} +``` + +### open + +open(mode: string): Promise<number> + +Opens this file asset. This API uses a promise to return the result. + +>**NOTE** +> +>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_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------------------- | +| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| + +**Return value** + +| Type | Description | +| --------------------- | ------------- | +| Promise<number> | Promise used to return the file handle.| + +**Example** + +```ts +async function example() { + console.info('openDemo'); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + const fileAsset = await mgr.createPhotoAsset(testFileName); + let fd = await fileAsset.open('rw'); + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd); + } else { + console.info(' open File fail'); + } + } catch (err) { + console.info('open Demo err' + err); + } +} +``` + +### close + +close(fd: number, callback: AsyncCallback<void>): void + +Closes this file asset. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| fd | number | Yes | File descriptor.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('closeDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let fd = await fileAsset.open('rw'); + console.info('file fd', fd); + fileAsset.close(fd, (err) => { + if (err == undefined) { + console.info('asset close succeed.'); + } else { + console.info('close failed, message = ' + err); + } + }); + } catch (err) { + console.info('close failed, message = ' + err); + } +} +``` + +### close + +close(fd: number): Promise<void> + +Closes this file asset. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| fd | number | Yes | File descriptor.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('closeDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + let fd = await asset.open('rw'); + console.info('file fd', fd); + await asset.close(fd); + console.info('asset close succeed.'); + } catch (err) { + console.info('close failed, message = ' + err); + } +} +``` + +### getThumbnail + +getThumbnail(callback: AsyncCallback<image.PixelMap>): void + +Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getThumbnailDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName); + asset.getThumbnail((err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); + } + }); +} +``` + +### getThumbnail + +getThumbnail(size: image.Size, callback: AsyncCallback<image.PixelMap>): void + +Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------- | +| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail to obtain. | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getThumbnailDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName); + asset.getThumbnail(size, (err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); + } + }); +} +``` + +### getThumbnail + +getThumbnail(size?: image.Size): Promise<image.PixelMap> + +Obtains the file thumbnail of the given size. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------- | ---- | ----- | +| size | [image.Size](js-apis-image.md#size) | No | Size of the thumbnail to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------- | --------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the pixel map of the thumbnail.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getThumbnailDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName); + asset.getThumbnail(size).then((pixelMap) => { + console.info('getThumbnail successful ' + pixelMap); + }).catch((err) => { + console.info('getThumbnail fail' + err); + }); +} +``` + +### favorite + +favorite(isFavorite: boolean, callback: AsyncCallback<void>): void + +Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ---------------------------------- | +| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('favoriteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true, (err) => { + if (err == undefined) { + console.info("favorite successfully"); + } else { + console.info("favorite failed with error:" + err); + } + }); +} +``` + +### favorite + +favorite(isFavorite: boolean): Promise<void> + +Favorites or unfavorites this file asset. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ---------------------------------- | +| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('favoriteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true).then(function () { + console.info("favorite successfully"); + }).catch(function (err) { + console.info("favorite failed with error:" + err); + }); +} +``` + +## FetchResult + +Provides APIs to manage the file retrieval result. + +### getCount + +getCount(): number + +Obtains the total number of files in the result set. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Total number of files.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getCountDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('fetchCount = ', fetchCount); +} +``` + +### isAfterLast + +isAfterLast(): boolean + +Checks whether the cursor is in the last row of the result set. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------- | ---------------------------------- | +| boolean | Returns **true** if the cursor is in the last row of the result set; returns **false** otherwise.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('count:' + fetchCount); + let fileAsset = await fetchResult.getLastObject(); + if (!fetchResult.isAfterLast()) { + console.info('fileAsset isAfterLast displayName = ', fileAsset.displayName); + } else { + console.info('fileAsset not isAfterLast '); + } +} +``` + +### close + +close(): void + +Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('fetchResultCloseDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.close(); + console.info('close succeed.'); + } catch (err) { + console.info('close fail. message = ' + err); + } +} +``` + +### getFirstObject + +getFirstObject(callback: AsyncCallback<T>): void + +Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------- | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the first file asset.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getFirstObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getFirstObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); +} +``` + +### getFirstObject + +getFirstObject(): Promise<T> + +Obtains the first file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise<T> | Promise used to return the first file asset.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getFirstObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAsset displayName: ', fileAsset.displayName); +} +``` + +### getNextObject + + getNextObject(callback: AsyncCallback<T>): void + +Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ----------------------------------------- | +| callbacke | AsyncCallback<T> | Yes | Callback invoked to return the next file asset.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getNextObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + fetchResult.getNextObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); + } +} +``` + +### getNextObject + + getNextObject(): Promise<T> + +Obtains the next file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<T> | Promise used to return the next file asset obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getNextObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + let fileAsset = await fetchResult.getNextObject(); + console.info('fileAsset displayName: ', fileAsset.displayName); + } +} +``` + +### getLastObject + +getLastObject(callback: AsyncCallback<T>): void + +Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | --------------------------- | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the last file asset obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getLastObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getLastObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); +} +``` + +### getLastObject + +getLastObject(): Promise<T> + +Obtains the last file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<T> | Promise used to return the last file asset obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getLastObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getLastObject(); + console.info('fileAsset displayName: ', fileAsset.displayName); +} +``` + +### getPositionObject + +getPositionObject(index: number, callback: AsyncCallback<T>): void + +Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------ | +| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the file asset obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPositionObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getPositionObject(0, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); +} +``` + +### getPositionObject + +getPositionObject(index: number): Promise<T> + +Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | -------------- | +| index | number | Yes | Index of the file asset to obtain. The value starts from **0**.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<T> | Promise used to return the file asset obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPositionObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getPositionObject(0); + console.info('fileAsset displayName: ', fileAsset.displayName); +} +``` + +## Album + +Provides APIs to manage albums. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable | Writable | Description | +| ------------ | ------ | ---- | ---- | ------- | +| albumName | string | Yes | Yes | Album name. | +| albumUri | string | Yes | No | Album URI. | +| dateModified | number | Yes | No | Date when the album was last modified. | +| count | number | Yes | No | Number of files in the album.| +| coverUri | string | Yes | No | URI of the cover file of the album. + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +Obtains image and video assets. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumGetFileAssetsDemoCallback'); + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { + if (albumFetchResult != undefined) { + console.info("album getPhotoAssets successfully, getCount:" + albumFetchResult.getCount()); + } else { + console.info("album getPhotoAssets failed with error:" + err); + } + }); +} +``` +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +Obtains image and video assets. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| +| Promise | [FetchResult](#fetchresult)<[FileAsset](#fileasset)> | Yes | Promise used to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumGetFileAssetsDemoPromise'); + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption).then((albumFetchResult) => { + console.info("album getFileAssets successfully, getCount:" + albumFetchResult.getCount()); + }).catch((err) => { + console.info("album getFileAssets failed with error:" + err); + }); +} +``` + +### commitModify + +commitModify(callback: AsyncCallback<void>): void; + +Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumCommitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify((err) => { + if (err != undefined) { + console.info("commitModify failed with error:" + err); + } else { + console.info("commitModify successfully"); + } + }); +} +``` + +### commitModify + +commitModify(): Promise<void>; + +Commits the modification on the album attributes to the database. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------ | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumCommitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + var albumList = await mgr.getPhotoAlbums(albumFetchOptions); + } catch (err) { + console.info('getPhotoAlbums failed. message = ', err); + } + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info("commitModify successfully"); + }).catch((err) => { + console.info("commitModify failed with error:" + err); + }); +} +``` + +## PrivateAlbum + +Provides APIs for managing the system albums. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable | Writable | Description | +| ------------ | ------ | ---- | ---- | ------- | +| albumName | string | Yes | Yes | Album name. | +| albumUri | string | Yes | No | Album URI. | +| dateModified | number | Yes | No | Date when the album was last modified. | +| count | number | Yes | No | Number of files in the album.| +| coverUri | string | Yes | No | URI of the cover file of the album. + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +Obtains image and video assets from a system album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumGetFileAssetsDemoCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + trashAlbum.getPhotoAssets(fetchOption, (err, fetchResult) => { + if (fetchResult != undefined) { + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); + } else { + console.info('getFileAssets failed, message = ', err); + } + }); +} + +``` +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +Obtains image and video assets from a system album. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise:[FetchResult](#fetchresult)<[FileAsset](#fileasset)>| Promise used to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumGetFileAssetsDemoPromise'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); +} +``` +### delete + +delete(uri: string, callback: AsyncCallback<void>): void; + +Deletes files from a system album. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumDeleteCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.delete failed, message = ', err); + } else { + console.info('trashAlbum.delete successfully'); + } + }); +} +``` +### delete + +delete(uri: string): Promise<void>; + +Deletes files from a system album. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumDeleteDemoPromise'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri).then(() => { + console.info('trashAlbum.delete successfully'); + }).catch((err) => { + console.info('trashAlbum.delete failed, message = ', err); + }); +} +``` + +### recover + +recover(uri: string, callback: AsyncCallback<void>): void; + +Recovers files in a system album. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumRecoverDemoCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.recover failed, message = ', err); + } else { + console.info('trashAlbum.recover successfully'); + } + }); +} +``` +### recover + +recover(uri: string): Promise<void>; + +Recovers files in a system album. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise that returns no value.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumRecoverDemoPromise'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri).then(() => { + console.info('trashAlbum.recover successfully'); + }).catch((err) => { + console.info('trashAlbum.recover failed, message = ', err); + }); +} +``` + +## MemberType + +Enumerates the member types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type| Readable | Writable | Description | +| ----- | ---- | ---- | ---- | ---- | +| number | number | Yes| Yes| The member is a number.| +| string | string | Yes| Yes| The member is a string.| +| boolean | boolean | Yes| Yes| The member is a Boolean value.| + +## ChangeEvent + +Enumerates the type of changes to observe. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type| Readable | Writable | Description| +| ----- | ---- | ---- | ---- | ---- | +| deviceChange | string | Yes| Yes| Device.| +| albumChange | string | Yes| Yes| Album.| +| imageChange | string | Yes| Yes| Image.| +| audioChange | string | Yes| Yes| Audio.| +| videoChange | string | Yes| Yes| Video.| +| remoteFileChange | string | Yes| Yes| Remote file.| + +## PeerInfo + +Defines information about a registered device. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +| Name | Type | Readable| Writable| Description | +| ---------- | -------------------------- | ---- | ---- | ---------------- | +| deviceName | string | Yes | No | Name of the registered device. | +| networkId | string | Yes | No | Network ID of the registered device.| +| isOnline | boolean | Yes | No | Whether the registered device is online. | + + +## FileType + +Enumerates media file types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Value| Description| +| ----- | ---- | ---- | +| IMAGE | 1 | Image.| +| VIDEO | 2 | Video.| +| AUDIO | 3 | Audio.| + +## PrivateAlbumType + +Enumerates the system album types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Value| Description | +| ----- | ---- | ---- | +| TYPE_FAVORITE | 0 | Favorites.| +| TYPE_TRASH | 1 | Recycle bin.| + + + +## AudioKey + +Defines the key information about an audio file. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | File URI. | +| DISPLAY_NAME | display_name | File name displayed. | +| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | title | Title in the file. | +| ARTIST | artist | Author of the file. | +| AUDIOALBUM | audio_album | Audio album. | +| DURATION | duration | Duration, in ms. | +| FAVORITE | favorite | Whether the file is added to favorites. | + +## ImageVideoKey + +Defines the key information about an image or video file. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | File URI. | +| FILE_TYPE | file_type | Type of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | title | Title in the file. | +| DURATION | duration | Duration, in ms. | +| WIDTH | width | Image width, in pixels. | +| HEIGHT | height | Image height, in pixels. | +| DATE_TAKEN | date_taken | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | +| ORIENTATION | orientation | Orientation of the image file. | +| FAVORITE | favorite | Whether the file is added to favorites. | + +## AlbumKey + +Defines the key album information. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | Album URI. | +| FILE_TYPE | file_type | Type of the file. | +| ALBUM_NAME | album_name | Name of the album. | +| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | + + +## FetchOptions + +Defines the options for fetching media files. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Description | +| ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ | +| fetchColumns | Array<string> | Yes | Yes | Columns to fetch. If this parameter is left empty, data is fetched by URI, name, and file type by default. For example,
**fetchColumns: "uri"**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | Yes | Yes | Predicates that specify the fetch criteria.| + +## AlbumFetchOptions + +Defines the options for fetching an album. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Description | +| ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | Yes | Yes | Predicates that specify the fetch criteria.| diff --git a/en/application-dev/reference/apis/js-apis-userfilemanager.md b/en/application-dev/reference/apis/js-apis-userfilemanager.md deleted file mode 100644 index bc02ba6fd6cde0da0b9c81932c60cfe94a3976c0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-userfilemanager.md +++ /dev/null @@ -1,2520 +0,0 @@ -# User Data Management - -> **NOTE**
-> This module is supported since API Version 9. Updates will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -```js -import userFileManager from '@ohos.filemanagement.userfile_manager'; -``` - -## userFileManager.getUserFileMgr - -getUserFileMgr(context: Context): UserFileManager - -Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video files, images, and documents). - -**Model restriction**: This API can be used only in the stage model. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | -------------------------- | -| context | [Context](../apis/js-apis-inner-app-context.md) | Yes | Context of the ability instance.| - -**Return value** - -| Type | Description | -| ----------------------------- | :---- | -| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| - -**Example** - -```ts -const context = getContext(this); -let userFileMgr = userfilemanager.getUserFileMgr(context); -``` - -## userFileManager.getUserFileMgr - -getUserFileMgr(): UserFileManager - -Obtains a **UserFileManager** instance.This instance can be used to access and modify user media data (such as audio and video clips, images, and documents). - -**Model restriction**: This API can be used only in the FA model. - -> **NOTE**
You are advised to use [UserFileManager.getUserFileMgr](#userfilemanagergetuserfilemgr), the API used in the stage model. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ----------------------------- | :--------- | -| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| - -**Example** - -```js -let userFileMgr = userfilemanager.getUserFileMgr(); -``` - -## UserFileManager - -### getPublicDirectory - -getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void; - -Obtains the preset public directory. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ------------------------- | -| type | [DirectoryType](#directorytype) | Yes | Type of the public directory. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the public directory.| - -**Example** - -```ts -async function getPublicDirectoryDemoCallback() { - console.info('getPublicDirectoryDemo'); - let DIR_CAMERA = directoryType.DIR_CAMERA; - console.info('DIR_CAMERA', DIR_CAMERA); - userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { - if (dicResult == 'Camera/') { - console.info('mediaLibraryTest : getPublicDirectory passed'); - } else { - console.info('mediaLibraryTest : getPublicDirectory failed'); - } - }); -} -``` - -### getPublicDirectory - -getPublicDirectory(type: DirectoryType): Promise<string>; - -Obtains the preset public directory. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------ | -| type | [DirectoryType](#directorytype) | Yes | Type of the public directory.| - -**Return value** - -| Type | Description | -| ---------------- | ---------------- | -| Promise\ | Promise used to return the public directory.| - -**Example** - -```ts -async function getPublicDirectoryDemoPromise() { - console.info('getPublicDirectoryDemo'); - let DIR_CAMERA = directoryType.DIR_CAMERA; - try { - let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA); - console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult); - } catch (err) { - console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err); - } -} -``` - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; - -Obtains file assets. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ------------------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | -| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the file assets obtained.| - -**Example** - -```ts -async function getFileAssetsDemoCallback() { - console.info('getFileAssets'); - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE - let fetchOp = { - selections: '', - selectionArgs: [], - }; - - userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => { - if (fetchFileResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchFileResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - }; - } - }) -} -``` - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; - -Obtains file assets. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------------------- | ---- | ---------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media type to obtain.| -| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | - -**Return value** - -| Type | Description | -| --------------------------- | -------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| - -**Example** - -```ts -async function getFileAssetsDemoPromise() { - console.info('getFileAssets'); - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE - let fetchOp = { - selections: '', - selectionArgs: [], - }; - try { - var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp) - } catch (err) { - console.info('getFileAssets failed, message = ', err); - } - - if (fetchFileResult != undefined) { - console.info('fetchFileResult success'); - let fileAsset = await fetchFileResult.getFirstObject(); - if (fileAsset != undefined) { - console.info("fileAsset.displayName :" + fileAsset.displayName); - }; - } -} -``` - -### on - -on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void - -Subscribes to changes of the file management library. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Media type to subscribe to.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**fileChange** indicates the file change.
**remoteFileChange** indicates the file change on the registered device.| -| callback | Callback<void> | Yes | Callback that returns no value. | - -**Example** - -```ts -async function onDemo() { - console.info('onDemo') - userFileMgr.on('imageChange', () => { - // Image file changes. Do something. - }); -} -``` - -### off - -off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void - -Unsubscribes from changes of the file management library. This API uses a callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Media type to unsubscribe from.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**fileChange** indicates the file change.
**remoteFileChange** indicates the file change on the registered device.| -| callback | Callback<void> | No | Callback that returns no value. | - -**Example** - -```ts -async function offDemo() { - console.info('offDemo') - userFileMgr.off('imageChange', () => { - // stop listening success - }); -} -``` - -### createAsset - -createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void - -Creates a file asset. This API uses an asynchronous callback to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------------ | --------------------------- | ---- | ------------------------------------------------------------ | -| mediaType | [MediaType](#mediatype) | Yes | Media type. | -| displayName | string | Yes | File name to display. | -| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.| -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset created. | - -**Example** - -```ts -async function createAssetDemoCallback() { - console.info('createAssetDemo') - let mediaType = userfile_manager.MediaType.FILE; - let DIR_DOC = directoryType.DIR_DOCUMENTS; - const path = await userFileMgr.getPublicDirectory(DIR_DOC); - userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => { - if (err == undefined) { - console.info('createAsset successfully'); - } else { - console.info('createAsset failed, message = ', err); - } - }) -} -``` - -### createAsset - -createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>; - -Creates a file asset. This API uses a promise to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------------ | --------- | ---- | ------------------------------------------------------------ | -| mediaType | [MediaType](#mediatype) | Yes | Media type. | -| displayName | string | Yes | File name to display. | -| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.| - -**Return value** - -| Type | Description | -| --------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset created.| - -**Example** - -```ts -async function createAssetDemoPromise() { - console.info('createAssetDemo') - let mediaType = userfile_manager.MediaType.FILE; - let DIR_DOC = directoryType.DIR_DOCUMENTS; - const path = await userFileMgr.getPublicDirectory(DIR_DOC); - try { - let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/') - console.info('createAsset successfully'); - } catch (err) { - console.info('createAsset failed, message = ', err); - } -} -``` - -### deleteAsset - -deleteAsset(uri: string, callback: AsyncCallback<void>): void; - -Deletes a file asset. This API uses an asynchronous callback to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------- | -| uri | string | Yes | URI of the file to delete. | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the result.| - -**Example** - -```ts -async function deleteAssetDemoCallback() { - console.info('deleteAssetDemo') - let fileKeyObj = userfile_manager.FileKey - let fileType = userfile_manager.MediaType.FILE - let option = { - selections: '', - selectionArgs: [], - }; - try { - const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); - var asset = await fetchFileResult.getFirstObject(); - } catch(err) { - console.info('fetch failed, message =', err) - } - - if (asset == undefined) { - console.error('asset not exist') - return - } - userFileMgr.deleteAsset(asset.uri, (err) => { - if (err == undefined) { - console.info("deleteAsset successfully"); - } else { - console.info("deleteAsset failed with error:"+ err); - } - }); -} -``` - -### deleteAsset - -deleteAsset(uri: string): Promise<void>; - -Deletes a file asset. This API uses a promise to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| uri | string | Yes | URI of the file to delete.| - -**Return value** - -| Type | Description | -| ---------------- | --------------------------------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```ts -async function deleteAssetDemoPromise() { - console.info('deleteAssetDemo') - let fileKeyObj = userfile_manager.FileKey - let fileType = userfile_manager.MediaType.FILE - let option = { - selections: '', - selectionArgs: [], - }; - try { - const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); - var asset = await fetchFileResult.getFirstObject(); - } catch(err) { - console.info('fetch failed, message =', err) - } - if (asset == undefined) { - console.error('asset not exist') - return - } - try { - await userFileMgr.deleteAsset(asset.uri); - console.info("deleteAsset successfully"); - } catch (err) { - console.info("deleteAsset failed with error:"+ err); - } -} -``` - -### getAlbums - -getAlbums(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback | Yes | Type of the media data to obtain. | -| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | -| callback | AsyncCallback<Array<[Album](#album)>> | Yes | Callback invoked to return the album list.| - -**Example** - -```ts -async function getAlbumsDemoCallback() { - console.info('getAlbumsDemo') - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => { - if (albumList != undefined) { - const album = albumList[0]; - console.info('first album.albumName = ' + album.albumName); - console.info('album.count = ' + albumList.length); - } else { - console.info('getAlbum fail, message = ' + err); - } - }) -} -``` - -### getAlbums - -getAlbums(type: Array<MediaType>, options: MediaFetchOptions): Promise>; - -Obtains albums. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------------------- | ---- | -------------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain.| -| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | - -**Return value** - -| Type | Description | -| ------------------------ | -------------------------- | -| Promise> | Promise used to return the album list.| - -**Example** - -```ts -async function getAlbumsDemoPromise() { - console.info('getAlbumsDemo') - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - try { - let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp); - const album = albumList[0]; - console.info('first album.albumName = ' + album.albumName); - console.info('album.count = ' + albumList.length); - } catch (err) { - console.info('getAlbum fail, message = ' + err); - } -} -``` - -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback): void - -Obtains the system album. This API uses an asynchronous callback to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ---------------------------------- | -| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain. | -| callback | AsyncCallback> | Yes | Callback invoked to return the system album obtained.| - -**Example** - -```ts -async function getPrivateAlbumDemoCallback() { - console.info('getPrivateAlbumDemo') - userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => { - if (err == undefined) { - console.info('getPrivateAlbum ok'); - try { - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - } catch (err) { - console.info('getFileAssets failed. message = ', err); - } - // Get file count in trash album - let count = fetchResult.getCount(); - console.info('fetchResult count = ', count) - // Get fileAssets in trash album - let trashAsset = await fetchResult.getFirstObject(); - // Get file trashed date - let isTrash = trashAsset.isTrash(); - console.info('is trashed', isTrash) - } else { - console.info('getPrivateAlbum failed. message = ', err); - } - }); -} -``` - -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType): Promise - -Obtains the system album. This API uses a promise to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ---------------- | ---- | ------------ | -| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain.| - -**Return value** - -| Type | Description | -| ------------------------------- | --------------------------------- | -| Promise> | Promise used to return the system album obtained.| - -**Example** - -```ts -async function getPrivateAlbumDemoPromise() { - console.info('getPrivateAlbumDemo'); - try { - var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - } catch(err) { - console.info('getPrivateAlbum failed. message = ', err); - } - try { - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - } catch (err) { - console.info('getFileAssets failed. message = ', err); - } - // Get file count in trash album - let count = fetchResult.getCount(); - console.info('fetchResult count = ', count) - // Get fileAssets in trash album - let trashAsset = await fetchResult.getFirstObject(); - - // Get file trashed date - let isTrash = trashAsset.isTrash(); - console.info('is trashed', isTrash) -} -``` - -### getActivePeers - -getActivePeers(callback: AsyncCallback>): void; - -Obtains information about online peer devices. This API uses an asynchronous callback to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback> | Yes | Callback invoked to return the online device list.| - -**Example** - -```ts -async function getActivePeersDemoCallback() { - console.info('getActivePeersDemo') - var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => { - if (err == undefined) { - console.log('getActivePeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('getActivePeers failed. message = ', err) - } - }); -} -``` - -### getActivePeers - -getActivePeers(): Promise>; - -Obtains information about online peer devices. This API uses a promise to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore - -**Return value** - -| Type | Description | -| --------------------------- | ----------------------------- | -| Promise> | Promise used to return the online device list.| - -**Example** - -```ts -async function getActivePeersDemoPromise() { - console.info('getActivePeersDemo') - try { - var devicesInfo = await userFileMgr.getActivePeers(); - } catch (err) { - console.info('getActivePeers failed. message = ', err) - } - if (devicesInfo != undefined) { - console.log('getActivePeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('get distributed fail') - } -} -``` - -### getAllPeers - -getAllPeers(callback: AsyncCallback>): void; - -Obtains information about all peer devices. This API uses an asynchronous callback to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------ | -| callback | AsyncCallback> | Yes | Callback invoked to return the peer device list.| - -**Example** - -```ts -async function getAllPeersDemoCallback() { - console.info('getAllPeersDemo') - var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => { - if (err == undefined) { - console.log('getAllPeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('getAllPeers failed. message = ', err) - } - }); -} -``` - -### getAllPeers - -getAllPeers(): Promise>; - -Obtains information about all peer devices. This API uses a promise to return the result. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore - -**Return value** - -| Type | Description | -| --------------------------- | ----------------------------- | -| Promise> | Promise used to return the peer device list.| - -**Example** - -```ts -async function getAllPeersDemoPromise() { - console.info('getAllPeersDemo') - try { - var devicesInfo = await userFileMgr.getAllPeers(); - } catch (err) { - console.info('getAllPeers failed. message = ', err) - } - if (devicesInfo != undefined) { - console.log('getAllPeers succeed.') - for (let i = 0; i < devicesInfo.length; i++) { - console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); - } - } else { - console.info('get distributed fail') - } -} -``` - -### release - -release(callback: AsyncCallback<void>): void - -Releases this **UserFileManager** instance. This API uses an asynchronous callback to return the result. -Call this API when the APIs in the **UserFileManager** instance are no longer used. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| - -**Example** - -```ts -async function releaseDemoCallback() { - console.info('releaseDemo'); - userFileMgr.release((err) => { - if (err != undefined) { - console.info('release failed. message = ', err); - } else { - console.info('release ok.'); - } - }) -} -``` - -### release - -release(): Promise<void> - -Releases this **UserFileManager** instance. This API uses a promise to return the result. -Call this API when the APIs in the **UserFileManager** instance are no longer used. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ------------------- | --------------------------------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```ts -async function releaseDemoPromise() { - console.info('releaseDemo'); - try { - await userFileMgr.release(); - console.info('release ok.'); - } catch (err) { - console.info('release failed. message = ', err); - } -} -``` - -## FileAsset - -Provides APIs for encapsulating file asset attributes. - -### Attributes - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Type | Readable| Writable| Description | -| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | -| uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. | -| mediaType | [MediaType](#mediatype) | Yes | No | Media type. | -| displayName | string | Yes | Yes | File name, including the file name extension, to display. | - - -### isDirectory - -isDirectory(callback: AsyncCallback<boolean>): void - -Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory((err, isDirectory) => { - // do something - }); -} -``` - -### isDirectory - -isDirectory():Promise<boolean> - -Checks whether this file asset is a directory. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ---------------------- | ---------------------------- | -| Promise<boolean> | Promise used to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - -```js -async function example() { - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory().then(function(isDirectory){ - console.info("isDirectory result:"+ isDirectory); - }).catch(function(err){ - console.info("isDirectory failed with error:"+ err); - }); -} -``` - -### commitModify - -commitModify(callback: AsyncCallback<void>): void - -Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----- | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.title = 'newtitle'; - asset.commitModify(() => { - console.info('commitModify success'); - }); -} -``` - -### commitModify - -commitModify(): Promise<void> - -Commits the modification on the file metadata to the database. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ------------------- | ---------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.title = 'newtitle'; - asset.commitModify(); -} -``` - -### open - -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 a write operation is complete, you must call **close** to release the resource. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ----------------------------------- | -| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| -| callback | AsyncCallback<number> | Yes | Callback used to return the file handle. | - -**Example** - -```js -async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); - const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw', (openError, fd) => { - if(fd > 0){ - asset.close(fd); - }else{ - console.info('File Open Failed!' + openError); - } - }); -} -``` - -### open - -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 a write operation is complete, you must call **close** to release the resource. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ----------------------------------- | -| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| - -**Return value** - -| Type | Description | -| --------------------- | ------------- | -| Promise<number> | Promise used to return the file handle.| - -**Example** - -```js -async function example() { - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); - const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); - asset.open('rw') - .then((fd) => { - console.info('File fd!' + fd); - }) - .catch((err) => { - console.info('File err!' + err); - }); -} -``` - -### close - -close(fd: number, callback: AsyncCallback<void>): void - -Closes this file asset. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----- | -| fd | number | Yes | File descriptor.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.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.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } - }); - }) - .catch((err) => { - console.info('File err!' + err); - }); -} -``` - -### close - -close(fd: number): Promise<void> - -Closes this file asset. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ----- | -| fd | number | Yes | File descriptor.| - -**Return value** - -| Type | Description | -| ------------------- | ---------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.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.info('mediaLibraryTest : close : FAIL ' + closeErr); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - - } else { - console.info("=======asset.close success====>"); - } - }); - }) - .catch((err) => { - console.info('File err!' + err); - }); -} -``` - -### getThumbnail - -getThumbnail(callback: AsyncCallback<image.PixelMap>): void - -Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[image.PixelMap](../apis/js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail((err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }); -} -``` - -### getThumbnail - -getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void - -Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------- | ---- | ---------------- | -| size | [Size](#size) | Yes | Size of the thumbnail to obtain. | -| callback | AsyncCallback<[image.PixelMap](../apis/js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| - -**Example** - -```js -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: "", - }; - let size = { width: 720, height: 720 }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size, (err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }); -} -``` - -### getThumbnail - -getThumbnail(size?: Size): Promise<image.PixelMap> - -Obtains the file thumbnail of the given size. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | -------------- | ---- | ----- | -| size | [Size](#size) | No | Size of the thumbnail to obtain.| - -**Return value** - -| Type | Description | -| ----------------------------- | --------------------- | -| Promise<[image.PixelMap](../apis/js-apis-image.md#pixelmap7)> | Promise used to return the pixel map of the thumbnail.| - -**Example** - -```js -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: "", - }; - let size = { width: 720, height: 720 }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.getThumbnail(size) - .then((pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); - }) - .catch((err) => { - console.info('mediaLibraryTest : getThumbnail fail'+ err); - }); -} -``` - -### favorite - -favorite(isFavorite: boolean, callback: AsyncCallback<void>): void - -Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | ---- | ---------------------------------- | -| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true,function(err){ - // Do something. - }); -} -``` - -### favorite - -favorite(isFavorite: boolean): Promise<void> - -Favorites or unfavorites this file asset. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---------- | ------- | ---- | ---------------------------------- | -| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| - -**Return value** - -| Type | Description | -| ------------------- | ---------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.favorite(true).then(function() { - console.info("favorite successfully"); - }).catch(function(err){ - console.info("favorite failed with error:"+ err); - }); -} -``` - -### isFavorite - -isFavorite(callback: AsyncCallback<boolean>): void - -Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ----------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.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'); - } - }); -} -``` - -### isFavorite - -isFavorite():Promise<boolean> - -Checks whether this file asset is favorited. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ---------------------- | ------------------ | -| Promise<boolean> | Promise used to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isFavorite().then(function(isFavorite){ - console.info("isFavorite result:"+ isFavorite); - }).catch(function(err){ - console.info("isFavorite failed with error:"+ err); - }); -} -``` - -### trash - -trash(isTrash: boolean, callback: AsyncCallback<void>): void - -Moves this file asset to the trash. This API uses an asynchronous callback to return the result. - -Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------- | -| isTrash | boolean | Yes | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value. | - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.trash(true, trashCallBack); - function trashCallBack(err, trash) { - console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); - } -} -``` - -### trash - -trash(isTrash: boolean): Promise<void> - -Moves this file asset to the trash. This API uses a promise to return the result. - -Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------- | ------- | ---- | --------- | -| isTrash | boolean | Yes | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.| - -**Return value** - -| Type | Description | -| ------------------- | ---------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.trash(true).then(function() { - console.info("trash successfully"); - }).catch(function(err){ - console.info("trash failed with error:"+ err); - }); -} -``` - -### isTrash - -isTrash(callback: AsyncCallback<boolean>): void - -Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | --------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.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); - }); -} -``` - -### isTrash - -isTrash():Promise<boolean> - -Checks whether this file asset is in the trash. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ------------------- | -------------------- | -| Promise<void> | Promise used to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - -```js -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", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.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); - }); -} -``` - -## FetchFileResult - -Provides APIs to manage the file retrieval result. - -### getCount - -getCount(): number - -Obtains the total number of files in the result set. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ------ | -------- | -| number | Total number of files.| - -**Example** - -```js -async function example() { - let fileKeyObj = mediaLibrary.FileKey; - let fileType = mediaLibrary.MediaType.FILE; - let getFileCountOneOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [fileType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp); - const fetchCount = fetchFileResult.getCount(); -} -``` - -### isAfterLast - -isAfterLast(): boolean - -Checks whether the cursor is in the last row of the result set. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ------- | ---------------------------------- | -| boolean | Returns **true** if the cursor is in the last row of the result set; returns **false** otherwise.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : 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(); - } - } -} -``` - -### close - -close(): void - -Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.close(); -} -``` - -### getFirstObject - -getFirstObject(callback: AsyncCallback<FileAsset>): void - -Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the first file asset.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) -} -``` - -### getFirstObject - -getFirstObject(): Promise<FileAsset> - -Obtains the first file asset in the result set. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| --------------------------------------- | -------------------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the first file asset.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getFirstObject().then(function(fileAsset){ - console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); - }).catch(function(err){ - console.info("getFirstObject failed with error:"+ err); - }); -} -``` - -### getNextObject - - getNextObject(callback: AsyncCallback<FileAsset>): void - -Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | --------------------------------------------- | ---- | ----------------------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the next file asset.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) -} -``` - -### getNextObject - - getNextObject(): Promise<FileAsset> - -Obtains the next file asset in the result set. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the next file asset.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const fetchCount = fetchFileResult.getCount(); - console.info('mediaLibraryTest : count:' + fetchCount); - let fileAsset = await fetchFileResult.getNextObject(); -} -``` - -### getLastObject - -getLastObject(callback: AsyncCallback<FileAsset>): void - -Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the last file asset.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) -} -``` - -### getLastObject - -getLastObject(): Promise<FileAsset> - -Obtains the last file asset in the result set. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the last file asset.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - let lastObject = await fetchFileResult.getLastObject(); -} -``` - -### getPositionObject - -getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void - -Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------ | -| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset obtained.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, fileAsset) => { - if (err) { - console.error('Failed '); - return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }) -} -``` - -### getPositionObject - -getPositionObject(index: number): Promise<FileAsset> - -Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | -------------- | -| index | number | Yes | Index of the file asset to obtain. The value starts from **0**.| - -**Return value** - -| Type | Description | -| --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset obtained.| - -**Example** - -```js -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: "", - }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.log('fileAsset.displayName : ' + fileAsset.displayName); - }).catch(function (err) { - console.info("getFileAssets failed with error:" + err); - }); -} -``` - -## Album - -Provides APIs to manage albums. - -### Attributes - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Type | Readable | Writable | Description | -| ------------ | ------ | ---- | ---- | ------- | -| albumName | string | Yes | Yes | Album name. | -| albumUri | string | Yes | No | Album URI. | -| dateModified | number | Yes | No | Date when the album was last modified. | -| count | number | Yes | No | Number of files in the album.| -| relativePath | string | Yes | No | Relative path of the album. | -| coverUri | string | Yes | No | URI of the cover file of the album. - -### commitModify - -commitModify(callback: AsyncCallback<void>): void; - -Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| - -**Example** - -```ts -async function commitModifyDemoCallback() { - console.info('commitModifyDemo') - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: '', - selectionArgs: [], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); - let asset = await fetchFileResult.getFirstObject(); - console.info('old displayName:', asset.displayName) - asset.displayName = 'newDisplayName'; - console.info('new displayName:', asset.displayName) - asset.commitModify((err) => { - if (err == undefined) { - console.info('commitModify succeed.') - } else { - console.info('commitModify failed, message =', err); - } - }); -} -``` - -### commitModify - -commitModify(): Promise<void>; - -Commits the modification on the album attributes to the database. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Return value** - -| Type | Description | -| ------------------- | ------------ | -| Promise<void> | Promise that returns no value.| - -**Example** - -```ts -async function commitModifyDemoPromise() { - console.info('commitModifyDemo') - let fileKeyObj = userfile_manager.FileKey - let imageType = userfile_manager.MediaType.IMAGE; - let getImageOp = { - selections: '', - selectionArgs: [], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", - }; - let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); - let asset = await fetchFileResult.getFirstObject(); - console.info('old displayName:', asset.displayName) - asset.displayName = 'newDisplayName'; - console.info('new displayName:', asset.displayName) - try { - await asset.commitModify(); - console.info('commitModify succeed.') - } catch (err) { - console.info('commitModify failed, message =', err); - } -} -``` - -### getFileAssets - -getFileAssets(type: Array<MediaType>, callback: AsyncCallback<FetchFileResult>): void; - -Obtains the file assets in this album. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| - -**Example** - -```ts -async function albumGetFileAssetsDemoCallback() { - console.info('albumGetFileAssetsDemoCallback2') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], (err, albumFetchFileResult) => { - if (err == undefined) { - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - } else { - console.info("getFileAssets failed with error:"+ err); - } - }); -} -``` - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; - -Obtains the file assets in this album. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | -| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the media data. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| - -**Example** - -```ts -async function albumGetFileAssetsDemoCallback() { - console.info('albumGetFileAssetsDemoCallback') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - } - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => { - if (err == undefined) { - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - } else { - console.info("getFileAssets failed with error:"+ err); - } - }); - } -``` - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options?: MediaFetchOptions): Promise<FetchFileResult>; - -Obtains the file assets in this album. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------------- | ---- | -------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | -|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the media data.| - -**Return value** - -| Type | Description | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| - -**Example** - -```ts -async function albumGetFileAssetsDemoPromise() { - console.info('albumGetFileAssetsDemoPromise') - let imageType = userfile_manager.MediaType.IMAGE; - let AlbumNoArgsfetchOp = { - selections: '', - selectionArgs: [], - }; - let fileNoArgsfetchOp = { - selections: '', - selectionArgs: [], - } - const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); - const album = albumList[0]; - album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); - }).catch(function(err){ - console.info("getFileAssets failed with error:"+ err); - }); -} -``` -## VirtualAlbum -Provides APIs for managing a virtual album. - -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; - -Obtains file assets in the virtual album. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -> **NOTE**
-> The ability privilege level (APL) of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the Access Control List (ACL). For details, see [ACL](../../security/accesstoken-overview.md#acl). -> -> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ----------------------------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | -| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| - -**Example** - -```ts -async function virtualAlbumGetFileAssetsDemoCallback() { - console.info('virtualAlbumGetFileAssetsDemoCallback') - try { - var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - } catch (err) { - console.info('getPrivateAlbum failed, message = ', err); - } - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - - trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => { - if (err == undefined) { - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); - } else { - console.info('getFileAssets failed, message = ', err); - } - }); -} -``` - -### getFileAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; - -Obtains file assets in the virtual album. This API uses a promise to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT - -> **NOTE**
-> The APL of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the ACL. For details, see [ACL](../../security/accesstoken-overview.md#acl). -> -> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------------- | ---- | -------------- | -| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | -|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the files.| - -**Return value** - -| Type | Description | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| - -**Example** - -```ts -async function virtualAlbumGetFileAssetsDemoPromise() { - console.info('virtualAlbumGetFileAssetsDemoPromise') - let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); - let fetchOpt = { - selections: '', - selectionArgs: [], - }; - let trashAlbum = albumArray[0]; - - let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); -} -``` - -## PeerInfo - -Describes information about a registered device. -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore - -| Name | Type | Readable| Writable| Description | -| ---------- | -------------------------- | ---- | ---- | ---------------- | -| deviceName | string | Yes | No | Name of the registered device. | -| networkId | string | Yes | No | Network ID of the registered device.| -| isOnline | boolean | Yes | No | Whether the registered device is online. | - -## MediaType - -Enumerates the media types. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Description| -| ----- | ---- | -| FILE | File.| -| IMAGE | Image.| -| VIDEO | Video.| -| AUDIO | Audio.| - -## FileKey - -Defines the key file information. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Default Value | Description | -| ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | File URI. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | -| DISPLAY_NAME | display_name | File name displayed. | -| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | -| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | -| TITLE | title | Title in the file. | - -## AudioKey - -Defines the key information about an audio file. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Default Value | Description | -| ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | Promise used to return the URI of the file created. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | -| DISPLAY_NAME | display_name | File name displayed. | -| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | -| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | -| TITLE | title | Title in the file. | -| ARTIST | artist | Author of the file. | -| AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in ms. | - -## ImageVideoKey - -Defines the key information about an image or video file. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Default Value | Description | -| ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | File URI. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | -| DISPLAY_NAME | display_name | File name displayed. | -| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | -| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | -| DURATION | duration | Duration, in ms. | -| WIDTH | width | Image width, in pixels. | -| HEIGHT | height | Image height, in pixels. | -| DATE_TAKEN | date_taken | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | - -## AlbumKey - -Defines the key album information. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Default Value | Description | -| ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | Album URI. | -| RELATIVE_PATH | relative_path | Relative public directory of the album. | -| DISPLAY_NAME | display_name | Album name displayed. | -| DATE_ADDED | date_added | Date when the album was added. The value is the number of seconds elapsed since the Epoch time. | -| DATE_MODIFIED | date_modified | Date when the album was last modified. The value is the number of seconds elapsed since the Epoch time. | - -## DirectoryType - -Enumerates directory types. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Description | -| ------------- | ------------------ | -| DIR_CAMERA | Directory of camera files.| -| DIR_VIDEO | Directory of video files. | -| DIR_IMAGE | Directory of image files. | -| DIR_AUDIO | Directory of audio files. | -| DIR_DOCUMENTS | Directory of documents. | -| DIR_DOWNLOAD | Download directory. | - -## MediaFetchOptions - -Defines the options for fetching media files. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Type | Readable| Writable| Mandatory| Description | -| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | Yes | Yes | Yes | Conditions for fetching files. The values in [FileKey](#filekey) 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 | Yes | Values of the conditions specified in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | - -## Size - -Defines the image size. -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | -------- | -| width | number | Yes | Yes | Image width, in pixels.| -| height | number | Yes | Yes | Image height, in pixels.| - -## VirtualAlbumType -Enumerates the system or virtual album types. - -This is a system API. - -**System capability**: SystemCapability.FileManagement.UserFileManager.Core - -| Name | Description | -| ------------- | ------------------ | -| TYPE_FAVORITE | Favorites album.
This is a system API.| -| TYPE_TRASH | Trash album.
This is a system API.| diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md index 9a45d1fe8f9644f0072fdfdb44c31f66c19e3d59..7005776c804fa21fe899f82d29253c2436b4f5ea 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -1,4 +1,4 @@ -# Facial Authentication +# @ohos.userIAM.faceAuth (Facial Authentication) The **userIAM.faceAuth** module provides APIs for face enrollment. @@ -34,17 +34,17 @@ A constructor used to create a **FaceAuthManager** object. **Example** - ```js - import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; - let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); - ``` +let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); +``` ### setSurfaceId setSurfaceId(surfaceId: string): void; -Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. +Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. This API must be used with [AddCredential](./js-apis-osAccount.md#addcredential8). **System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth @@ -56,17 +56,28 @@ Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#ge | -------------- | ---------------------------------- | ---- | -------------------------- | | surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| +For details about the following error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 12700001 | The operation is failed. | + **Example** - ```js - import faceAuth from '@ohos.userIAM.faceAuth'; - - let surfaceId = "123456"; - let manager = new faceAuth.FaceAuthManager(); - try { - manager.setSurfaceId(surfaceId); - console.info("Set the surface ID successfully"); - } catch (e) { - console.error("Failed to set the surface ID, error = " + e); - } - ``` +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + +// The surfaceId is obtained from the XComponent control. The surfaceId here is only an example. +let surfaceId = "123456"; +let manager = new userIAM_faceAuth.FaceAuthManager(); +try { + manager.setSurfaceId(surfaceId); + console.info("Set the surface ID successfully"); +} catch (e) { + console.error("Failed to set the surface ID, error = " + e); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index ce73ba0bcd0ed53bb75bcb873cf35dd8f6910f6d..29044d135b43286a8b3df624584750022f6576b8 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,4 +1,4 @@ -# User Authentication +# @ohos.userIAM.userAuth (User Authentication) The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login. @@ -12,268 +12,115 @@ The **userIAM.userAuth** module provides user authentication capabilities in ide import userIAM_userAuth from '@ohos.userIAM.userAuth'; ``` -## Sample Code - -```js -// API version 9 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -export default { - getVersion() { - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - }, - - start() { - console.info("start auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - // If tips are needed - auth.on("tip", { - callback : (result : userIAM_userAuth.TipInfo) => { - switch (result.tip) { - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: - // Do something; - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: - // Do something; - // ... - default: - // Do others. - } - } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - }, +## AuthResultInfo9+ - getAvailableStatus() { - console.info("start check auth support"); - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - }, +Defines the authentication result. - cancel() { - console.info("start cancel auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +**System capability**: SystemCapability.UserIAM.UserAuth.Core - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| result | number | Yes | Authentication result. | +| token | Uint8Array | No | Token that has passed the user identity authentication.| +| remainAttempts | number | No | Number of remaining authentication times allowed.| +| lockoutDuration | number | No | Time for which the authentication operation is frozen.| -```js -// API version 8 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; -let auth = new userIAM_userAuth.UserAuth(); +## TipInfo9+ -export default { - getVersion() { - console.info("start get version"); - let version = auth.getVersion(); - console.info("auth version = " + version); - }, - - startAuth() { - console.info("start auth"); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - }, - - checkAuthSupport() { - console.info("start check auth support"); - let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - }, - - cancelAuth() { - console.info("start cancel auth"); - // Obtain contextId using auth(). - let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - console.info("auth onResult result = " + result); - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - console.info("auth onAcquireInfo module = " + module); - } - }); - let cancelCode = this.auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - } -} -``` +Defines the authentication tip information. -```js -// API version 6 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; +**System capability**: SystemCapability.UserIAM.UserAuth.Core -export default { - startAuth() { - console.info("start auth"); - let auth = userIAM_userAuth.getAuthenticator(); - auth.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - // Add the logic to be executed when the authentication is successful. - }).catch((code)=>{ - console.error("auth fail, code = " + code); - // Add the logic to be executed when the authentication fails. - }); - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| module | number | Yes | ID of the module that sends the tip information. | +| tip | number | Yes | Tip to be given during the authentication process. | ## EventInfo9+ -Defines the event information used in authentication. +Enumerates the authentication event information types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Type | Description | +| Value | Description | | --------- | ----------------------- | -| [AuthResultInfo](#authresultinfo9) | Authentication result information. | +| [AuthResultInfo](#authresultinfo9) | Authentication result. | | [TipInfo](#tipinfo9) | Authentication tip information. | +## AuthEventKey9+ + +Defines the keyword of the authentication event type. It is used as a parameter of [on](#on9). + +| Value | Description | +| ---------- | ----------------------- | +| "result" | If the first parameter of [on](#on9) is **result**, the [callback](#callback9) returns the authentication result.| +| "tip" | If the first parameter of [on](#on9) is **tip**, the [callback](#callback9) returns the authentication tip information.| + ## AuthEvent9+ -Provides callbacks to return authentication events. +Provides an asynchronous callback to return the authentication event information. ### callback9+ -callback: (result : EventInfo) => void +callback(result : EventInfo) : void -Called to return the authentication result or authentication tips. +Called to return the authentication result or authentication tip information. **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | -------------------------------------------------------- | -| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------ | +| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +// Obtain the authentication result through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` - -## AuthResultInfo9+ - -Defines the authentication result information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| result | number | Yes | Authentication result. | -| token | Uint8Array | No | Token that has passed the user identity authentication.| -| remainAttempts | number | No | Number of remaining authentication times allowed.| -| lockoutDuration | number | No | Time for which the authentication operation is frozen.| - -## TipInfo9+ - -Defines the authentication tip information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| module | number | No | Authentication module. | -| tip | number | No | Tip to be given during the authentication process. | - -## AuthEventKey9+ - -Defines the keyword of an authentication event. - -| Value | Description | -| ---------- | ----------------------- | -| "result" | Indicates authentication result.| -| "tip" | If **AuthEventKey** is **result**, the callback returns the authentication tip information.| + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +// Obtain the authentication tip information through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("tip", { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // Do something; + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // Do something. + default: + // Do others. + } + } + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ## AuthInstance9+ @@ -281,9 +128,12 @@ Implements user authentication. ### on9+ -on(name : AuthEventKey, callback : AuthEvent) : void +on : (name : AuthEventKey, callback : AuthEvent) => void -Enables authentication event listening. +Subscribes to the user authentication events of the specified type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to subscribe to events. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -291,151 +141,210 @@ Enables authentication event listening. | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event to listen for. | -| callback | AuthEvent | Yes | Callback invoked to return the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Authentication event type. If the value is **result**, the callback returns the authentication result. If the value is **tip**, the callback returns the authentication tip information.| +| callback | [AuthEvent](#authevent9) | Yes | Callback invoked to return the authentication result or tip information.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - // If tips are needed - auth.on("tip", { + }); + // Subscribe to authentication tip information. + auth.on("tip", { callback : (result : userIAM_userAuth.TipInfo) => { switch (result.tip) { case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: // Do something; case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: // Do something; - // ... default: // Do others. } } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ### off9+ -off(name : AuthEventKey) : void +off : (name : AuthEventKey) => void -Disables authentication event listening. +Unsubscribes from the user authentication events of the specific type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to unsubscribe from events. **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Type of the authentication event to unsubscribe from. If the value is **result**, the authentication result is unsubscribed from. If the value is **tip**, the authentication tip information is unsubscribed from.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let auth; +try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); +} catch (error) { + console.log("get auth instance failed" + error); +} - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +try { + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - console.log("turn on authentication event listening success"); - } catch (error) { - console.log("turn off authentication event listening failed " + error); - // do error - } - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.off("result"); - console.info("turn off authentication event listening success"); - } catch (error) { - console.info("turn off authentication event listening failed, error = " + error); - } - ``` + }); + console.log("subscribe authentication event success"); +} catch (error) { + console.log("subscribe authentication event failed " + error); +} +// Unsubscribe from the authentication result. +try { + auth.off("result"); + console.info("cancel subscribe authentication event success"); +} catch (error) { + console.info("cancel subscribe authentication event failed, error = " + error); +} +``` ### start9+ -start() : void +start : () => void Starts authentication. +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500001 | Authentication failed. | +| 12500002 | General operation error. | +| 12500003 | The operation is canceled. | +| 12500004 | The operation is time-out. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500007 | The authentication task is busy. | +| 12500009 | The authenticator is locked. | +| 12500010 | The type of credential has not been enrolled. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.start(); + console.info("authV9 start auth success"); +} catch (error) { + console.info("authV9 start auth failed, error = " + error); +} +``` ### cancel9+ -cancel(): void +cancel : () => void -Cancels the authentication. +Cancels this authentication. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. The [AuthInstance](#authinstance9) instance must be the one being authenticated. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.cancel(); + console.info("cancel auth success"); +} catch (error) { + console.info("cancel auth failed, error = " + error); +} +``` ## userIAM_userAuth.getAuthInstance9+ @@ -444,7 +353,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel Obtains an **AuthInstance** instance for user authentication. > **NOTE**
-> Each **AuthInstance** can be used to initiate an authentication only once. +> An **AuthInstance** instance can be used for an authentication only once. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -460,23 +369,35 @@ Obtains an **AuthInstance** instance for user authentication. | Type | Description | | ----------------------------------------- | ------------ | -| [AuthInstance](#authinstance9) | **Authenticator** object obtained.| +| [AuthInstance](#authinstance9) | **Authenticator** instance obtained.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - console.info("get auth instance success"); - } catch (error) { - console.info("get auth instance success failed, error = " + error); - } - ``` +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.info("get auth instance success"); +} catch (error) { + console.info("get auth instance success failed, error = " + error); +} +``` ## userIAM_userAuth.getVersion9+ @@ -494,24 +415,33 @@ Obtains the version of this authenticator. | ------ | ---------------------- | | number | Authenticator version obtained.| +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - ``` +try { + let version = userIAM_userAuth.getVersion(); + console.info("auth version = " + version); +} catch (error) { + console.info("get version failed, error = " + error); +} +``` ## userIAM_userAuth.getAvailableStatus9+ getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void -Checks whether the authentication capability of the specified trust level is available. +Checks whether the specified authentication capability is supported. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -522,54 +452,65 @@ Checks whether the authentication capability of the specified trust level is ava | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500010 | The type of credential has not been enrolled. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - ``` +try { + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info("current auth trust level is supported"); +} catch (error) { + console.info("current auth trust level is not supported, error = " + error); +} +``` - ## ResultCodeV99+ +## UserAuthResultCode9+ -Enumerates the operation results. +Enumerates the authentication result codes. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------- | ------ | -------------------- | -| SUCCESS | 12500000 | The operation is successful. | -| FAIL | 12500001 | The operation failed. | -| GENERAL_ERROR | 12500002 | A common operation error occurred. | -| CANCELED | 12500003 | The operation is canceled. | -| TIMEOUT | 12500004 | The operation timed out. | +| SUCCESS | 12500000 | The authentication is successful. | +| FAIL | 12500001 | The authentication failed. | +| GENERAL_ERROR | 12500002 | A general operation error occurred. | +| CANCELED | 12500003 | The authentication is canceled. | +| TIMEOUT | 12500004 | The authentication timed out. | | TYPE_NOT_SUPPORT | 12500005 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 12500006 | The authentication trust level is not supported. | | BUSY | 12500007 | Indicates the busy state. | -| INVALID_PARAMETERS | 12500008 | Invalid parameters are detected. | | LOCKED | 12500009 | The authentication executor is locked. | | NOT_ENROLLED | 12500010 | The user has not entered the authentication information.| ## UserAuth8+ -Provides methods to manage an **Authenticator** object. +Provides APIs to manage an **Authenticator** object. ### constructor(deprecated) constructor() -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). +A constructor used to create an authenticator instance. -A constructor used to create an **authenticator** object. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -577,25 +518,24 @@ A constructor used to create an **authenticator** object. | Type | Description | | ---------------------- | -------------------- | -| [UserAuth](#userauth8) | **Authenticator** object obtained.| +| [UserAuth](#userauth8) | **Authenticator** instance obtained.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - ``` +let auth = new userIAM_userAuth.UserAuth(); +``` ### getVersion(deprecated) getVersion() : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). +Obtains the version of this authenticator. -Obtains the authentication executor version. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -609,23 +549,22 @@ Obtains the authentication executor version. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - let version = auth.getVersion(); - console.info("auth version = " + version); - ``` +let auth = new userIAM_userAuth.UserAuth(); +let version = auth.getVersion(); +console.info("auth version = " + version); +``` ### getAvailableStatus(deprecated) getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). +Checks whether the specified authentication capability is supported. -Obtains the available status of the specified authentication trust level. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -636,40 +575,37 @@ Obtains the available status of the specified authentication trust level. | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Available status obtained. For details, see [ResultCode](#resultcodedeprecated).| +| number | Query result. If the authentication capability is supported, **SUCCESS** is returned. Otherwise, a [ResultCode](#resultcodedeprecated) is returned.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); +if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); +} else { + console.error("check auth support fail, code = " + checkCode); +} +``` ### auth(deprecated) auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9). - Performs user authentication. This API uses a callback to return the result. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9). + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -680,8 +616,8 @@ Performs user authentication. This API uses a callback to return the result. | -------------- | ---------------------------------------- | ---- | ------------------------ | | challenge | Uint8Array | Yes | Challenge value, which can be null. | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | -| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | +| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | **Return value** @@ -691,36 +627,35 @@ Performs user authentication. This API uses a callback to return the result. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### cancelAuth(deprecated) cancelAuth(contextID : Uint8Array) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). +Cancels an authentication based on the context ID. -Cancels an authentication. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -730,100 +665,86 @@ Cancels an authentication. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | Context ID, which is obtained by using [auth](#authdeprecated).| +| contextID | Uint8Array | Yes | Context ID, which is obtained by [auth](#authdeprecated).| **Return value** | Type | Description | | ------ | ------------------------ | -| number | Whether the authentication is canceled.| +| number | Returns **SUCCESS** if the cancellation is successful. Returns a [ResultCode](#resultcodedeprecated) otherwise.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - // contextId can be obtained using auth(). In this example, it is defined here. - let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - let auth = new userIAM_userAuth.UserAuth(); - let cancelCode = auth.cancelAuth(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +// contextId can be obtained by auth(). In this example, it is defined here. +let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); +let auth = new userIAM_userAuth.UserAuth(); +let cancelCode = auth.cancelAuth(contextId); +if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); +} else { + console.error("cancel auth fail"); +} +``` ## IUserAuthCallback(deprecated) -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). +Provides callbacks to return the authentication result. -Defines the object of the result returned by the callback during authentication. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). ### onResult(deprecated) onResult: (result : number, extraInfo : AuthResult) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to return the authentication result. -Obtains the authentication result. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | ------------------------------------------------------------ | -| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated). | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------------------------ | +| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated).| | extraInfo | [AuthResult](#authresultdeprecated) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| - **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### onAcquireInfo(deprecated) onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to acquire authentication tip information. This API is optional. -Obtains the tip code information during authentication. This function is optional. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -831,89 +752,74 @@ Obtains the tip code information during authentication. This function is optiona | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------ | -| module | number | Yes | Type of the authentication executor. | -| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| +| module | number | Yes | ID of the module that sends the tip information. | +| acquire | number | Yes | Authentication tip information.| | extraInfo | any | Yes | Reserved field. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; -## AuthResult(deprecated) +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } +}); +``` -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). +## AuthResult(deprecated) Represents the authentication result object. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). + **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| token | Uint8Array | No | Identity authentication token. | +| ------------ | ---------- | ---- | -------------------| +| token | Uint8Array | No | Authentication token information.| | remainTimes | number | No | Number of remaining authentication operations.| | freezingTime | number | No | Time for which the authentication operation is frozen.| ## ResultCode(deprecated) -> **NOTE**
-> This object is deprecated since API version 9. You are advised to use [ResultCodeV9](#resultcodev99). +Enumerates the authentication result codes. -Enumerates the operation results. +> **NOTE**
+> This object is deprecated since API version 9. You are advised to use [UserAuthResultCode](#userauthresultcode9). **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------- | ------ | -------------------- | | SUCCESS | 0 | The operation is successful. | -| FAIL | 1 | The operation failed. | -| GENERAL_ERROR | 2 | A common operation error occurred. | -| CANCELED | 3 | The operation is canceled. | -| TIMEOUT | 4 | The operation timed out. | +| FAIL | 1 | The authentication failed. | +| GENERAL_ERROR | 2 | A general operation error occurred. | +| CANCELED | 3 | The authentication is canceled. | +| TIMEOUT | 4 | The authentication timed out. | | TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | | BUSY | 7 | Indicates the busy state. | +| INVALID_PARAMETERS | 8 | Invalid parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | | NOT_ENROLLED | 10 | The user has not entered the authentication information.| - ## FaceTips8+ Enumerates the tip codes used during the facial authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------------- | ------ | ------------------------------------ | | FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. | | FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. | @@ -934,7 +840,7 @@ Enumerates the tip codes used during the fingerprint authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------------------- | ------ | -------------------------------------------------- | | FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | | FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| @@ -950,7 +856,7 @@ Enumerates the identity authentication types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------- | ------ | ---------- | | FACE | 2 | Facial authentication.| | FINGERPRINT | 4 | Fingerprint authentication.| @@ -961,7 +867,7 @@ Enumerates the trust levels of the authentication result. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name| Default Value| Description | +| Name| Value | Description | | ---- | ------ | ------------------------- | | ATL1 | 10000 | Trust level 1.| | ATL2 | 20000 | Trust level 2.| @@ -972,18 +878,18 @@ Enumerates the trust levels of the authentication result. getAuthenticator(): Authenticator +Obtains an **Authenticator** instance for user authentication. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [constructor](#constructordeprecated). -Obtains an **Authenticator** object for user authentication. - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** | Type | Description | | ----------------------------------------- | ------------ | -| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| +| [Authenticator](#authenticatordeprecated) | **Authenticator** instance obtained.| **Example** ```js @@ -992,61 +898,61 @@ Obtains an **Authenticator** object for user authentication. ## Authenticator(deprecated) +Defines the **Authenticator** object. + > **NOTE**
> This object is deprecated since API version 8. You are advised to use [UserAuth](#userauth8). -Provides methods to manage an **Authenticator** object. - - ### execute(deprecated) execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void +Performs user authentication. This API uses asynchronous callback to return the result. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses asynchronous callback to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------- | | type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| -| callback | AsyncCallback<number> | No | Callback used to return the result. | +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | - Parameters returned in callback +Parameters returned in callback | Type | Description | | ------ | ------------------------------------------------------------ | | number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ - if (code === userIAM_userAuth.ResultCode.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); - }); - ``` + +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { + console.info("auth success"); + return; + } + console.error("auth fail, code = " + code); +}); +``` ### execute(deprecated) -execute(type:AuthType, level:SecureLevel): Promise<number> +execute(type : AuthType, level : SecureLevel): Promise<number> + +Performs user authentication. This API uses a promise to return the result. > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses a promise to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -1066,25 +972,25 @@ Performs user authentication. This API uses a promise to return the result. **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - }).catch((error)=>{ - console.error("auth fail, code = " + error); - }); - ``` +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); +}).catch((error)=>{ + console.error("auth fail, code = " + error); +}); +``` ## AuthenticationResult(deprecated) +Enumerates the authentication results. + > **NOTE**
> This object is discarded since API version 8. You are advised to use [ResultCode](#resultcodedeprecated). -Enumerates the authentication results. - **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | -------------------------- | | NO_SUPPORT | -1 | The device does not support the current authentication mode.| | SUCCESS | 0 | The authentication is successful. | diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 8897b51f07b4e00feae752e792820e6b9b32370f..f4193680d4d0732a38ab9564bbd67428c7a3497a 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,6 +1,6 @@ -# @ohos.util +# @ohos.util (util) -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. +The **util** module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. > **NOTE** > @@ -41,38 +41,6 @@ let res = util.format("%s", "hello world!"); console.log(res); ``` -## util.printf(deprecated) - -printf(format: string, ...args: Object[]): string - -Formats the specified values and inserts them into the string by replacing the wildcard in the string. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| 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.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | String containing the formatted values.| - -**Example** - - ```js - let res = util.printf("%s", "hello world!"); - console.log(res); - ``` - ## util.errnoToString9+ errnoToString(errno: number): string @@ -96,43 +64,11 @@ Obtains detailed information about a system error code. **Example** ```js -let errnum = 10; // 10 is a system error code. +let errnum = -1; // -1 is a system error code. let result = util.errnoToString(errnum); console.log("result = " + result); ``` -## util.getErrorString(deprecated) - -getErrorString(errno: number): string - -Obtains detailed information about a system error code. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errno | number | Yes| Error code generated.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Detailed information about the error code.| - -**Example** - - ```js - let errnum = 10; // 10 is a system error code. - let result = util.getErrorString(errnum); - console.log("result = " + result); - ``` - ## util.callbackWrapper callbackWrapper(original: Function): (err: Object, value: Object )=>void @@ -203,30 +139,6 @@ Processes an asynchronous function and returns a promise. }) ``` -## util.promiseWrapper(deprecated) - -promiseWrapper(original: (err: Object, value: Object) => void): Object - -Processes an asynchronous function and returns a promise. - -> **NOTE** -> -> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| original | Function | Yes| Asynchronous function.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| - ## util.randomUUID9+ randomUUID(entropyCache?: boolean): string @@ -314,6 +226,96 @@ Parses a UUID from a string, as described in RFC 4122 version 4. // 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156 ``` +## util.printf(deprecated) + +printf(format: string, ...args: Object[]): string + +Formats the specified values and inserts them into the string by replacing the wildcard in the string. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| 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.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | String containing the formatted values.| + +**Example** + + ```js + let res = util.printf("%s", "hello world!"); + console.log(res); + ``` + + +## util.getErrorString(deprecated) + +getErrorString(errno: number): string + +Obtains detailed information about a system error code. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errno | number | Yes| Error code generated.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Detailed information about the error code.| + +**Example** + + ```js + let errnum = -1; // -1 is a system error code. + let result = util.getErrorString(errnum); + console.log("result = " + result); + ``` + +## util.promiseWrapper(deprecated) + +promiseWrapper(original: (err: Object, value: Object) => void): Object + +Processes an asynchronous function and returns a promise. + +> **NOTE** +> +> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| original | Function | Yes| Asynchronous function.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| + + ## TextDecoder ### Attributes @@ -336,7 +338,7 @@ A constructor used to create a **TextDecoder** object. ### create9+ -create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): TextDecoder; +create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean }): TextDecoder; Creates a **TextDecoder** object. It provides the same function as the deprecated argument constructor. @@ -363,41 +365,9 @@ let textDecoder = new util.TextDecoder() textDecoder.create('utf-8', { ignoreBOM : true }); ``` -### constructor(deprecated) - -constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) - -A constructor used to create a **TextDecoder** object. - -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| encoding | string | No| Encoding format.| -| options | Object | No| Encoding-related options, which include **fatal** and **ignoreBOM**.| - - **Table 1** options - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| fatal | boolean | No| Whether to display fatal errors.| -| ignoreBOM | boolean | No| Whether to ignore the BOM.| - -**Example** - - ```js - let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); - ``` - -### decode +### decodeWithStream9+ -decode(input: Uint8Array, options?: { stream?: false }): string +decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string Decodes the input content. @@ -414,7 +384,7 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| +| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| **Return value** @@ -434,17 +404,52 @@ Decodes the input content. result[4] = 0x62; result[5] = 0x63; console.log("input num:"); - let retStr = textDecoder.decode( result , {stream: false}); + let retStr = textDecoder.decodeWithStream( result , {stream: false}); console.log("retStr = " + retStr); ``` +### constructor(deprecated) -### decodeWithStream9+ +constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean }) -decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string +A constructor used to create a **TextDecoder** object. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [create9+](#create9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| encoding | string | No| Encoding format.| +| options | Object | No| Encoding-related options, which include **fatal** and **ignoreBOM**.| + + **Table 1** options + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fatal | boolean | No| Whether to display fatal errors.| +| ignoreBOM | boolean | No| Whether to ignore the BOM.| + +**Example** + + ```js + let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); + ``` + +### decode(deprecated) + +decode(input: Uint8Array, options?: { stream?: false }): string Decodes the input content. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [decodeWithStream9+](#decodewithstream9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -458,7 +463,7 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| +| stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| **Return value** @@ -478,11 +483,10 @@ Decodes the input content. result[4] = 0x62; result[5] = 0x63; console.log("input num:"); - let retStr = textDecoder.decodeWithStream( result , {stream: false}); + let retStr = textDecoder.decode( result , {stream: false}); console.log("retStr = " + retStr); ``` - ## TextEncoder ### Attributes @@ -493,7 +497,6 @@ Decodes the input content. | -------- | -------- | -------- | -------- | -------- | | encoding | string | Yes| No| Encoding format. The default format is **utf-8**.| - ### constructor constructor() @@ -508,65 +511,53 @@ A constructor used to create a **TextEncoder** object. let textEncoder = new util.TextEncoder(); ``` -### encodeInto9+ +### constructor9+ -encodeInto(input?: string): Uint8Array +constructor(encoding?: string) -Encodes the input content. +A constructor used to create a **TextEncoder** object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| input | string | No | String to encode.| - -**Return value** - -| Type | Description | -| ---------- | ------------------ | -| Uint8Array | Encoded text.| +| Name| Type| Mandatory| Description| +| ----- | ---- | ---- | ---- | +| encoding | string | No| Encoding format.| **Example** ```js -let textEncoder = new util.TextEncoder(); -let buffer = new ArrayBuffer(20); -let result = new Uint8Array(buffer); -result = textEncoder.encodeInto("\uD800¥¥"); + let textEncoder = new util.TextEncoder("utf-8"); ``` -### encode(deprecated) +### encodeInto9+ -encode(input?: string): Uint8Array +encodeInto(input?: string): Uint8Array Encodes the input content. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. - **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| input | string | No| String to encode.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| input | string | No | String to encode.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ---------- | ------------------ | | Uint8Array | Encoded text.| **Example** + ```js - let textEncoder = new util.TextEncoder(); - let buffer = new ArrayBuffer(20); - let result = new Uint8Array(buffer); - result = textEncoder.encode("\uD800¥¥"); +let textEncoder = new util.TextEncoder(); +let buffer = new ArrayBuffer(20); +let result = new Uint8Array(buffer); +result = textEncoder.encodeInto("\uD800¥¥"); ``` ### encodeIntoUint8Array9+ @@ -597,7 +588,7 @@ let that = new util.TextEncoder() let buffer = new ArrayBuffer(4) let dest = new Uint8Array(buffer) let result = new Object() -result = that.encodeInto('abcd', dest) +result = that.encodeIntoUint8Array('abcd', dest) ``` ### encodeInto(deprecated) @@ -634,6 +625,38 @@ Stores the UTF-8 encoded text. result = that.encodeInto('abcd', dest) ``` +### encode(deprecated) + +encode(input?: string): Uint8Array + +Encodes the input content. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| input | string | No| String to encode.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Uint8Array | Encoded text.| + +**Example** + ```js + let textEncoder = new util.TextEncoder(); + let buffer = new ArrayBuffer(20); + let result = new Uint8Array(buffer); + result = textEncoder.encode("\uD800¥¥"); + ``` + ## RationalNumber8+ ### constructor9+ @@ -671,31 +694,6 @@ Parses a rational number. Previously, this processing is an internal action of t let rationalNumber = util.RationalNumber.parseRationalNumber(1,2) ``` -### constructor(deprecated) - -constructor(numerator: number,denominator: number) - -A constructor used to create a **RationalNumber** object. - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| numerator | number | Yes| Numerator, which is an integer.| -| denominator | number | Yes| Denominator, which is an integer.| - -**Example** - -```js -let rationalNumber = new util.RationalNumber(1,2); -``` - ### createRationalFromString8+ static createRationalFromString​(rationalString: string): RationalNumber​ @@ -751,38 +749,6 @@ let rational = util.RationalNumber.createRationalFromString("3/4"); let result = rationalNumber.compare(rational); ``` -### compareTo(deprecated) - -compareTo​(another: RationalNumber): number​ - -Compares this **RationalNumber** object with a given object. - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| - -**Example** - -```js -let rationalNumber = new util.RationalNumber(1,2); -let rational = util.RationalNumber.createRationalFromString("3/4"); -let result = rationalNumber.compareTo(rational); -``` - ### valueOf8+ valueOf(): number @@ -860,38 +826,6 @@ let rationalNumber = new util.RationalNumber(1,2); let result = util.RationalNumber.getCommonFactor(4,6); ``` -### getCommonDivisor(deprecated) - -static getCommonDivisor​(number1: number,number2: number): number - -Obtains the greatest common divisor of two specified integers. - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| number1 | number | Yes| The first integer used to get the greatest common divisor.| -| number2 | number | Yes| The second integer used to get the greatest common divisor.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Greatest common divisor obtained.| - -**Example** - -```js -let rationalNumber = new util.RationalNumber(1,2); -let result = util.RationalNumber.getCommonDivisor(4,6); -``` - ### getNumerator8+ getNumerator​(): number @@ -1018,6 +952,94 @@ let rationalNumber = new util.RationalNumber(1,2); let result = rationalNumber.toString(); ``` +### constructor(deprecated) + +constructor(numerator: number,denominator: number) + +A constructor used to create a **RationalNumber** object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| numerator | number | Yes| Numerator, which is an integer.| +| denominator | number | Yes| Denominator, which is an integer.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +``` + +### compareTo(deprecated) + +compareTo​(another: RationalNumber): number​ + +Compares this **RationalNumber** object with a given object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compareTo(rational); +``` + +### getCommonDivisor(deprecated) + +static getCommonDivisor​(number1: number,number2: number): number + +Obtains the greatest common divisor of two specified integers. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| number1 | number | Yes| The first integer used to get the greatest common divisor.| +| number2 | number | Yes| The second integer used to get the greatest common divisor.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Greatest common divisor obtained.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonDivisor(4,6); +``` ## LRUCache9+ @@ -1464,7 +1486,7 @@ lru.afterRemoval(false,10,30,null); ### contains9+ -contains(key: object): boolean +contains(key: K): boolean Checks whether this cache contains the specified key. @@ -1474,7 +1496,7 @@ Checks whether this cache contains the specified key. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| key | object | Yes | Key to check.| +| key | K | Yes | Key to check.| **Return value** @@ -1564,1026 +1586,1014 @@ pro.put(2,10); let result = pro[Symbol.iterator](); ``` -## LruBuffer(deprecated) - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. +## ScopeComparable8+ -### Attributes +The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Total number of values in this buffer.| +### compareTo8+ -**Example** +compareTo(other: ScopeComparable): boolean; - ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(1,8); - let result = pro.length; - ``` +Compares two values and returns a Boolean value. -### constructor(deprecated) +**System capability**: SystemCapability.Utils.Lang -constructor(capacity?: number) +**Parameters** -A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| other | [ScopeComparable](#scopecomparable8) | Yes | The other value to be compared with the current value.| -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +**Return value** -**System capability**: SystemCapability.Utils.Lang +| Type| Description | +| ---- | ------------------ | +| boolean | If the current value is greater than or equal to the input value, **true** is returned. Otherwise, **false** is returned.| -**Parameters** +**Example** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| capacity | number | No| Capacity of the **LruBuffer** to create.| +Create a class to implement the **compareTo** method. The **Temperature** class is used as an example in the following sample code. -**Example** +```js +class Temperature{ + constructor(value){ + // If TS is used for development, add the following code: + // private readonly _temp: Temperature; + this._temp = value; + } + compareTo(value){ + return this._temp >= value.getTemp(); + } + getTemp(){ + return this._temp; + } + toString(){ + return this._temp.toString(); + } +} +``` - ```js - let lrubuffer= new util.LruBuffer(); - ``` +## ScopeType8+ -### updateCapacity(deprecated) +Defines the type of values in a **Scope** object. -updateCapacity(newCapacity: number): void +**System capability**: SystemCapability.Utils.Lang -Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +| Type| Description| +| -------- | -------- | +| number | The value type is a number.| +| [ScopeComparable](#scopecomparable8) | The value type is ScopeComparable.| -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. +## ScopeHelper9+ + +### constructor9+ + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +A constructor used to create a **ScopeHelper** object with the specified upper and lower limits. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| newCapacity | number | Yes| New capacity of the **LruBuffer**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit of the **Scope** object.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit of the **Scope** object.| **Example** ```js - let pro = new util.LruBuffer(); - let result = pro.updateCapacity(100); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); ``` -### toString(deprecated) -toString(): string +### toString9+ -Obtains the string representation of this **LruBuffer** object. +toString(): string -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +Obtains a string representation that contains this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| string | String representation of this **LruBuffer** object.| +| Type | Description | +| ------ | -------------------------------------- | +| string | String representation containing the **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - pro.remove(20); - let result = pro.toString(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.toString(); ``` -### getCapacity(deprecated) -getCapacity(): number +### intersect9+ -Obtains the capacity of this buffer. +intersect(range: ScopeHelper): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. +Obtains the intersection of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Capacity of this buffer.| +| Type | Description | +| ------------------------------ | ------------------------------ | +| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - let result = pro.getCapacity(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +range.intersect(rangeFir); ``` -### clear(deprecated) -clear(): void +### intersect9+ -Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. +Obtains the intersection of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------------------------------------- | +| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| + **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.length; - pro.clear(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.intersect(tempMiDF, tempMidS); ``` -### getCreateCount(deprecated) -getCreateCount(): number +### getUpper9+ -Obtains the number of return values for **createDefault()**. +getUpper(): ScopeType -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. +Obtains the upper limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of return values for **createDefault()**.| +| Type | Description | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(1,8); - let result = pro.getCreateCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getUpper(); ``` -### getMissCount(deprecated) -getMissCount(): number +### getLower9+ -Obtains the number of times that the queried values are mismatched. +getLower(): ScopeType -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. +Obtains the lower limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of times that the queried values are mismatched.| +| Type | Description | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMissCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getLower(); ``` -### getRemovalCount(deprecated) -getRemovalCount(): number +### expand9+ -Obtains the number of removals from this buffer. +expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. +Obtains the union set of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of removals from the buffer.| +| Type | Description | +| ---------------------------- | ------------------------------------ | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.updateCapacity(2); - pro.put(50,22); - let result = pro.getRemovalCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF, tempMidS); ``` -### getMatchCount(deprecated) -getMatchCount(): number +### expand9+ -Obtains the number of times that the queried values are matched. +expand(range: ScopeHelper): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. +Obtains the union set of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of times that the queried values are matched.| +| Type | Description | +| ---------------------------- | ---------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMatchCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +let result = range.expand(rangeFir); ``` -### getPutCount(deprecated) -getPutCount(): number +### expand9+ -Obtains the number of additions to this buffer. +expand(value: ScopeType): ScopeHelper -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. +Obtains the union set of this **Scope** and the given value. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of additions to the buffer.| +| Type | Description | +| ---------------------------- | -------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.getPutCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF); ``` -### isEmpty(deprecated) -isEmpty(): boolean +### contains9+ -Checks whether this buffer is empty. +contains(value: ScopeType): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. +Checks whether a value is within this **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the buffer does not contain any value.| +| Type | Description | +| ------- | --------------------------------------------------- | +| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.isEmpty(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +range.contains(tempMiDF); ``` -### get(deprecated) -get(key: K): V | undefined +### contains9+ -Obtains the value of the specified key. +contains(range: ScopeHelper): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. +Checks whether a range is within this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key based on which the value is queried.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** -| Type| Description| -| -------- | -------- | -| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| Type | Description | +| ------- | ----------------------------------------------------- | +| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.get(2); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempLess = new Temperature(20); +let tempMore = new Temperature(45); +let rangeSec = new util.ScopeHelper(tempLess, tempMore); +let result = range.contains(rangeSec); ``` -### put(deprecated) -put(key: K,value: V): V +### clamp9+ -Adds a key-value pair to this buffer. +clamp(value: ScopeType): ScopeType -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. +Limits a value to this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the key-value pair to add.| -| value | V | Yes| Value of the key-value pair to add.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | -------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| **Return value** -| Type| Description| -| -------- | -------- | -| V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | +| Type | Description | +| ------------------------ | ------------------------------------------------------------ | +| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** ```js - let pro = new util.LruBuffer(); - let result = pro.put(2,10); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.clamp(tempMiDF); ``` -### values(deprecated) +## Base64Helper9+ -values(): V[] +### constructor9+ -Obtains all values in this buffer, listed from the most to the least recently accessed. +constructor() -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. +A constructor used to create a **Base64Helper** instance. **System capability**: SystemCapability.Utils.Lang +**Example** + + ```js +let base64 = new util.Base64Helper(); + ``` + +### encodeSync9+ + +encodeSync(src: Uint8Array): Uint8Array + +Encodes the input content. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | Yes | Uint8Array to encode.| + **Return value** -| Type| Description| -| -------- | -------- | -| V [] | All values in the buffer, listed from the most to the least recently accessed.| +| Type | Description | +| ---------- | ----------------------------- | +| Uint8Array | Uint8Array encoded.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(2,"anhu"); - pro.put("afaf","grfb"); - let result = pro.values(); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeSync(array); ``` -### keys(deprecated) -keys(): K[] +### encodeToStringSync9+ -Obtains all keys in this buffer, listed from the most to the least recently accessed. +encodeToStringSync(src: Uint8Array): string -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. +Encodes the input content. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | Yes | Uint8Array to encode.| + **Return value** -| Type| Description| -| -------- | -------- | -| K [] | All keys in the buffer, listed from the most to the least recently accessed.| +| Type | Description | +| ------ | -------------------- | +| string | String encoded from the Uint8Array.| **Example** - ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.keys(); + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeToStringSync(array); ``` -### remove(deprecated) -remove(key: K): V | undefined +### decodeSync9+ -Removes the specified key and its value from this buffer. +decodeSync(src: Uint8Array | string): Uint8Array -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. +Decodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key to remove.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ----------------------------- | +| src | Uint8Array \| string | Yes | Uint8Array or string to decode.| **Return value** -| Type| Description| -| -------- | -------- | -| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| Type | Description | +| ---------- | ----------------------------- | +| Uint8Array | Uint8Array decoded.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.remove(20); +let that = new util.Base64Helper(); +let buff = 'czEz'; +let result = that.decodeSync(buff); ``` -### afterRemoval(deprecated) -afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void +### encode9+ -Performs subsequent operations after a value is removed. +encode(src: Uint8Array): Promise<Uint8Array> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. +Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| -| key | K | Yes| Key removed.| -| value | V | Yes| Value removed.| -| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| + +**Return value** + +| Type | Description | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** ```js - let arr = []; - class ChildLruBuffer extends util.LruBuffer - { - constructor() - { - super(); - } - afterRemoval(isEvict, key, value, newValue) - { - if (isEvict === false) - { - arr = [key, value, newValue]; - } - } - } - let lru = new ChildLruBuffer(); - lru.afterRemoval(false,10,30,null); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let rarray = new Uint8Array([99,122,69,122]); +that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) ``` -### contains(deprecated) - -contains(key: K): boolean -Checks whether this buffer contains the specified key. +### encodeToString9+ +encodeToString(src: Uint8Array): Promise<string> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key to check.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| +| Type | Description | +| --------------------- | ------------------------ | +| Promise<string> | String obtained after asynchronous encoding.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.contains(20); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +that.encodeToString(array).then(val=>{ + console.log(val) +}) ``` -### createDefault(deprecated) -createDefault(key: K): V +### decode9+ -Creates a value if the value of the specified key is not available. +decode(src: Uint8Array | string): Promise<Uint8Array> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. +Decodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key of which the value is missing.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | --------------------------------- | +| src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| **Return value** -| Type| Description| -| -------- | -------- | -| V | Value of the key.| +| Type | Description | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** ```js - let pro = new util.LruBuffer(); - let result = pro.createDefault(50); +let that = new util.Base64Helper(); +let array = new Uint8Array([99,122,69,122]); +let rarray = new Uint8Array([115,49,51]); +that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) ``` -### entries(deprecated) +## types8+ -entries(): IterableIterator<[K,V]> +### constructor8+ -Obtains a new iterator object that contains all key-value pairs in this object. +constructor() -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. +A constructor used to create a **Types** object. **System capability**: SystemCapability.Utils.Lang -**Return value** - -| Type| Description| -| -------- | -------- | -| [K, V] | Iterable array.| - **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.entries(); + let type = new util.types(); ``` -### [Symbol.iterator](deprecated) -[Symbol.iterator]\(): IterableIterator<[K, V]> +### isAnyArrayBuffer8+ -Obtains a two-dimensional array in key-value pairs. +isAnyArrayBuffer(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. +Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [K, V] | Two-dimensional array in key-value pairs.| +| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro[Symbol.iterator](); + let that = new util.types(); + let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); ``` -### ScopeType8+ - -Defines the type of values in a **Scope** object. The value type can be **ScopeComparable** or **number**. - -The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. - -```js -interface ScopeComparable{ - compareTo(other: ScopeComparable): boolean; -} -type ScopeType = ScopeComparable | number; -``` - - -Create a class to implement the **compareTo** method. In the subsequent sample code, **Temperature** is used as an example of the [ScopeType](#scopetype8) object. - - -Example -```js -class Temperature{ - constructor(value){ - // If TS is used for development, add the following code: - // private readonly _temp: Temperature; - this._temp = value; - } - compareTo(value){ - return this._temp >= value.getTemp(); - } - getTemp(){ - return this._temp; - } - toString(){ - return this._temp.toString(); - } -} -``` -## ScopeHelper9+ +### isArrayBufferView8+ -### constructor9+ +isArrayBufferView(value: Object): boolean -constructor(lowerObj: ScopeType, upperObj: ScopeType) +Checks whether the input value is of the **ArrayBufferView** type. -A constructor used to create a **ScopeHelper** object with the specified upper and lower limits. +**ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit of the **Scope** object.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit of the **Scope** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); + let that = new util.types(); + let result = that.isArrayBufferView(new Int8Array([])); ``` -### toString9+ +### isArgumentsObject8+ -toString(): string +isArgumentsObject(value: Object): boolean -Obtains a string representation that contains this **Scope**. +Checks whether the input value is of the **arguments** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------ | -------------------------------------- | -| string | String representation containing the **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.toString(); + let that = new util.types(); + function foo() { + var result = that.isArgumentsObject(arguments); + } + let f = foo(); ``` -### intersect9+ +### isArrayBuffer8+ -intersect(range: ScopeHelper): ScopeHelper +isArrayBuffer(value: Object): boolean -Obtains the intersection of this **Scope** and the given **Scope**. +Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------- | ---- | ------------------ | -| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | ------------------------------ | -| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); -range.intersect(rangeFir ); + let that = new util.types(); + let result = that.isArrayBuffer(new ArrayBuffer(0)); ``` -### intersect9+ +### isAsyncFunction8+ -intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper +isAsyncFunction(value: Object): boolean -Obtains the intersection of this **Scope** and the given lower and upper limits. +Checks whether the input value is an asynchronous function. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------------------- | -| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.intersect(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isAsyncFunction(async function foo() {}); ``` -### getUpper9+ +### isBooleanObject8+ -getUpper(): ScopeType +isBooleanObject(value: Object): boolean -Obtains the upper limit of this **Scope**. +Checks whether the input value is of the **Boolean** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------------------------ | ---------------------- | -| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.getUpper(); + let that = new util.types(); + let result = that.isBooleanObject(new Boolean(true)); ``` -### getLower9+ +### isBoxedPrimitive8+ -getLower(): ScopeType +isBoxedPrimitive(value: Object): boolean -Obtains the lower limit of this **Scope**. +Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------------------------ | ---------------------- | -| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.getLower(); + let that = new util.types(); + let result = that.isBoxedPrimitive(new Boolean(false)); ``` -### expand9+ +### isDataView8+ -expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper +isDataView(value: Object): boolean -Obtains the union set of this **Scope** and the given lower and upper limits. +Checks whether the input value is of the **DataView** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------------------ | -| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.expand(tempMiDF, tempMidS); + let that = new util.types(); + const ab = new ArrayBuffer(20); + let result = that.isDataView(new DataView(ab)); ``` -### expand9+ +### isDate8+ -expand(range: ScopeHelper): ScopeHelper +isDate(value: Object): boolean -Obtains the union set of this **Scope** and the given **Scope**. +Checks whether the input value is of the **Date** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------- | ---- | ------------------ | -| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------------- | -| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); -let result = range.expand(rangeFir); + let that = new util.types(); + let result = that.isDate(new Date()); ``` -### expand9+ +### isExternal8+ -expand(value: ScopeType): ScopeHelper +isExternal(value: Object): boolean -Obtains the union set of this **Scope** and the given value. +Checks whether the input value is of the **native external** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | ---------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------------------------- | -------------------------------- | -| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.expand(tempMiDF); + let that = new util.types(); + let result = that.isExternal(true); ``` -### contains9+ +### isFloat32Array8+ -contains(value: ScopeType): boolean +isFloat32Array(value: Object): boolean -Checks whether a value is within this **Scope**. +Checks whether the input value is of the **Float32Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | ---------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------- | --------------------------------------------------- | -| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -range.contains(tempMiDF); + let that = new util.types(); + let result = that.isFloat32Array(new Float32Array()); ``` -### contains9+ +### isFloat64Array8+ -contains(range: ScopeHelper): boolean +isFloat64Array(value: Object): boolean -Checks whether a range is within this **Scope**. +Checks whether the input value is of the **Float64Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------- | ---- | ------------------ | -| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------- | ----------------------------------------------------- | -| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let tempLess = new Temperature(20); -let tempMore = new Temperature(45); -let rangeSec = new util.ScopeHelper(tempLess, tempMore); -let result = range.contains(rangeSec); + let that = new util.types(); + let result = that.isFloat64Array(new Float64Array()); ``` -### clamp9+ +### isGeneratorFunction8+ -clamp(value: ScopeType): ScopeType +isGeneratorFunction(value: Object): boolean -Limits a value to this **Scope**. +Checks whether the input value is a generator function. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | -------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------ | ------------------------------------------------------------ | -| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.clamp(tempMiDF); + let that = new util.types(); + let result = that.isGeneratorFunction(function* foo() {}); ``` -## Scope(deprecated) - -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. - -### constructor(deprecated) - -constructor(lowerObj: ScopeType, upperObj: ScopeType) -A constructor used to create a **Scope** object with the specified upper and lower limits. +### isGeneratorObject8+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +isGeneratorObject(value: Object): boolean +Checks whether the input value is a generator object. **System capability**: SystemCapability.Utils.Lang @@ -2591,52 +2601,57 @@ A constructor used to create a **Scope** object with the specified upper and low | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); + let that = new util.types(); + function* foo() {} + const generator = foo(); + let result = that.isGeneratorObject(generator); ``` -### toString(deprecated) -toString(): string +### isInt8Array8+ -Obtains a string representation that contains this **Scope**. +isInt8Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +Checks whether the input value is of the **Int8Array** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| string | String representation containing the **Scope**.| +| boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.toString(); + let that = new util.types(); + let result = that.isInt8Array(new Int8Array([])); ``` -### intersect(deprecated) -intersect(range: Scope): Scope +### isInt16Array8+ -Obtains the intersection of this **Scope** and the given **Scope**. +isInt16Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +Checks whether the input value is of the **Int16Array** type. **System capability**: SystemCapability.Utils.Lang @@ -2644,35 +2659,27 @@ Obtains the intersection of this **Scope** and the given **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given **Scope**.| +| boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let rangeFir = new util.Scope(tempMiDF, tempMidS); - range.intersect(rangeFir ); + let that = new util.types(); + let result = that.isInt16Array(new Int16Array([])); ``` -### intersect(deprecated) -intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope +### isInt32Array8+ -Obtains the intersection of this **Scope** and the given lower and upper limits. +isInt32Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +Checks whether the input value is of the **Int32Array** type. **System capability**: SystemCapability.Utils.Lang @@ -2680,89 +2687,85 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| +| boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let result = range.intersect(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isInt32Array(new Int32Array([])); ``` -### getUpper(deprecated) -getUpper(): ScopeType +### isMap8+ -Obtains the upper limit of this **Scope**. +isMap(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. +Checks whether the input value is of the **Map** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| +| boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.getUpper(); + let that = new util.types(); + let result = that.isMap(new Map()); ``` -### getLower(deprecated) -getLower(): ScopeType +### isMapIterator8+ -Obtains the lower limit of this **Scope**. +isMapIterator(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. +Checks whether the input value is of the **MapIterator** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| +| boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.getLower(); + let that = new util.types(); + const map = new Map(); + let result = that.isMapIterator(map.keys()); ``` -### expand(deprecated) -expand(lowerObj: ScopeType,upperObj: ScopeType): Scope +### isNativeError8+ -Obtains the union set of this **Scope** and the given lower and upper limits. +isNativeError(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +Checks whether the input value is of the **Error** type. **System capability**: SystemCapability.Utils.Lang @@ -2770,35 +2773,27 @@ Obtains the union set of this **Scope** and the given lower and upper limits. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given lower and upper limits.| +| boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let result = range.expand(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isNativeError(new TypeError()); ``` -### expand(deprecated) -expand(range: Scope): Scope +### isNumberObject8+ -Obtains the union set of this **Scope** and the given **Scope**. +isNumberObject(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang @@ -2806,35 +2801,27 @@ Obtains the union set of this **Scope** and the given **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| +| boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let rangeFir = new util.Scope(tempMiDF, tempMidS); - let result = range.expand(rangeFir); + let that = new util.types(); + let result = that.isNumberObject(new Number(0)); ``` -### expand(deprecated) -expand(value: ScopeType): Scope +### isPromise8+ -Obtains the union set of this **Scope** and the given value. +isPromise(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +Checks whether the input value is a promise. **System capability**: SystemCapability.Utils.Lang @@ -2842,33 +2829,27 @@ Obtains the union set of this **Scope** and the given value. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| +| boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - let result = range.expand(tempMiDF); + let that = new util.types(); + let result = that.isPromise(Promise.resolve(1)); ``` -### contains(deprecated) -contains(value: ScopeType): boolean +### isProxy8+ -Checks whether a value is within this **Scope**. +isProxy(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +Checks whether the input value is a proxy. **System capability**: SystemCapability.Utils.Lang @@ -2876,33 +2857,29 @@ Checks whether a value is within this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| +| boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - range.contains(tempMiDF); + let that = new util.types(); + const target = {}; + const proxy = new Proxy(target, {}); + let result = that.isProxy(proxy); ``` -### contains(deprecated) - -contains(range: Scope): boolean -Checks whether a range is within this **Scope**. +### isRegExp8+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +isRegExp(value: Object): boolean + +Checks whether the input value is of the **RegExp** type. **System capability**: SystemCapability.Utils.Lang @@ -2910,36 +2887,27 @@ Checks whether a range is within this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| +| boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let tempLess = new Temperature(20); - let tempMore = new Temperature(45); - let rangeSec = new util.Scope(tempLess, tempMore); - let result = range.contains(rangeSec); + let that = new util.types(); + let result = that.isRegExp(new RegExp('abc')); ``` -### clamp(deprecated) - -clamp(value: ScopeType): ScopeType +### isSet8+ -Limits a value to this **Scope**. +isSet(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. +Checks whether the input value is of the **Set** type. **System capability**: SystemCapability.Utils.Lang @@ -2947,259 +2915,255 @@ Limits a value to this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| +| boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - let result = range.clamp(tempMiDF); + let that = new util.types(); + let result = that.isSet(new Set()); ``` -## Base64Helper9+ -### constructor9+ +### isSetIterator8+ -constructor() +isSetIterator(value: Object): boolean -A constructor used to create a **Base64Helper** instance. +Checks whether the input value is of the **SetIterator** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| + **Example** ```js -let base64 = new util.Base64Helper(); + let that = new util.types(); + const set = new Set(); + let result = that.isSetIterator(set.keys()); ``` -### encodeSync9+ -encodeSync(src: Uint8Array): Uint8Array +### isStringObject8+ -Encodes the input content. +isStringObject(value: Object): boolean + +Checks whether the input value is a string object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------------- | -| src | Uint8Array | Yes | Uint8Array to encode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------- | ----------------------------- | -| Uint8Array | Uint8Array encoded.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeSync(array); + let that = new util.types(); + let result = that.isStringObject(new String('foo')); ``` -### encodeToStringSync9+ +### isSymbolObjec8+ -encodeToStringSync(src: Uint8Array): string +isSymbolObject(value: Object): boolean -Encodes the input content. +Checks whether the input value is a symbol object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------------- | -| src | Uint8Array | Yes | Uint8Array to encode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------ | -------------------- | -| string | String encoded from the Uint8Array.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeToStringSync(array); + let that = new util.types(); + const symbols = Symbol('foo'); + let result = that.isSymbolObject(Object(symbols)); ``` -### decodeSync9+ +### isTypedArray8+ -decodeSync(src: Uint8Array | string): Uint8Array +isTypedArray(value: Object): boolean -Decodes the input content. +Checks whether the input value is of the **TypedArray** type. + +**TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ----------------------------- | -| src | Uint8Array \| string | Yes | Uint8Array or string to decode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------- | ----------------------------- | -| Uint8Array | Uint8Array decoded.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let buff = 'czEz'; -let result = that.decodeSync(buff); + let that = new util.types(); + let result = that.isTypedArray(new Float64Array([])); ``` -### encode9+ +### isUint8Array8+ -encode(src: Uint8Array): Promise<Uint8Array> +isUint8Array(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **Uint8Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ----------------------- | -| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------- | --------------------------------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let rarray = new Uint8Array([99,122,69,122]); -that.encode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } -}) + let that = new util.types(); + let result = that.isUint8Array(new Uint8Array([])); ``` -### encodeToString9+ +### isUint8ClampedArray8+ -encodeToString(src: Uint8Array): Promise<string> +isUint8ClampedArray(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **Uint8ClampedArray** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ----------------------- | -| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| --------------------- | ------------------------ | -| Promise<string> | String obtained after asynchronous encoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -that.encodeToString(array).then(val=>{ - console.log(val) -}) + let that = new util.types(); + let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); ``` -### decode9+ +### isUint16Array8+ -decode(src: Uint8Array | string): Promise<Uint8Array> +isUint16Array(value: Object): boolean -Decodes the input content asynchronously. +Checks whether the input value is of the **Uint16Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | --------------------------------- | -| src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------- | --------------------------------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([99,122,69,122]); -let rarray = new Uint8Array([115,49,51]); -that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } -}) + let that = new util.types(); + let result = that.isUint16Array(new Uint16Array([])); ``` -## Base64(deprecated) +### isUint32Array8+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. +isUint32Array(value: Object): boolean -### constructor(deprecated) +Checks whether the input value is of the **Uint32Array** type. -constructor() +**System capability**: SystemCapability.Utils.Lang -A constructor used to create a **Base64** object. +**Parameters** -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| -**System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| **Example** ```js - let base64 = new util.Base64(); + let that = new util.types(); + let result = that.isUint32Array(new Uint32Array([])); ``` -### encodeSync(deprecated) -encodeSync(src: Uint8Array): Uint8Array +### isWeakMap8+ -Encodes the input content. +isWeakMap(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. +Checks whether the input value is of the **WeakMap** type. **System capability**: SystemCapability.Utils.Lang @@ -3207,31 +3171,27 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Uint8Array | Uint8Array encoded.| +| boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let result = that.encodeSync(array); + let that = new util.types(); + let result = that.isWeakMap(new WeakMap()); ``` -### encodeToStringSync(deprecated) -encodeToStringSync(src: Uint8Array): string +### isWeakSet8+ -Encodes the input content. +isWeakSet(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. +Checks whether the input value is of the **WeakSet** type. **System capability**: SystemCapability.Utils.Lang @@ -3239,31 +3199,27 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| string | String encoded from the Uint8Array.| +| boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let result = that.encodeToStringSync(array); + let that = new util.types(); + let result = that.isWeakSet(new WeakSet()); ``` -### decodeSync(deprecated) -decodeSync(src: Uint8Array | string): Uint8Array +### isBigInt64Array8+ -Decodes the input content. +isBigInt64Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. +Checks whether the input value is of the **BigInt64Array** type. **System capability**: SystemCapability.Utils.Lang @@ -3271,31 +3227,27 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array \| string | Yes| Uint8Array or string to decode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Uint8Array | Uint8Array decoded.| +| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let buff = 'czEz'; - let result = that.decodeSync(buff); + let that = new util.types(); + let result = that.isBigInt64Array(new BigInt64Array([])); ``` -### encode(deprecated) -encode(src: Uint8Array): Promise<Uint8Array> +### isBigUint64Array8+ -Encodes the input content asynchronously. +isBigUint64Array(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. +Checks whether the input value is of the **BigUint64Array** type. **System capability**: SystemCapability.Utils.Lang @@ -3303,36 +3255,27 @@ Encodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| +| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let rarray = new Uint8Array([99,122,69,122]); - that.encode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } - }) + let that = new util.types(); + let result = that.isBigUint64Array(new BigUint64Array([])); ``` -### encodeToString(deprecated) -encodeToString(src: Uint8Array): Promise<string> +### isModuleNamespaceObject8+ -Encodes the input content asynchronously. +isModuleNamespaceObject(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. +Checks whether the input value is a module namespace object. **System capability**: SystemCapability.Utils.Lang @@ -3340,34 +3283,28 @@ Encodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<string> | String obtained after asynchronous encoding.| +| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - that.encodeToString(array).then(val=>{ - console.log(val) - }) + import url from '@ohos.url' + let that = new util.types(); + let result = that.isModuleNamespaceObject(url); ``` -### decode(deprecated) - -decode(src: Uint8Array | string): Promise<Uint8Array> +### isSharedArrayBuffer8+ -Decodes the input content asynchronously. +isSharedArrayBuffer(value: Object): boolean -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. +Checks whether the input value is of the **SharedArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang @@ -3375,50 +3312,53 @@ Decodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| +| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([99,122,69,122]); - let rarray = new Uint8Array([115,49,51]); - that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } - }) + let that = new util.types(); + let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); ``` -## types8+ - - -### constructor8+ +## LruBuffer(deprecated) -constructor() +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. -A constructor used to create a **Types** object. +### Attributes **System capability**: SystemCapability.Utils.Lang +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Total number of values in this buffer.| + **Example** ```js - let type = new util.types(); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(1,8); + let result = pro.length; ``` +### constructor(deprecated) -### isAnyArrayBuffer8+ +constructor(capacity?: number) -isAnyArrayBuffer(value: Object): boolean +A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. -Checks whether the input value is of the **ArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3426,29 +3366,23 @@ Checks whether the input value is of the **ArrayBuffer** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| +| capacity | number | No| Capacity of the **LruBuffer** to create.| **Example** ```js - let that = new util.types(); - let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); + let lrubuffer= new util.LruBuffer(); ``` +### updateCapacity(deprecated) -### isArrayBufferView8+ - -isArrayBufferView(value: Object): boolean +updateCapacity(newCapacity: number): void -Checks whether the input value is of the **ArrayBufferView** type. +Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. -**ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3456,255 +3390,257 @@ Checks whether the input value is of the **ArrayBufferView** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| +| newCapacity | number | Yes| New capacity of the **LruBuffer**.| **Example** ```js - let that = new util.types(); - let result = that.isArrayBufferView(new Int8Array([])); + let pro = new util.LruBuffer(); + let result = pro.updateCapacity(100); ``` +### toString(deprecated) -### isArgumentsObject8+ +toString(): string -isArgumentsObject(value: Object): boolean +Obtains the string representation of this **LruBuffer** object. -Checks whether the input value is of the **arguments** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| +| string | String representation of this **LruBuffer** object.| **Example** ```js - let that = new util.types(); - function foo() { - var result = that.isArgumentsObject(arguments); - } - let f = foo(); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + pro.remove(20); + let result = pro.toString(); ``` +### getCapacity(deprecated) -### isArrayBuffer8+ +getCapacity(): number -isArrayBuffer(value: Object): boolean +Obtains the capacity of this buffer. -Checks whether the input value is of the **ArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| +| number | Capacity of this buffer.| **Example** - ```js - let that = new util.types(); - let result = that.isArrayBuffer(new ArrayBuffer(0)); + let pro = new util.LruBuffer(); + let result = pro.getCapacity(); ``` +### clear(deprecated) -### isAsyncFunction8+ +clear(): void -isAsyncFunction(value: Object): boolean +Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. -Checks whether the input value is an asynchronous function. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** +**Example** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.length; + pro.clear(); + ``` + +### getCreateCount(deprecated) + +getCreateCount(): number + +Obtains the number of return values for **createDefault()**. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. + +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| +| number | Number of return values for **createDefault()**.| **Example** ```js - let that = new util.types(); - let result = that.isAsyncFunction(async function foo() {}); + let pro = new util.LruBuffer(); + pro.put(1,8); + let result = pro.getCreateCount(); ``` +### getMissCount(deprecated) -### isBooleanObject8+ +getMissCount(): number -isBooleanObject(value: Object): boolean +Obtains the number of times that the queried values are mismatched. -Checks whether the input value is of the **Boolean** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| +| number | Number of times that the queried values are mismatched.| **Example** ```js - let that = new util.types(); - let result = that.isBooleanObject(new Boolean(true)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMissCount(); ``` +### getRemovalCount(deprecated) -### isBoxedPrimitive8+ +getRemovalCount(): number -isBoxedPrimitive(value: Object): boolean +Obtains the number of removals from this buffer. -Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| +| number | Number of removals from the buffer.| **Example** ```js - let that = new util.types(); - let result = that.isBoxedPrimitive(new Boolean(false)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.updateCapacity(2); + pro.put(50,22); + let result = pro.getRemovalCount(); ``` +### getMatchCount(deprecated) -### isDataView8+ +getMatchCount(): number -isDataView(value: Object): boolean +Obtains the number of times that the queried values are matched. -Checks whether the input value is of the **DataView** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| +| number | Number of times that the queried values are matched.| **Example** ```js - let that = new util.types(); - const ab = new ArrayBuffer(20); - let result = that.isDataView(new DataView(ab)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMatchCount(); ``` +### getPutCount(deprecated) -### isDate8+ +getPutCount(): number -isDate(value: Object): boolean +Obtains the number of additions to this buffer. -Checks whether the input value is of the **Date** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| +| number | Number of additions to the buffer.| **Example** ```js - let that = new util.types(); - let result = that.isDate(new Date()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.getPutCount(); ``` +### isEmpty(deprecated) -### isExternal8+ +isEmpty(): boolean -isExternal(value: Object): boolean +Checks whether this buffer is empty. -Checks whether the input value is of the **native external** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| +| boolean | Returns **true** if the buffer does not contain any value.| **Example** ```js - let that = new util.types(); - let result = that.isExternal(true); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.isEmpty(); ``` +### get(deprecated) -### isFloat32Array8+ +get(key: K): V | undefined -isFloat32Array(value: Object): boolean +Obtains the value of the specified key. -Checks whether the input value is of the **Float32Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3712,27 +3648,31 @@ Checks whether the input value is of the **Float32Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key based on which the value is queried.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isFloat32Array(new Float32Array()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.get(2); ``` +### put(deprecated) -### isFloat64Array8+ +put(key: K,value: V): V -isFloat64Array(value: Object): boolean +Adds a key-value pair to this buffer. -Checks whether the input value is of the **Float64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3740,85 +3680,84 @@ Checks whether the input value is of the **Float64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key of the key-value pair to add.| +| value | V | Yes| Value of the key-value pair to add.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| +| V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | **Example** ```js - let that = new util.types(); - let result = that.isFloat64Array(new Float64Array()); + let pro = new util.LruBuffer(); + let result = pro.put(2,10); ``` +### values(deprecated) -### isGeneratorFunction8+ +values(): V[] -isGeneratorFunction(value: Object): boolean +Obtains all values in this buffer, listed from the most to the least recently accessed. -Checks whether the input value is a generator function. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| +| V [] | All values in the buffer, listed from the most to the least recently accessed.| **Example** ```js - let that = new util.types(); - let result = that.isGeneratorFunction(function* foo() {}); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(2,"anhu"); + pro.put("afaf","grfb"); + let result = pro.values(); ``` +### keys(deprecated) -### isGeneratorObject8+ +keys(): K[] -isGeneratorObject(value: Object): boolean +Obtains all keys in this buffer, listed from the most to the least recently accessed. -Checks whether the input value is a generator object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| +| K [] | All keys in the buffer, listed from the most to the least recently accessed.| **Example** - ```js - let that = new util.types(); - function* foo() {} - const generator = foo(); - let result = that.isGeneratorObject(generator); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.keys(); ``` +### remove(deprecated) -### isInt8Array8+ +remove(key: K): V | undefined -isInt8Array(value: Object): boolean +Removes the specified key and its value from this buffer. -Checks whether the input value is of the **Int8Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3826,27 +3765,30 @@ Checks whether the input value is of the **Int8Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key to remove.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** - ```js - let that = new util.types(); - let result = that.isInt8Array(new Int8Array([])); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.remove(20); ``` +### afterRemoval(deprecated) -### isInt16Array8+ +afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void -isInt16Array(value: Object): boolean +Performs subsequent operations after a value is removed. -Checks whether the input value is of the **Int16Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3854,27 +3796,43 @@ Checks whether the input value is of the **Int16Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| +| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| +| key | K | Yes| Key removed.| +| value | V | Yes| Value removed.| +| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** ```js - let that = new util.types(); - let result = that.isInt16Array(new Int16Array([])); + let arr = []; + class ChildLruBuffer extends util.LruBuffer + { + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } + } + let lru = new ChildLruBuffer(); + lru.afterRemoval(false,10,30,null); ``` +### contains(deprecated) -### isInt32Array8+ +contains(key: K): boolean -isInt32Array(value: Object): boolean +Checks whether this buffer contains the specified key. -Checks whether the input value is of the **Int32Array** type. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3882,27 +3840,31 @@ Checks whether the input value is of the **Int32Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| +| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isInt32Array(new Int32Array([])); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.contains(20); ``` +### createDefault(deprecated) -### isMap8+ +createDefault(key: K): V -isMap(value: Object): boolean +Creates a value if the value of the specified key is not available. -Checks whether the input value is of the **Map** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3910,85 +3872,89 @@ Checks whether the input value is of the **Map** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key of which the value is missing.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| +| V | Value of the key.| **Example** ```js - let that = new util.types(); - let result = that.isMap(new Map()); + let pro = new util.LruBuffer(); + let result = pro.createDefault(50); ``` +### entries(deprecated) -### isMapIterator8+ +entries(): IterableIterator<[K,V]> -isMapIterator(value: Object): boolean +Obtains a new iterator object that contains all key-value pairs in this object. -Checks whether the input value is of the **MapIterator** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| +| [K, V] | Iterable array.| **Example** ```js - let that = new util.types(); - const map = new Map(); - let result = that.isMapIterator(map.keys()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.entries(); ``` +### [Symbol.iterator](deprecated) -### isNativeError8+ +[Symbol.iterator]\(): IterableIterator<[K, V]> -isNativeError(value: Object): boolean +Obtains a two-dimensional array in key-value pairs. -Checks whether the input value is of the **Error** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| +| [K, V] | Two-dimensional array in key-value pairs.| **Example** ```js - let that = new util.types(); - let result = that.isNativeError(new TypeError()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro[Symbol.iterator](); ``` +## Scope(deprecated) -### isNumberObject8+ +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. -isNumberObject(value: Object): boolean +### constructor(deprecated) + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +A constructor used to create a **Scope** object with the specified upper and lower limits. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. -Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang @@ -3996,55 +3962,52 @@ Checks whether the input value is a number object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| **Example** - ```js - let that = new util.types(); - let result = that.isNumberObject(new Number(0)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); ``` +### toString(deprecated) -### isPromise8+ +toString(): string -isPromise(value: Object): boolean +Obtains a string representation that contains this **Scope**. -Checks whether the input value is a promise. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| +| string | String representation containing the **Scope**.| **Example** ```js - let that = new util.types(); - let result = that.isPromise(Promise.resolve(1)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.toString(); ``` +### intersect(deprecated) -### isProxy8+ +intersect(range: Scope): Scope -isProxy(value: Object): boolean +Obtains the intersection of this **Scope** and the given **Scope**. -Checks whether the input value is a proxy. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4052,29 +4015,35 @@ Checks whether the input value is a proxy. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given **Scope**.| **Example** ```js - let that = new util.types(); - const target = {}; - const proxy = new Proxy(target, {}); - let result = that.isProxy(proxy); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + range.intersect(rangeFir ); ``` +### intersect(deprecated) -### isRegExp8+ +intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope -isRegExp(value: Object): boolean +Obtains the intersection of this **Scope** and the given lower and upper limits. -Checks whether the input value is of the **RegExp** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4082,84 +4051,89 @@ Checks whether the input value is of the **RegExp** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| **Example** ```js - let that = new util.types(); - let result = that.isRegExp(new RegExp('abc')); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.intersect(tempMiDF, tempMidS); ``` +### getUpper(deprecated) -### isSet8+ +getUpper(): ScopeType -isSet(value: Object): boolean +Obtains the upper limit of this **Scope**. -Checks whether the input value is of the **Set** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** ```js - let that = new util.types(); - let result = that.isSet(new Set()); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getUpper(); ``` +### getLower(deprecated) -### isSetIterator8+ +getLower(): ScopeType -isSetIterator(value: Object): boolean +Obtains the lower limit of this **Scope**. -Checks whether the input value is of the **SetIterator** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** ```js - let that = new util.types(); - const set = new Set(); - let result = that.isSetIterator(set.keys()); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getLower(); ``` +### expand(deprecated) -### isStringObject8+ +expand(lowerObj: ScopeType,upperObj: ScopeType): Scope -isStringObject(value: Object): boolean +Obtains the union set of this **Scope** and the given lower and upper limits. -Checks whether the input value is a string object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4167,27 +4141,35 @@ Checks whether the input value is a string object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given lower and upper limits.| **Example** ```js - let that = new util.types(); - let result = that.isStringObject(new String('foo')); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF, tempMidS); ``` +### expand(deprecated) -### isSymbolObjec8+ +expand(range: Scope): Scope -isSymbolObject(value: Object): boolean +Obtains the union set of this **Scope** and the given **Scope**. -Checks whether the input value is a symbol object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4195,30 +4177,35 @@ Checks whether the input value is a symbol object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| **Example** ```js - let that = new util.types(); - const symbols = Symbol('foo'); - let result = that.isSymbolObject(Object(symbols)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + let result = range.expand(rangeFir); ``` +### expand(deprecated) -### isTypedArray8+ - -isTypedArray(value: Object): boolean +expand(value: ScopeType): Scope -Checks whether the input value is of the **TypedArray** type. +Obtains the union set of this **Scope** and the given value. -**TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4226,27 +4213,33 @@ Checks whether the input value is of the **TypedArray** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| **Example** ```js - let that = new util.types(); - let result = that.isTypedArray(new Float64Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF); ``` +### contains(deprecated) -### isUint8Array8+ +contains(value: ScopeType): boolean -isUint8Array(value: Object): boolean +Checks whether a value is within this **Scope**. -Checks whether the input value is of the **Uint8Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4254,27 +4247,33 @@ Checks whether the input value is of the **Uint8Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| +| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isUint8Array(new Uint8Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + range.contains(tempMiDF); ``` +### contains(deprecated) -### isUint8ClampedArray8+ +contains(range: Scope): boolean -isUint8ClampedArray(value: Object): boolean +Checks whether a range is within this **Scope**. -Checks whether the input value is of the **Uint8ClampedArray** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4282,27 +4281,36 @@ Checks whether the input value is of the **Uint8ClampedArray** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| +| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** ```js - let that = new util.types(); - let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempLess = new Temperature(20); + let tempMore = new Temperature(45); + let rangeSec = new util.Scope(tempLess, tempMore); + let result = range.contains(rangeSec); ``` +### clamp(deprecated) -### isUint16Array8+ -isUint16Array(value: Object): boolean +clamp(value: ScopeType): ScopeType -Checks whether the input value is of the **Uint16Array** type. +Limits a value to this **Scope**. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4310,55 +4318,58 @@ Checks whether the input value is of the **Uint16Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** ```js - let that = new util.types(); - let result = that.isUint16Array(new Uint16Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.clamp(tempMiDF); ``` -### isUint32Array8+ - -isUint32Array(value: Object): boolean +## Base64(deprecated) -Checks whether the input value is of the **Uint32Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. -**System capability**: SystemCapability.Utils.Lang +### constructor(deprecated) -**Parameters** +constructor() -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +A constructor used to create a **Base64** object. -**Return value** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| +**System capability**: SystemCapability.Utils.Lang **Example** ```js - let that = new util.types(); - let result = that.isUint32Array(new Uint32Array([])); + let base64 = new util.Base64(); ``` +### encodeSync(deprecated) -### isWeakMap8+ +encodeSync(src: Uint8Array): Uint8Array -isWeakMap(value: Object): boolean +Encodes the input content. -Checks whether the input value is of the **WeakMap** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4366,27 +4377,31 @@ Checks whether the input value is of the **WeakMap** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| +| Uint8Array | Uint8Array encoded.| **Example** ```js - let that = new util.types(); - let result = that.isWeakMap(new WeakMap()); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeSync(array); ``` +### encodeToStringSync(deprecated) -### isWeakSet8+ +encodeToStringSync(src: Uint8Array): string -isWeakSet(value: Object): boolean +Encodes the input content. -Checks whether the input value is of the **WeakSet** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4394,27 +4409,31 @@ Checks whether the input value is of the **WeakSet** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| +| string | String encoded from the Uint8Array.| **Example** ```js - let that = new util.types(); - let result = that.isWeakSet(new WeakSet()); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeToStringSync(array); ``` +### decodeSync(deprecated) -### isBigInt64Array8+ +decodeSync(src: Uint8Array | string): Uint8Array -isBigInt64Array(value: Object): boolean +Decodes the input content. -Checks whether the input value is of the **BigInt64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4422,27 +4441,31 @@ Checks whether the input value is of the **BigInt64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array \| string | Yes| Uint8Array or string to decode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| +| Uint8Array | Uint8Array decoded.| **Example** ```js - let that = new util.types(); - let result = that.isBigInt64Array(new BigInt64Array([])); + let that = new util.Base64(); + let buff = 'czEz'; + let result = that.decodeSync(buff); ``` +### encode(deprecated) -### isBigUint64Array8+ +encode(src: Uint8Array): Promise<Uint8Array> -isBigUint64Array(value: Object): boolean +Encodes the input content asynchronously. -Checks whether the input value is of the **BigUint64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4450,27 +4473,36 @@ Checks whether the input value is of the **BigUint64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| +| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** ```js - let that = new util.types(); - let result = that.isBigUint64Array(new BigUint64Array([])); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let rarray = new Uint8Array([99,122,69,122]); + that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } + }) ``` +### encodeToString(deprecated) -### isModuleNamespaceObject8+ +encodeToString(src: Uint8Array): Promise<string> -isModuleNamespaceObject(value: Object): boolean +Encodes the input content asynchronously. -Checks whether the input value is a module namespace object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4478,28 +4510,34 @@ Checks whether the input value is a module namespace object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| +| Promise<string> | String obtained after asynchronous encoding.| **Example** ```js - import url from '@ohos.url' - let that = new util.types(); - let result = that.isModuleNamespaceObject(url); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + that.encodeToString(array).then(val=>{ + console.log(val) + }) ``` +### decode(deprecated) + -### isSharedArrayBuffer8+ +decode(src: Uint8Array | string): Promise<Uint8Array> -isSharedArrayBuffer(value: Object): boolean +Decodes the input content asynchronously. -Checks whether the input value is of the **SharedArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4507,18 +4545,25 @@ Checks whether the input value is of the **SharedArrayBuffer** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| +| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** ```js - let that = new util.types(); - let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); + let that = new util.Base64(); + let array = new Uint8Array([99,122,69,122]); + let rarray = new Uint8Array([115,49,51]); + that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } + }) ``` + diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index cff7eed5a375d77355bf7f20d26b497bff57d7a9..f99f74149b06752ec0d1edf51ba5c46e40e3e43e 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -1,4 +1,4 @@ -# Vibrator +# @ohos.vibrator (Vibrator) The **vibrator** module provides APIs for starting or stopping vibration. diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index 79cbf5db12746acc8e18d293c03fe3aa48bdc86a..e6af2c7d1c7a12aa67c491fb468b7d81555c917b 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -1,11 +1,10 @@ -# Volume Management +# @ohos.volumeManager (Volume 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**
+> **NOTE** > > - The initial APIs of this module are supported since API version 9. -> - API version 9 is a canary version for trial use. The APIs of this version may be unstable. > - The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -52,7 +51,7 @@ Asynchronously obtains information about all available volumes. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback: AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| + | callback | AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| **Example** @@ -110,7 +109,7 @@ Asynchronously obtains the available space of the specified volume. This API use | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback: AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| **Example** @@ -167,7 +166,7 @@ Asynchronously unmounts a volume. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback: AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| **Example** @@ -226,7 +225,7 @@ Asynchronously obtains volume information based on the UUID. This API uses a cal | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------- | | uuid | string | Yes | UUID of the volume. | - | callback | callback: AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + | callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| **Example** @@ -285,7 +284,7 @@ Asynchronously obtains volume information based on the volume ID. This API uses | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. | + | callback | AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. | **Example** @@ -347,7 +346,7 @@ Asynchronously sets the volume description based on the UUID. This API uses a ca | ---------- | --------------------------------------- | ---- | ---------------- | | uuid | string | Yes | UUID of the volume. | | description | string | Yes | Volume description. | - | callback | callback: AsyncCallback<void> | Yes | Callback invoked to return the result.| + | callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -410,7 +409,7 @@ Asynchronously formats a volume. This API uses a callback to return the result. | -------- | ------------------------- | ---- | ----------------------------- | | volumeId | string | Yes | Volume ID. | | fsType | string | Yes | File system type.| - | callback | callback: AsyncCallback<void> | Yes | Called after the volume is formatted. | + | callback | AsyncCallback<void> | Yes | Called after the volume is formatted. | **Example** @@ -473,7 +472,7 @@ Asynchronously partitions a disk. This API uses a callback to return the result. | -------- | --------------------------------------- | ---- | ---------------- | | diskId | string | Yes | ID of the disk to which the volume belongs. | | type | number | Yes | Partition type. | - | callback | callback: AsyncCallback<void> | Yes | Callback invoked to return the result. | + | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -491,12 +490,12 @@ Asynchronously partitions a disk. This API uses a callback to return the result. ### Attributes -| Name | Type | Description | -| ----------- | ------- | -------------------- | -| id | string | Volume ID. | -| uuid | string | UUID of the volume. | -| diskId | string | ID of the disk to which the volume belongs. | -| description | string | Description of the volume. | -| removable | boolean | Whether the volume is a removable storage device.| -| state | number | Volume state. | -| path | string | Mount address of the volume. | +| Name | Type | Readable | Writable | Description | +| ----------- | ------- | ------- | ----- | -------------------- | +| id | string | Yes| No| Volume ID. | +| uuid | string | Yes| No| UUID of the volume. | +| diskId | string | Yes| No| ID of the disk to which the volume belongs. | +| description | string | Yes| No| Description of the volume. | +| removable | boolean | Yes| No| Whether the volume is a removable storage device.| +| state | number | Yes| No| Volume state. | +| path | string | Yes| No| Mount address of the volume. | diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index c7f4c94d54cc19d3a95ff40784af886d28f1e3ff..e8d51f5b1c24b57ecabb1de9341abdac99200e82 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,4 +1,4 @@ -# @ohos.wallpaper +# @ohos.wallpaper (Wallpaper) The **wallpaper** module is a system service module in OpenHarmony that provides the wallpaper management service. You can use the APIs of this module to show, set, and switch between wallpapers. diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 252dc45b802251e8cf0eb7493ce51ef917a5fa99..215816e358a3c70d147a149db7c9142a15535ec1 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,6 +1,6 @@ # @ohos.wantAgent -The **WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. +The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. > **NOTE** > @@ -8,7 +8,7 @@ The **WantAgent** module provides APIs for triggering, canceling, and comparing ## Modules to Import -```js +```ts import WantAgent from '@ohos.wantAgent'; ``` @@ -24,37 +24,41 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ----------------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + if (err.code) { + console.info('getWantAgent Callback err:' + JSON.stringify(err)) + } else { + console.info('getWantAgent Callback success') + } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -64,11 +68,9 @@ var wantAgentInfo = { wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); ``` - - ## WantAgent.getWantAgent getWantAgent(info: WantAgentInfo): Promise\ @@ -81,7 +83,7 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------------- | ---- | ------------- | -| info | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| **Return value** @@ -91,29 +93,29 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -124,12 +126,10 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); }); ``` - - ## WantAgent.getBundleName getBundleName(agent: WantAgent, callback: AsyncCallback\): void @@ -147,16 +147,16 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -164,24 +164,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -195,9 +195,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // getBundleName callback function getBundleNameCallback(err, data) { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); } -WantAgent.getBundleName(wantAgent, getBundleNameCallback) +WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -218,38 +218,37 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ----------------- | ------------------------------------------------ | | Promise\ | Promise used to return the bundle name.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -260,12 +259,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getBundleName(wantAgent).then((data) => { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); }); ``` @@ -288,16 +287,16 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -305,24 +304,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -336,9 +335,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // getUid callback function getUidCallback(err, data) { - console.info("==========================>getUidCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); } -WantAgent.getUid(wantAgent, getUidCallback) +WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -365,32 +364,32 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -401,162 +400,16 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getUid(wantAgent).then((data) => { - console.info("==========================>getUidCallback=======================>"); -}); -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent, callback: AsyncCallback\): void - -Obtains the want in a **WantAgent** object. 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 | -| -------- | --------------------- | ---- | ------------------------------- | -| agent | WantAgent | Yes | Target **WantAgent** object. | -| callback | AsyncCallback\ | Yes | Callback used to return the want.| - -**Example** - -```js -import WantAgent from '@ohos.wantAgent'; - - -// WantAgent object -var wantAgent; - -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getWant callback -function getWantCallback(err, data) { - console.info("==========================>getWantCallback=======================>"); -} -WantAgent.getWant(wantAgent, getWantCallback) -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent): Promise\ - -Obtains the want in a **WantAgent** object. 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 | -| ----- | --------- | ---- | ------------- | -| agent | WantAgent | Yes | Target **WantAgent** object.| - -**Return value** - -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the want.| - -**Example** - -```js -import WantAgent from '@ohos.wantAgent'; - - -// WantAgent object -var wantAgent; - -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); - -WantAgent.getWant(wantAgent).then((data) => { - console.info("==========================>getWantCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); }); ``` - ## WantAgent.cancel cancel(agent: WantAgent, callback: AsyncCallback\): void @@ -574,16 +427,16 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -591,24 +444,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -622,9 +475,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // cancel callback function cancelCallback(err, data) { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); } -WantAgent.cancel(wantAgent, cancelCallback) +WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -651,32 +504,32 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -687,12 +540,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.cancel(wantAgent).then((data) => { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); }); ``` @@ -711,21 +564,21 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ----------- | ----------------------------- | ---- | ------------------------------- | | agent | WantAgent | Yes | Target **WantAgent** object. | -| triggerInfo | TriggerInfo | Yes | **TriggerInfo** object. | +| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | | callback | AsyncCallback\ | No | Callback used to return the result.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -733,24 +586,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -764,7 +617,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // trigger callback function triggerCallback(data) { - console.info("==========================>triggerCallback=======================>"); + console.info('==========================>triggerCallback=======================>'); } var triggerInfo = { @@ -779,7 +632,7 @@ WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void -Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -793,17 +646,17 @@ Checks whether two **WantAgent** objects are equal. This API uses an asynchronou **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent1 = data; wantAgent2 = data; @@ -812,24 +665,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -843,7 +696,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // equal callback function equalCallback(err, data) { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); } WantAgent.equal(wantAgent1, wantAgent2, equalCallback) ``` @@ -854,7 +707,7 @@ WantAgent.equal(wantAgent1, wantAgent2, equalCallback) equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -873,33 +726,33 @@ Checks whether two **WantAgent** objects are equal. This API uses a promise to r **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -910,13 +763,13 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); }); ``` @@ -937,31 +790,31 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -972,7 +825,7 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); @@ -1003,31 +856,31 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1038,15 +891,14 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + WantAgent.getOperationType(wantAgent).then((OperationType) => { + console.log('getOperationType success, OperationType: ' + OperationType); + }).catch((err) => { + console.log('getOperationType fail, err: ' + err); + }) }); - -WantAgent.getOperationType(wantAgent).then((OperationType) => { - console.log('getOperationType success, OperationType: ' + OperationType); -}).catch((err) => { - console.log('getOperationType fail, err: ' + err); -}) ``` diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index bda4ad227b32b18130682bb4fe10db9a446535ec..2b2fa3af70da2fd1725ef0221b8fd7cf5654f531 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,7 +1,9 @@ -# WebSocket Connection +# @ohos.net.webSocket (WebSocket Connection) ->![](public_sys-resources/icon-note.gif) **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 **webSocket** module implements WebSocket connection management and operation. + +> **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. > You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index a205de94d8080753ed0305f56fb6fc5ce8534707..455416ed7c1290971e5a797766d35c52ed08b537 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -43,9 +43,9 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **Table 1** Type -| Name| Type| +| Name| Type| | -------- | -------- | -| GLenum | number | +| GLenum | number | | GLboolean | boolean | | GLbitfield | number | | GLbyte | number | @@ -58,7 +58,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | GLushort | number | | GLuint | number | | GLfloat | number | -| GLclampf | number | +| GLclampf | number | | TexImageSource | ImageData | | Float32List | array | | Int32List | array | @@ -81,7 +81,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | WebGLShader | | WebGLTexture | | WebGLUniformLocation | -| [WebGLActiveInfo](#webglactiveinfo) | +| [WebGLActiveInfo](#webglactiveinfo) | | [WebGLShaderPrecisionFormat](#webglshaderprecisionformat) | | [WebGLRenderingContextBase](#webglrenderingcontextbase) | | [WebGLRenderingContextOverloads](#webglrenderingcontextoverloads) | @@ -92,39 +92,39 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); WebGLContextAttributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| alpha | boolean | No| -| depth | boolean | No| -| stencil | boolean | No| -| antialias | boolean | No| -| premultipliedAlpha | boolean | No| -| preserveDrawingBuffer | boolean | No| -| powerPreference | WebGLPowerPreference | No| -| failIfMajorPerformanceCaveat | boolean | No| -| desynchronized | boolean | No| +| alpha | boolean | No| +| depth | boolean | No| +| stencil | boolean | No| +| antialias | boolean | No| +| premultipliedAlpha | boolean | No| +| preserveDrawingBuffer | boolean | No| +| powerPreference | WebGLPowerPreference | No| +| failIfMajorPerformanceCaveat | boolean | No| +| desynchronized | boolean | No| ## WebGLActiveInfo WebGLActiveInfo -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| size | GLint | Yes| -| type | GLenum | Yes| -| name | string | Yes| +| size | GLint | Yes| +| type | GLenum | Yes| +| name | string | Yes| ## WebGLShaderPrecisionFormat WebGLShaderPrecisionFormat -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| rangeMin | GLint | Yes| -| rangeMax | GLint | Yes| -| precision | GLint | Yes| +| rangeMin | GLint | Yes| +| rangeMax | GLint | Yes| +| precision | GLint | Yes| ## WebGLRenderingContextBase @@ -134,455 +134,455 @@ WebGLRenderingContextBase ### Attributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| DEPTH_BUFFER_BIT | GLenum | Yes| -| STENCIL_BUFFER_BIT | GLenum | Yes| -| COLOR_BUFFER_BIT | GLenum | Yes| -| POINTS | GLenum | Yes| -| LINES | GLenum | Yes| -| LINE_LOOP | GLenum | Yes| -| LINE_STRIP | GLenum | Yes| -| TRIANGLES | GLenum | Yes| -| TRIANGLE_STRIP | GLenum | Yes| -| TRIANGLE_FAN | GLenum | Yes| -| ZERO | GLenum | Yes| -| ONE | GLenum | Yes| -| SRC_COLOR | GLenum | Yes| -| ONE_MINUS_SRC_COLOR | GLenum | Yes| -| SRC_ALPHA | GLenum | Yes| -| ONE_MINUS_SRC_ALPHA | GLenum | Yes| -| DST_ALPHA | GLenum | Yes| -| ONE_MINUS_DST_ALPHA | GLenum | Yes| -| DST_COLOR | GLenum | Yes| -| ONE_MINUS_DST_COLOR | GLenum | Yes| -| SRC_ALPHA_SATURATE | GLenum | Yes| -| FUNC_ADD | GLenum | Yes| -| BLEND_EQUATION | GLenum | Yes| -| BLEND_EQUATION_RGB | GLenum | Yes| -| BLEND_EQUATION_ALPHA | GLenum | Yes| -| FUNC_SUBTRACT | GLenum | Yes| -| FUNC_REVERSE_SUBTRACT | GLenum | Yes| -| BLEND_DST_RGB | GLenum | Yes| -| BLEND_SRC_RGB | GLenum | Yes| -| BLEND_DST_ALPHA | GLenum | Yes| -| BLEND_SRC_ALPHA | GLenum | Yes| -| CONSTANT_COLOR | GLenum | Yes| -| ONE_MINUS_CONSTANT_COLOR | GLenum | Yes| -| CONSTANT_ALPHA | GLenum | Yes| -| ONE_MINUS_CONSTANT_ALPHA | GLenum | Yes| -| BLEND_COLOR | GLenum | Yes| -| ARRAY_BUFFER | GLenum | Yes| -| ELEMENT_ARRAY_BUFFER | GLenum | Yes| -| ARRAY_BUFFER_BINDING | GLenum | Yes| -| ELEMENT_ARRAY_BUFFER_BINDING | GLenum | Yes| -| STREAM_DRAW | GLenum | Yes| -| STATIC_DRAW | GLenum | Yes| -| DYNAMIC_DRAW | GLenum | Yes| -| BUFFER_SIZE | GLenum | Yes| -| BUFFER_USAGE | GLenum | Yes| -| CURRENT_VERTEX_ATTRIB | GLenum | Yes| -| FRONT | GLenum | Yes| -| BACK | GLenum | Yes| -| FRONT_AND_BACK | GLenum | Yes| -| CULL_FACE | GLenum | Yes| -| BLEND | GLenum | Yes| -| DITHER | GLenum | Yes| -| STENCIL_TEST | GLenum | Yes| -| DEPTH_TEST | GLenum | Yes| -| SCISSOR_TEST | GLenum | Yes| -| POLYGON_OFFSET_FILL | GLenum | Yes| -| SAMPLE_ALPHA_TO_COVERAGE | GLenum | Yes| -| SAMPLE_COVERAGE | GLenum | Yes| -| NO_ERROR | GLenum | Yes| -| INVALID_ENUM | GLenum | Yes| -| INVALID_VALUE | GLenum | Yes| -| INVALID_OPERATION | GLenum | Yes| -| OUT_OF_MEMORY | GLenum | Yes| -| CW | GLenum | Yes| -| CCW | GLenum | Yes| -| LINE_WIDTH | GLenum | Yes| -| ALIASED_POINT_SIZE_RANGE | GLenum | Yes| -| ALIASED_LINE_WIDTH_RANGE | GLenum | Yes| -| CULL_FACE_MODE | GLenum | Yes| -| FRONT_FACE | GLenum | Yes| -| DEPTH_RANGE | GLenum | Yes| -| DEPTH_WRITEMASK | GLenum | Yes| -| DEPTH_CLEAR_VALUE | GLenum | Yes| -| DEPTH_FUNC | GLenum | Yes| -| STENCIL_CLEAR_VALUE | GLenum | Yes| -| STENCIL_FUNC | GLenum | Yes| -| STENCIL_FAIL | GLenum | Yes| -| STENCIL_PASS_DEPTH_FAIL | GLenum | Yes| -| STENCIL_PASS_DEPTH_PASS | GLenum | Yes| -| STENCIL_REF | GLenum | Yes| -| STENCIL_VALUE_MASK | GLenum | Yes| -| STENCIL_WRITEMASK | GLenum | Yes| -| STENCIL_BACK_FUNC | GLenum | Yes| -| STENCIL_BACK_FAIL | GLenum | Yes| -| STENCIL_BACK_PASS_DEPTH_FAIL | GLenum | Yes| -| STENCIL_BACK_PASS_DEPTH_PASS | GLenum | Yes| -| STENCIL_BACK_REF | GLenum | Yes| -| STENCIL_BACK_VALUE_MASK | GLenum | Yes| -| STENCIL_BACK_WRITEMASK | GLenum | Yes| -| VIEWPORT | GLenum | Yes| -| SCISSOR_BOX | GLenum | Yes| -| COLOR_CLEAR_VALUE | GLenum | Yes| -| COLOR_WRITEMASK | GLenum | Yes| -| UNPACK_ALIGNMENT | GLenum | Yes| -| PACK_ALIGNMENT | GLenum | Yes| -| MAX_TEXTURE_SIZE | GLenum | Yes| -| MAX_VIEWPORT_DIMS | GLenum | Yes| -| SUBPIXEL_BITS | GLenum | Yes| -| RED_BITS | GLenum | Yes| -| GREEN_BITS | GLenum | Yes| -| BLUE_BITS | GLenum | Yes| -| ALPHA_BITS | GLenum | Yes| -| DEPTH_BITS | GLenum | Yes| -| STENCIL_BITS | GLenum | Yes| -| POLYGON_OFFSET_UNITS | GLenum | Yes| -| POLYGON_OFFSET_FACTOR | GLenum | Yes| -| TEXTURE_BINDING_2D | GLenum | Yes| -| SAMPLE_BUFFERS | GLenum | Yes| -| SAMPLES | GLenum | Yes| -| SAMPLE_COVERAGE_VALUE | GLenum | Yes| -| SAMPLE_COVERAGE_INVERT | GLenum | Yes| -| COMPRESSED_TEXTURE_FORMATS | GLenum | Yes| -| DONT_CARE | GLenum | Yes| -| FASTEST | GLenum | Yes| -| NICEST | GLenum | Yes| -| GENERATE_MIPMAP_HINT | GLenum | Yes| -| BYTE | GLenum | Yes| -| UNSIGNED_BYTE | GLenum | Yes| -| SHORT | GLenum | Yes| -| UNSIGNED_SHORT | GLenum | Yes| -| INT | GLenum | Yes| -| UNSIGNED_INT | GLenum | Yes| -| FLOAT | GLenum | Yes| -| DEPTH_COMPONENT | GLenum | Yes| -| ALPHA | GLenum | Yes| -| RGB | GLenum | Yes| -| RGBA | GLenum | Yes| -| LUMINANCE | GLenum | Yes| -| LUMINANCE_ALPHA | GLenum | Yes| -| UNSIGNED_SHORT_4_4_4_4 | GLenum | Yes| -| UNSIGNED_SHORT_5_5_5_1 | GLenum | Yes| -| UNSIGNED_SHORT_5_6_5 | GLenum | Yes| -| FRAGMENT_SHADER | GLenum | Yes| -| VERTEX_SHADER | GLenum | Yes| -| MAX_VERTEX_ATTRIBS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_VECTORS | GLenum | Yes| -| MAX_VARYING_VECTORS | GLenum | Yes| -| MAX_COMBINED_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_VERTEX_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_VECTORS | GLenum | Yes| -| SHADER_TYPE | GLenum | Yes| -| DELETE_STATUS | GLenum | Yes| -| LINK_STATUS | GLenum | Yes| -| VALIDATE_STATUS | GLenum | Yes| -| ATTACHED_SHADERS | GLenum | Yes| -| ACTIVE_UNIFORMS | GLenum | Yes| -| ACTIVE_ATTRIBUTES | GLenum | Yes| -| SHADING_LANGUAGE_VERSION | GLenum | Yes| -| CURRENT_PROGRAM | GLenum | Yes| -| NEVER | GLenum | Yes| -| LESS | GLenum | Yes| -| EQUAL | GLenum | Yes| -| LEQUAL | GLenum | Yes| -| GREATER | GLenum | Yes| -| NOTEQUAL | GLenum | Yes| -| GEQUAL | GLenum | Yes| -| ALWAYS | GLenum | Yes| -| KEEP | GLenum | Yes| -| REPLACE | GLenum | Yes| -| INCR | GLenum | Yes| -| DECR | GLenum | Yes| -| INVERT | GLenum | Yes| -| INCR_WRAP | GLenum | Yes| -| DECR_WRAP | GLenum | Yes| -| VENDOR | GLenum | Yes| -| RENDERER | GLenum | Yes| -| VERSION | GLenum | Yes| -| NEAREST | GLenum | Yes| -| LINEAR | GLenum | Yes| -| NEAREST_MIPMAP_NEAREST | GLenum | Yes| -| LINEAR_MIPMAP_NEAREST | GLenum | Yes| -| NEAREST_MIPMAP_LINEAR | GLenum | Yes| -| LINEAR_MIPMAP_LINEAR | GLenum | Yes| -| TEXTURE_MIN_FILTER | GLenum | Yes| -| TEXTURE_WRAP_S | GLenum | Yes| -| TEXTURE_WRAP_T | GLenum | Yes| -| TEXTURE_2D | GLenum | Yes| -| TEXTURE | GLenum | Yes| -| TEXTURE_CUBE_MAP | GLenum | Yes| -| TEXTURE_BINDING_CUBE_MAP | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_X | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_X | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_Y | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_Y | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_Z | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_Z | GLenum | Yes| -| MAX_CUBE_MAP_TEXTURE_SIZE | GLenum | Yes| -| TEXTURE0 | GLenum | Yes| -| TEXTURE1 | GLenum | Yes| -| TEXTURE2 | GLenum | Yes| -| TEXTURE3 | GLenum | Yes| -| TEXTURE4 | GLenum | Yes| -| TEXTURE5 | GLenum | Yes| -| TEXTURE6 | GLenum | Yes| -| TEXTURE7 | GLenum | Yes| -| TEXTURE8 | GLenum | Yes| -| TEXTURE9 | GLenum | Yes| -| TEXTURE10 | GLenum | Yes| -| TEXTURE11 | GLenum | Yes| -| TEXTURE12 | GLenum | Yes| -| TEXTURE13 | GLenum | Yes| -| TEXTURE14 | GLenum | Yes| -| TEXTURE15 | GLenum | Yes| -| TEXTURE16 | GLenum | Yes| -| TEXTURE17 | GLenum | Yes| -| TEXTURE18 | GLenum | Yes| -| TEXTURE19 | GLenum | Yes| -| TEXTURE20 | GLenum | Yes| -| TEXTURE21 | GLenum | Yes| -| TEXTURE22 | GLenum | Yes| -| TEXTURE23 | GLenum | Yes| -| TEXTURE24 | GLenum | Yes| -| TEXTURE25 | GLenum | Yes| -| TEXTURE26 | GLenum | Yes| -| TEXTURE27 | GLenum | Yes| -| TEXTURE28 | GLenum | Yes| -| TEXTURE29 | GLenum | Yes| -| TEXTURE30 | GLenum | Yes| -| TEXTURE31 | GLenum | Yes| -| ACTIVE_TEXTURE | GLenum | Yes| -| REPEAT | GLenum | Yes| -| CLAMP_TO_EDGE | GLenum | Yes| -| MIRRORED_REPEAT | GLenum | Yes| -| FLOAT_VEC2 | GLenum | Yes| -| FLOAT_VEC3 | GLenum | Yes| -| FLOAT_VEC4 | GLenum | Yes| -| INT_VEC2 | GLenum | Yes| -| INT_VEC3 | GLenum | Yes| -| INT_VEC4 | GLenum | Yes| -| BOOL | GLenum | Yes| -| BOOL_VEC2 | GLenum | Yes| -| BOOL_VEC3 | GLenum | Yes| -| BOOL_VEC4 | GLenum | Yes| -| FLOAT_MAT2 | GLenum | Yes| -| FLOAT_MAT3 | GLenum | Yes| -| FLOAT_MAT4 | GLenum | Yes| -| SAMPLER_2D | GLenum | Yes| -| SAMPLER_CUBE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_ENABLED | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_SIZE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_STRIDE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_TYPE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_NORMALIZED | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_POINTER | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_BUFFER_BINDING | GLenum | Yes| -| IMPLEMENTATION_COLOR_READ_TYPE | GLenum | Yes| -| IMPLEMENTATION_COLOR_READ_FORMAT | GLenum | Yes| -| COMPILE_STATUS | GLenum | Yes| -| LOW_FLOAT | GLenum | Yes| -| MEDIUM_FLOAT | GLenum | Yes| -| HIGH_FLOAT | GLenum | Yes| -| LOW_INT | GLenum | Yes| -| MEDIUM_INT | GLenum | Yes| -| HIGH_INT | GLenum | Yes| -| FRAMEBUFFER | GLenum | Yes| -| RENDERBUFFER | GLenum | Yes| -| RGBA4 | GLenum | Yes| -| RGB5_A1 | GLenum | Yes| -| RGB565 | GLenum | Yes| -| DEPTH_COMPONENT16 | GLenum | Yes| -| STENCIL_INDEX8 | GLenum | Yes| -| DEPTH_STENCIL | GLenum | Yes| -| RENDERBUFFER_WIDTH | GLenum | Yes| -| RENDERBUFFER_HEIGHT | GLenum | Yes| -| RENDERBUFFER_INTERNAL_FORMAT | GLenum | Yes| -| RENDERBUFFER_RED_SIZE | GLenum | Yes| -| RENDERBUFFER_GREEN_SIZE | GLenum | Yes| -| RENDERBUFFER_BLUE_SIZE | GLenum | Yes| -| RENDERBUFFER_ALPHA_SIZE | GLenum | Yes| -| RENDERBUFFER_DEPTH_SIZE | GLenum | Yes| -| RENDERBUFFER_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | GLenum | Yes| -| COLOR_ATTACHMENT0 | GLenum | Yes| -| DEPTH_ATTACHMENT | GLenum | Yes| -| STENCIL_ATTACHMENT | GLenum | Yes| -| DEPTH_STENCIL_ATTACHMENT | GLenum | Yes| -| NONE | GLenum | Yes| -| FRAMEBUFFER_COMPLETE | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_ATTACHMENT | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_DIMENSIONS | GLenum | Yes| -| FRAMEBUFFER_UNSUPPORTED | GLenum | Yes| -| FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_BINDING | GLenum | Yes| -| MAX_RENDERBUFFER_SIZE | GLenum | Yes| -| INVALID_FRAMEBUFFER_OPERATION | GLenum | Yes| -| UNPACK_FLIP_Y_WEBGL | GLenum | Yes| -| UNPACK_PREMULTIPLY_ALPHA_WEBGL | GLenum | Yes| -| CONTEXT_LOST_WEBGL | GLenum | Yes| -| UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| -| BROWSER_DEFAULT_WEBGL | GLenum | Yes| -| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| -| drawingBufferWidth | GLsizei | Yes| -| drawingBufferHeight | GLsizei | Yes| +| DEPTH_BUFFER_BIT | GLenum | Yes| +| STENCIL_BUFFER_BIT | GLenum | Yes| +| COLOR_BUFFER_BIT | GLenum | Yes| +| POINTS | GLenum | Yes| +| LINES | GLenum | Yes| +| LINE_LOOP | GLenum | Yes| +| LINE_STRIP | GLenum | Yes| +| TRIANGLES | GLenum | Yes| +| TRIANGLE_STRIP | GLenum | Yes| +| TRIANGLE_FAN | GLenum | Yes| +| ZERO | GLenum | Yes| +| ONE | GLenum | Yes| +| SRC_COLOR | GLenum | Yes| +| ONE_MINUS_SRC_COLOR | GLenum | Yes| +| SRC_ALPHA | GLenum | Yes| +| ONE_MINUS_SRC_ALPHA | GLenum | Yes| +| DST_ALPHA | GLenum | Yes| +| ONE_MINUS_DST_ALPHA | GLenum | Yes| +| DST_COLOR | GLenum | Yes| +| ONE_MINUS_DST_COLOR | GLenum | Yes| +| SRC_ALPHA_SATURATE | GLenum | Yes| +| FUNC_ADD | GLenum | Yes| +| BLEND_EQUATION | GLenum | Yes| +| BLEND_EQUATION_RGB | GLenum | Yes| +| BLEND_EQUATION_ALPHA | GLenum | Yes| +| FUNC_SUBTRACT | GLenum | Yes| +| FUNC_REVERSE_SUBTRACT | GLenum | Yes| +| BLEND_DST_RGB | GLenum | Yes| +| BLEND_SRC_RGB | GLenum | Yes| +| BLEND_DST_ALPHA | GLenum | Yes| +| BLEND_SRC_ALPHA | GLenum | Yes| +| CONSTANT_COLOR | GLenum | Yes| +| ONE_MINUS_CONSTANT_COLOR | GLenum | Yes| +| CONSTANT_ALPHA | GLenum | Yes| +| ONE_MINUS_CONSTANT_ALPHA | GLenum | Yes| +| BLEND_COLOR | GLenum | Yes| +| ARRAY_BUFFER | GLenum | Yes| +| ELEMENT_ARRAY_BUFFER | GLenum | Yes| +| ARRAY_BUFFER_BINDING | GLenum | Yes| +| ELEMENT_ARRAY_BUFFER_BINDING | GLenum | Yes| +| STREAM_DRAW | GLenum | Yes| +| STATIC_DRAW | GLenum | Yes| +| DYNAMIC_DRAW | GLenum | Yes| +| BUFFER_SIZE | GLenum | Yes| +| BUFFER_USAGE | GLenum | Yes| +| CURRENT_VERTEX_ATTRIB | GLenum | Yes| +| FRONT | GLenum | Yes| +| BACK | GLenum | Yes| +| FRONT_AND_BACK | GLenum | Yes| +| CULL_FACE | GLenum | Yes| +| BLEND | GLenum | Yes| +| DITHER | GLenum | Yes| +| STENCIL_TEST | GLenum | Yes| +| DEPTH_TEST | GLenum | Yes| +| SCISSOR_TEST | GLenum | Yes| +| POLYGON_OFFSET_FILL | GLenum | Yes| +| SAMPLE_ALPHA_TO_COVERAGE | GLenum | Yes| +| SAMPLE_COVERAGE | GLenum | Yes| +| NO_ERROR | GLenum | Yes| +| INVALID_ENUM | GLenum | Yes| +| INVALID_VALUE | GLenum | Yes| +| INVALID_OPERATION | GLenum | Yes| +| OUT_OF_MEMORY | GLenum | Yes| +| CW | GLenum | Yes| +| CCW | GLenum | Yes| +| LINE_WIDTH | GLenum | Yes| +| ALIASED_POINT_SIZE_RANGE | GLenum | Yes| +| ALIASED_LINE_WIDTH_RANGE | GLenum | Yes| +| CULL_FACE_MODE | GLenum | Yes| +| FRONT_FACE | GLenum | Yes| +| DEPTH_RANGE | GLenum | Yes| +| DEPTH_WRITEMASK | GLenum | Yes| +| DEPTH_CLEAR_VALUE | GLenum | Yes| +| DEPTH_FUNC | GLenum | Yes| +| STENCIL_CLEAR_VALUE | GLenum | Yes| +| STENCIL_FUNC | GLenum | Yes| +| STENCIL_FAIL | GLenum | Yes| +| STENCIL_PASS_DEPTH_FAIL | GLenum | Yes| +| STENCIL_PASS_DEPTH_PASS | GLenum | Yes| +| STENCIL_REF | GLenum | Yes| +| STENCIL_VALUE_MASK | GLenum | Yes| +| STENCIL_WRITEMASK | GLenum | Yes| +| STENCIL_BACK_FUNC | GLenum | Yes| +| STENCIL_BACK_FAIL | GLenum | Yes| +| STENCIL_BACK_PASS_DEPTH_FAIL | GLenum | Yes| +| STENCIL_BACK_PASS_DEPTH_PASS | GLenum | Yes| +| STENCIL_BACK_REF | GLenum | Yes| +| STENCIL_BACK_VALUE_MASK | GLenum | Yes| +| STENCIL_BACK_WRITEMASK | GLenum | Yes| +| VIEWPORT | GLenum | Yes| +| SCISSOR_BOX | GLenum | Yes| +| COLOR_CLEAR_VALUE | GLenum | Yes| +| COLOR_WRITEMASK | GLenum | Yes| +| UNPACK_ALIGNMENT | GLenum | Yes| +| PACK_ALIGNMENT | GLenum | Yes| +| MAX_TEXTURE_SIZE | GLenum | Yes| +| MAX_VIEWPORT_DIMS | GLenum | Yes| +| SUBPIXEL_BITS | GLenum | Yes| +| RED_BITS | GLenum | Yes| +| GREEN_BITS | GLenum | Yes| +| BLUE_BITS | GLenum | Yes| +| ALPHA_BITS | GLenum | Yes| +| DEPTH_BITS | GLenum | Yes| +| STENCIL_BITS | GLenum | Yes| +| POLYGON_OFFSET_UNITS | GLenum | Yes| +| POLYGON_OFFSET_FACTOR | GLenum | Yes| +| TEXTURE_BINDING_2D | GLenum | Yes| +| SAMPLE_BUFFERS | GLenum | Yes| +| SAMPLES | GLenum | Yes| +| SAMPLE_COVERAGE_VALUE | GLenum | Yes| +| SAMPLE_COVERAGE_INVERT | GLenum | Yes| +| COMPRESSED_TEXTURE_FORMATS | GLenum | Yes| +| DONT_CARE | GLenum | Yes| +| FASTEST | GLenum | Yes| +| NICEST | GLenum | Yes| +| GENERATE_MIPMAP_HINT | GLenum | Yes| +| BYTE | GLenum | Yes| +| UNSIGNED_BYTE | GLenum | Yes| +| SHORT | GLenum | Yes| +| UNSIGNED_SHORT | GLenum | Yes| +| INT | GLenum | Yes| +| UNSIGNED_INT | GLenum | Yes| +| FLOAT | GLenum | Yes| +| DEPTH_COMPONENT | GLenum | Yes| +| ALPHA | GLenum | Yes| +| RGB | GLenum | Yes| +| RGBA | GLenum | Yes| +| LUMINANCE | GLenum | Yes| +| LUMINANCE_ALPHA | GLenum | Yes| +| UNSIGNED_SHORT_4_4_4_4 | GLenum | Yes| +| UNSIGNED_SHORT_5_5_5_1 | GLenum | Yes| +| UNSIGNED_SHORT_5_6_5 | GLenum | Yes| +| FRAGMENT_SHADER | GLenum | Yes| +| VERTEX_SHADER | GLenum | Yes| +| MAX_VERTEX_ATTRIBS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_VECTORS | GLenum | Yes| +| MAX_VARYING_VECTORS | GLenum | Yes| +| MAX_COMBINED_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_VERTEX_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_VECTORS | GLenum | Yes| +| SHADER_TYPE | GLenum | Yes| +| DELETE_STATUS | GLenum | Yes| +| LINK_STATUS | GLenum | Yes| +| VALIDATE_STATUS | GLenum | Yes| +| ATTACHED_SHADERS | GLenum | Yes| +| ACTIVE_UNIFORMS | GLenum | Yes| +| ACTIVE_ATTRIBUTES | GLenum | Yes| +| SHADING_LANGUAGE_VERSION | GLenum | Yes| +| CURRENT_PROGRAM | GLenum | Yes| +| NEVER | GLenum | Yes| +| LESS | GLenum | Yes| +| EQUAL | GLenum | Yes| +| LEQUAL | GLenum | Yes| +| GREATER | GLenum | Yes| +| NOTEQUAL | GLenum | Yes| +| GEQUAL | GLenum | Yes| +| ALWAYS | GLenum | Yes| +| KEEP | GLenum | Yes| +| REPLACE | GLenum | Yes| +| INCR | GLenum | Yes| +| DECR | GLenum | Yes| +| INVERT | GLenum | Yes| +| INCR_WRAP | GLenum | Yes| +| DECR_WRAP | GLenum | Yes| +| VENDOR | GLenum | Yes| +| RENDERER | GLenum | Yes| +| VERSION | GLenum | Yes| +| NEAREST | GLenum | Yes| +| LINEAR | GLenum | Yes| +| NEAREST_MIPMAP_NEAREST | GLenum | Yes| +| LINEAR_MIPMAP_NEAREST | GLenum | Yes| +| NEAREST_MIPMAP_LINEAR | GLenum | Yes| +| LINEAR_MIPMAP_LINEAR | GLenum | Yes| +| TEXTURE_MIN_FILTER | GLenum | Yes| +| TEXTURE_WRAP_S | GLenum | Yes| +| TEXTURE_WRAP_T | GLenum | Yes| +| TEXTURE_2D | GLenum | Yes| +| TEXTURE | GLenum | Yes| +| TEXTURE_CUBE_MAP | GLenum | Yes| +| TEXTURE_BINDING_CUBE_MAP | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_X | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_X | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_Y | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_Y | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_Z | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_Z | GLenum | Yes| +| MAX_CUBE_MAP_TEXTURE_SIZE | GLenum | Yes| +| TEXTURE0 | GLenum | Yes| +| TEXTURE1 | GLenum | Yes| +| TEXTURE2 | GLenum | Yes| +| TEXTURE3 | GLenum | Yes| +| TEXTURE4 | GLenum | Yes| +| TEXTURE5 | GLenum | Yes| +| TEXTURE6 | GLenum | Yes| +| TEXTURE7 | GLenum | Yes| +| TEXTURE8 | GLenum | Yes| +| TEXTURE9 | GLenum | Yes| +| TEXTURE10 | GLenum | Yes| +| TEXTURE11 | GLenum | Yes| +| TEXTURE12 | GLenum | Yes| +| TEXTURE13 | GLenum | Yes| +| TEXTURE14 | GLenum | Yes| +| TEXTURE15 | GLenum | Yes| +| TEXTURE16 | GLenum | Yes| +| TEXTURE17 | GLenum | Yes| +| TEXTURE18 | GLenum | Yes| +| TEXTURE19 | GLenum | Yes| +| TEXTURE20 | GLenum | Yes| +| TEXTURE21 | GLenum | Yes| +| TEXTURE22 | GLenum | Yes| +| TEXTURE23 | GLenum | Yes| +| TEXTURE24 | GLenum | Yes| +| TEXTURE25 | GLenum | Yes| +| TEXTURE26 | GLenum | Yes| +| TEXTURE27 | GLenum | Yes| +| TEXTURE28 | GLenum | Yes| +| TEXTURE29 | GLenum | Yes| +| TEXTURE30 | GLenum | Yes| +| TEXTURE31 | GLenum | Yes| +| ACTIVE_TEXTURE | GLenum | Yes| +| REPEAT | GLenum | Yes| +| CLAMP_TO_EDGE | GLenum | Yes| +| MIRRORED_REPEAT | GLenum | Yes| +| FLOAT_VEC2 | GLenum | Yes| +| FLOAT_VEC3 | GLenum | Yes| +| FLOAT_VEC4 | GLenum | Yes| +| INT_VEC2 | GLenum | Yes| +| INT_VEC3 | GLenum | Yes| +| INT_VEC4 | GLenum | Yes| +| BOOL | GLenum | Yes| +| BOOL_VEC2 | GLenum | Yes| +| BOOL_VEC3 | GLenum | Yes| +| BOOL_VEC4 | GLenum | Yes| +| FLOAT_MAT2 | GLenum | Yes| +| FLOAT_MAT3 | GLenum | Yes| +| FLOAT_MAT4 | GLenum | Yes| +| SAMPLER_2D | GLenum | Yes| +| SAMPLER_CUBE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_ENABLED | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_SIZE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_STRIDE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_TYPE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_NORMALIZED | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_POINTER | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_BUFFER_BINDING | GLenum | Yes| +| IMPLEMENTATION_COLOR_READ_TYPE | GLenum | Yes| +| IMPLEMENTATION_COLOR_READ_FORMAT | GLenum | Yes| +| COMPILE_STATUS | GLenum | Yes| +| LOW_FLOAT | GLenum | Yes| +| MEDIUM_FLOAT | GLenum | Yes| +| HIGH_FLOAT | GLenum | Yes| +| LOW_INT | GLenum | Yes| +| MEDIUM_INT | GLenum | Yes| +| HIGH_INT | GLenum | Yes| +| FRAMEBUFFER | GLenum | Yes| +| RENDERBUFFER | GLenum | Yes| +| RGBA4 | GLenum | Yes| +| RGB5_A1 | GLenum | Yes| +| RGB565 | GLenum | Yes| +| DEPTH_COMPONENT16 | GLenum | Yes| +| STENCIL_INDEX8 | GLenum | Yes| +| DEPTH_STENCIL | GLenum | Yes| +| RENDERBUFFER_WIDTH | GLenum | Yes| +| RENDERBUFFER_HEIGHT | GLenum | Yes| +| RENDERBUFFER_INTERNAL_FORMAT | GLenum | Yes| +| RENDERBUFFER_RED_SIZE | GLenum | Yes| +| RENDERBUFFER_GREEN_SIZE | GLenum | Yes| +| RENDERBUFFER_BLUE_SIZE | GLenum | Yes| +| RENDERBUFFER_ALPHA_SIZE | GLenum | Yes| +| RENDERBUFFER_DEPTH_SIZE | GLenum | Yes| +| RENDERBUFFER_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | GLenum | Yes| +| COLOR_ATTACHMENT0 | GLenum | Yes| +| DEPTH_ATTACHMENT | GLenum | Yes| +| STENCIL_ATTACHMENT | GLenum | Yes| +| DEPTH_STENCIL_ATTACHMENT | GLenum | Yes| +| NONE | GLenum | Yes| +| FRAMEBUFFER_COMPLETE | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_ATTACHMENT | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_DIMENSIONS | GLenum | Yes| +| FRAMEBUFFER_UNSUPPORTED | GLenum | Yes| +| FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_BINDING | GLenum | Yes| +| MAX_RENDERBUFFER_SIZE | GLenum | Yes| +| INVALID_FRAMEBUFFER_OPERATION | GLenum | Yes| +| UNPACK_FLIP_Y_WEBGL | GLenum | Yes| +| UNPACK_PREMULTIPLY_ALPHA_WEBGL | GLenum | Yes| +| CONTEXT_LOST_WEBGL | GLenum | Yes| +| UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| +| BROWSER_DEFAULT_WEBGL | GLenum | Yes| +| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| +| drawingBufferWidth | GLsizei | Yes| +| drawingBufferHeight | GLsizei | Yes| ### Methods -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| getContextAttributes() | WebGLContextAttributes \| null | -| isContextLost() | boolean | -| getSupportedExtensions() | string[] \| null | -| getExtension(name: string) | any | -| activeTexture(texture: GLenum) | void | -| attachShader(program: WebGLProgram, shader: WebGLShader) | void | -| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | -| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | -| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | -| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | -| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| blendEquation(mode: GLenum) | void | -| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | -| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | -| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | -| checkFramebufferStatus(target: GLenum) | GLenum | -| clear(mask: GLbitfield) | void | -| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| clearDepth(depth: GLclampf) | void | -| clearStencil(s: GLint) | void | -| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | -| compileShader(shader: WebGLShader) | void | -| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | -| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| createBuffer() | WebGLBuffer \| null | -| createFramebuffer() | WebGLFramebuffer \| null | -| createProgram() | WebGLProgram \| null | -| createRenderbuffer() | WebGLRenderbuffer \| null | -| createShader(type: GLenum) | WebGLShader \| null | -| createTexture() | WebGLTexture \| null | -| cullFace(mode: GLenum) | void | -| deleteBuffer(buffer: WebGLBuffer \| null) | void | -| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | -| deleteProgram(program: WebGLProgram \| null) | void | -| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | -| deleteShader(shader: WebGLShader \| null) | void | -| deleteTexture(texture: WebGLTexture \| null) | void | -| depthFunc(func: GLenum) | void | -| depthMask(flag: GLboolean) | void | -| depthRange(zNear: GLclampf, zFar: GLclampf) | void | -| detachShader(program: WebGLProgram, shader: WebGLShader) | void | -| disable(cap: GLenum) | void | -| disableVertexAttribArray(index: GLuint) | void | -| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | -| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| enable(cap: GLenum) | void | -| enableVertexAttribArray(index: GLuint) | void | -| finish() | void | -| flush() | void | -| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | -| frontFace(mode: GLenum) | void | -| generateMipmap(target: GLenum) | void | -| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | -| getAttribLocation(program: WebGLProgram, name: string) | GLint | -| getBufferParameter(target: GLenum, pname: GLenum) | any | -| getParameter(pname: GLenum) | any | -| getError() | GLenum | -| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | -| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | -| getProgramInfoLog(program: WebGLProgram) | string \| null | -| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | -| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | -| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | -| getShaderInfoLog(shader: WebGLShader) | string \| null | -| getShaderSource(shader: WebGLShader) | string \| null | -| getTexParameter(target: GLenum, pname: GLenum) | any | -| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | -| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | -| getVertexAttrib(index: GLuint, pname: GLenum) | any | -| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | -| hint(target: GLenum, mode: GLenum) | void | -| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | -| isEnabled(cap: GLenum) | GLboolean | -| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | -| isProgram(program: WebGLProgram \| null) | GLboolean | -| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | -| isShader(shader: WebGLShader \| null) | GLboolean | -| isTexture(texture: WebGLTexture \| null) | GLboolean | -| lineWidth(width: GLfloat) | void | -| linkProgram(program: WebGLProgram) | void | -| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | -| polygonOffset(factor: GLfloat, units: GLfloat) | void | -| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| sampleCoverage(value: GLclampf, invert: GLboolean) | void | -| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| shaderSource(shader: WebGLShader, source: string) | void | -| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilMask(mask: GLuint) | void | -| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | -| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | -| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | -| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | -| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | -| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | -| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | -| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | -| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| useProgram(program: WebGLProgram \| null) | void | -| validateProgram(program: WebGLProgram) | void | -| vertexAttrib1f(index: GLuint, x: GLfloat) | void | -| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | -| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| vertexAttrib1fv(index: GLuint, values: Float32List) | void | -| vertexAttrib2fv(index: GLuint, values: Float32List) | void | -| vertexAttrib3fv(index: GLuint, values: Float32List) | void | -| vertexAttrib4fv(index: GLuint, values: Float32List) | void | -| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | -| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| getContextAttributes() | WebGLContextAttributes \| null | +| isContextLost() | boolean | +| getSupportedExtensions() | string[] \| null | +| getExtension(name: string) | any | +| activeTexture(texture: GLenum) | void | +| attachShader(program: WebGLProgram, shader: WebGLShader) | void | +| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | +| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | +| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | +| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | +| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| blendEquation(mode: GLenum) | void | +| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | +| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | +| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | +| checkFramebufferStatus(target: GLenum) | GLenum | +| clear(mask: GLbitfield) | void | +| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| clearDepth(depth: GLclampf) | void | +| clearStencil(s: GLint) | void | +| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | +| compileShader(shader: WebGLShader) | void | +| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | +| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| createBuffer() | WebGLBuffer \| null | +| createFramebuffer() | WebGLFramebuffer \| null | +| createProgram() | WebGLProgram \| null | +| createRenderbuffer() | WebGLRenderbuffer \| null | +| createShader(type: GLenum) | WebGLShader \| null | +| createTexture() | WebGLTexture \| null | +| cullFace(mode: GLenum) | void | +| deleteBuffer(buffer: WebGLBuffer \| null) | void | +| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | +| deleteProgram(program: WebGLProgram \| null) | void | +| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | +| deleteShader(shader: WebGLShader \| null) | void | +| deleteTexture(texture: WebGLTexture \| null) | void | +| depthFunc(func: GLenum) | void | +| depthMask(flag: GLboolean) | void | +| depthRange(zNear: GLclampf, zFar: GLclampf) | void | +| detachShader(program: WebGLProgram, shader: WebGLShader) | void | +| disable(cap: GLenum) | void | +| disableVertexAttribArray(index: GLuint) | void | +| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | +| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| enable(cap: GLenum) | void | +| enableVertexAttribArray(index: GLuint) | void | +| finish() | void | +| flush() | void | +| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | +| frontFace(mode: GLenum) | void | +| generateMipmap(target: GLenum) | void | +| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | +| getAttribLocation(program: WebGLProgram, name: string) | GLint | +| getBufferParameter(target: GLenum, pname: GLenum) | any | +| getParameter(pname: GLenum) | any | +| getError() | GLenum | +| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | +| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | +| getProgramInfoLog(program: WebGLProgram) | string \| null | +| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | +| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | +| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | +| getShaderInfoLog(shader: WebGLShader) | string \| null | +| getShaderSource(shader: WebGLShader) | string \| null | +| getTexParameter(target: GLenum, pname: GLenum) | any | +| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | +| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | +| getVertexAttrib(index: GLuint, pname: GLenum) | any | +| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | +| hint(target: GLenum, mode: GLenum) | void | +| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | +| isEnabled(cap: GLenum) | GLboolean | +| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | +| isProgram(program: WebGLProgram \| null) | GLboolean | +| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | +| isShader(shader: WebGLShader \| null) | GLboolean | +| isTexture(texture: WebGLTexture \| null) | GLboolean | +| lineWidth(width: GLfloat) | void | +| linkProgram(program: WebGLProgram) | void | +| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | +| polygonOffset(factor: GLfloat, units: GLfloat) | void | +| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| sampleCoverage(value: GLclampf, invert: GLboolean) | void | +| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| shaderSource(shader: WebGLShader, source: string) | void | +| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilMask(mask: GLuint) | void | +| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | +| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | +| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | +| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | +| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | +| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | +| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | +| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | +| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| useProgram(program: WebGLProgram \| null) | void | +| validateProgram(program: WebGLProgram) | void | +| vertexAttrib1f(index: GLuint, x: GLfloat) | void | +| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | +| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| vertexAttrib1fv(index: GLuint, values: Float32List) | void | +| vertexAttrib2fv(index: GLuint, values: Float32List) | void | +| vertexAttrib3fv(index: GLuint, values: Float32List) | void | +| vertexAttrib4fv(index: GLuint, values: Float32List) | void | +| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | +| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | ## WebGLRenderingContextOverloads WebGLRenderingContextOverloads -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index 6fc36366d38b7d65484822911e8acdf926b8e931..dc19039007c1f8207e2dd3ac026c67bdac169d9f 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -75,409 +75,409 @@ WebGL2RenderingContextBase ### Attributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| READ_BUFFER | GLenum | Yes| -| UNPACK_ROW_LENGTH | GLenum | Yes| -| UNPACK_SKIP_ROWS | GLenum | Yes| -| UNPACK_SKIP_PIXELS | GLenum | Yes| -| PACK_ROW_LENGTH | GLenum | Yes| -| PACK_SKIP_ROWS | GLenum | Yes| -| PACK_SKIP_PIXELS | GLenum | Yes| -| COLOR | GLenum | Yes| -| DEPTH | GLenum | Yes| -| STENCIL | GLenum | Yes| -| RED | GLenum | Yes| -| RGB8 | GLenum | Yes| -| RGBA8 | GLenum | Yes| -| RGB10_A2 | GLenum | Yes| -| TEXTURE_BINDING_3D | GLenum | Yes| -| UNPACK_SKIP_IMAGES | GLenum | Yes| -| UNPACK_IMAGE_HEIGHT | GLenum | Yes| -| TEXTURE_3D | GLenum | Yes| -| TEXTURE_WRAP_R | GLenum | Yes| -| MAX_3D_TEXTURE_SIZE | GLenum | Yes| -| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| -| MAX_ELEMENTS_VERTICES | GLenum | Yes| -| MAX_ELEMENTS_INDICES | GLenum | Yes| -| TEXTURE_MIN_LOD | GLenum | Yes| -| TEXTURE_MAX_LOD | GLenum | Yes| -| TEXTURE_BASE_LEVEL | GLenum | Yes| -| TEXTURE_MAX_LEVEL | GLenum | Yes| -| MIN | GLenum | Yes| -| MAX | GLenum | Yes| -| DEPTH_COMPONENT24 | GLenum | Yes| -| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| -| TEXTURE_COMPARE_MODE | GLenum | Yes| -| TEXTURE_COMPARE_FUNC | GLenum | Yes| -| CURRENT_QUERY | GLenum | Yes| -| QUERY_RESULT | GLenum | Yes| -| QUERY_RESULT_AVAILABLE | GLenum | Yes| -| STREAM_READ | GLenum | Yes| -| STREAM_COPY | GLenum | Yes| -| STATIC_READ | GLenum | Yes| -| STATIC_COPY | GLenum | Yes| -| DYNAMIC_READ | GLenum | Yes| -| DYNAMIC_COPY | GLenum | Yes| -| MAX_DRAW_BUFFERS | GLenum | Yes| -| DRAW_BUFFER0 | GLenum | Yes| -| DRAW_BUFFER1 | GLenum | Yes| -| DRAW_BUFFER2 | GLenum | Yes| -| DRAW_BUFFER3 | GLenum | Yes| -| DRAW_BUFFER4 | GLenum | Yes| -| DRAW_BUFFER5 | GLenum | Yes| -| DRAW_BUFFER6 | GLenum | Yes| -| DRAW_BUFFER7 | GLenum | Yes| -| DRAW_BUFFER8 | GLenum | Yes| -| DRAW_BUFFER9 | GLenum | Yes| -| DRAW_BUFFER10 | GLenum | Yes| -| DRAW_BUFFER11 | GLenum | Yes| -| DRAW_BUFFER12 | GLenum | Yes| -| DRAW_BUFFER13 | GLenum | Yes| -| DRAW_BUFFER14 | GLenum | Yes| -| DRAW_BUFFER15 | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| SAMPLER_3D | GLenum | Yes| -| SAMPLER_2D_SHADOW | GLenum | Yes| -| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| -| PIXEL_PACK_BUFFER | GLenum | Yes| -| PIXEL_UNPACK_BUFFER | GLenum | Yes| -| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| -| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| -| FLOAT_MAT2x3 | GLenum | Yes| -| FLOAT_MAT2x4 | GLenum | Yes| -| FLOAT_MAT3x2 | GLenum | Yes| -| FLOAT_MAT3x4 | GLenum | Yes| -| FLOAT_MAT4x2 | GLenum | Yes| -| FLOAT_MAT4x3 | GLenum | Yes| -| SRGB | GLenum | Yes| -| SRGB8 | GLenum | Yes| -| SRGB8_ALPHA8 | GLenum | Yes| -| COMPARE_REF_TO_TEXTURE | GLenum | Yes| -| RGBA32F | GLenum | Yes| -| RGB32F | GLenum | Yes| -| RGBA16F | GLenum | Yes| -| RGB16F | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| -| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| -| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_VARYING_COMPONENTS | GLenum | Yes| -| TEXTURE_2D_ARRAY | GLenum | Yes| -| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| -| R11F_G11F_B10F | GLenum | Yes| -| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| -| RGB9_E5 | GLenum | Yes| -| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| -| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| -| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| -| RASTERIZER_DISCARD | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| -| INTERLEAVED_ATTRIBS | GLenum | Yes| -| SEPARATE_ATTRIBS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| -| RGBA32UI | GLenum | Yes| -| RGB32UI | GLenum | Yes| -| RGBA16UI | GLenum | Yes| -| RGB16UI | GLenum | Yes| -| RGBA8UI | GLenum | Yes| -| RGB8UI | GLenum | Yes| -| RGBA32I | GLenum | Yes| -| RGB32I | GLenum | Yes| -| RGBA16I | GLenum | Yes| -| RGB16I | GLenum | Yes| -| RGBA8I | GLenum | Yes| -| RGB8I | GLenum | Yes| -| RED_INTEGER | GLenum | Yes| -| RGB_INTEGER | GLenum | Yes| -| RGBA_INTEGER | GLenum | Yes| -| SAMPLER_2D_ARRAY | GLenum | Yes| -| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| -| SAMPLER_CUBE_SHADOW | GLenum | Yes| -| UNSIGNED_INT_VEC2 | GLenum | Yes| -| UNSIGNED_INT_VEC3 | GLenum | Yes| -| UNSIGNED_INT_VEC4 | GLenum | Yes| -| INT_SAMPLER_2D | GLenum | Yes| -| INT_SAMPLER_3D | GLenum | Yes| -| INT_SAMPLER_CUBE | GLenum | Yes| -| INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| DEPTH_COMPONENT32F | GLenum | Yes| -| DEPTH32F_STENCIL8 | GLenum | Yes| -| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_DEFAULT | GLenum | Yes| -| UNSIGNED_INT_24_8 | GLenum | Yes| -| DEPTH24_STENCIL8 | GLenum | Yes| -| UNSIGNED_NORMALIZED | GLenum | Yes| -| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| -| READ_FRAMEBUFFER | GLenum | Yes| -| DRAW_FRAMEBUFFER | GLenum | Yes| -| READ_FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_SAMPLES | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| -| MAX_COLOR_ATTACHMENTS | GLenum | Yes| -| COLOR_ATTACHMENT1 | GLenum | Yes| -| COLOR_ATTACHMENT2 | GLenum | Yes| -| COLOR_ATTACHMENT3 | GLenum | Yes| -| COLOR_ATTACHMENT4 | GLenum | Yes| -| COLOR_ATTACHMENT5 | GLenum | Yes| -| COLOR_ATTACHMENT6 | GLenum | Yes| -| COLOR_ATTACHMENT7 | GLenum | Yes| -| COLOR_ATTACHMENT8 | GLenum | Yes| -| COLOR_ATTACHMENT9 | GLenum | Yes| -| COLOR_ATTACHMENT10 | GLenum | Yes| -| COLOR_ATTACHMENT11 | GLenum | Yes| -| COLOR_ATTACHMENT12 | GLenum | Yes| -| COLOR_ATTACHMENT13 | GLenum | Yes| -| COLOR_ATTACHMENT14 | GLenum | Yes| -| COLOR_ATTACHMENT15 | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| -| MAX_SAMPLES | GLenum | Yes| -| HALF_FLOAT | GLenum | Yes| -| RG | GLenum | Yes| -| RG_INTEGER | GLenum | Yes| -| R8 | GLenum | Yes| -| RG8 | GLenum | Yes| -| R16F | GLenum | Yes| -| R32F | GLenum | Yes| -| RG16F | GLenum | Yes| -| RG32F | GLenum | Yes| -| R8I | GLenum | Yes| -| R8UI | GLenum | Yes| -| R16I | GLenum | Yes| -| R16UI | GLenum | Yes| -| R32I | GLenum | Yes| -| R32UI | GLenum | Yes| -| RG8I | GLenum | Yes| -| RG8UI | GLenum | Yes| -| RG16I | GLenum | Yes| -| RG16UI | GLenum | Yes| -| RG32I | GLenum | Yes| -| RG32UI | GLenum | Yes| -| VERTEX_ARRAY_BINDING | GLenum | Yes| -| R8_SNORM | GLenum | Yes| -| RG8_SNORM | GLenum | Yes| -| RGB8_SNORM | GLenum | Yes| -| SIGNED_NORMALIZED | GLenum | Yes| -| COPY_READ_BUFFER | GLenum | Yes| -| COPY_WRITE_BUFFER | GLenum | Yes| -| COPY_READ_BUFFER_BINDING | GLenum | Yes| -| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER | GLenum | Yes| -| UNIFORM_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER_START | GLenum | Yes| -| UNIFORM_BUFFER_SIZE | GLenum | Yes| -| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| -| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| -| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| -| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| -| UNIFORM_TYPE | GLenum | Yes| -| UNIFORM_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_INDEX | GLenum | Yes| -| UNIFORM_OFFSET | GLenum | Yes| -| UNIFORM_ARRAY_STRIDE | GLenum | Yes| -| UNIFORM_MATRIX_STRIDE | GLenum | Yes| -| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| -| UNIFORM_BLOCK_BINDING | GLenum | Yes| -| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| -| INVALID_INDEX | GLenum | Yes| -| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| -| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| -| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| -| OBJECT_TYPE | GLenum | Yes| -| SYNC_CONDITION | GLenum | Yes| -| SYNC_STATUS | GLenum | Yes| -| SYNC_FLAGS | GLenum | Yes| -| SYNC_FENCE | GLenum | Yes| -| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| -| UNSIGNALED | GLenum | Yes| -| SIGNALED | GLenum | Yes| -| ALREADY_SIGNALED | GLenum | Yes| -| TIMEOUT_EXPIRED | GLenum | Yes| -| CONDITION_SATISFIED | GLenum | Yes| -| WAIT_FAILED | GLenum | Yes| -| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| -| ANY_SAMPLES_PASSED | GLenum | Yes| -| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| -| SAMPLER_BINDING | GLenum | Yes| -| RGB10_A2UI | GLenum | Yes| -| INT_2_10_10_10_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK | GLenum | Yes| -| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| -| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| -| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| -| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| -| MAX_ELEMENT_INDEX | GLenum | Yes| -| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| -| TIMEOUT_IGNORED | GLint64 | Yes| -| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| +| READ_BUFFER | GLenum | Yes| +| UNPACK_ROW_LENGTH | GLenum | Yes| +| UNPACK_SKIP_ROWS | GLenum | Yes| +| UNPACK_SKIP_PIXELS | GLenum | Yes| +| PACK_ROW_LENGTH | GLenum | Yes| +| PACK_SKIP_ROWS | GLenum | Yes| +| PACK_SKIP_PIXELS | GLenum | Yes| +| COLOR | GLenum | Yes| +| DEPTH | GLenum | Yes| +| STENCIL | GLenum | Yes| +| RED | GLenum | Yes| +| RGB8 | GLenum | Yes| +| RGBA8 | GLenum | Yes| +| RGB10_A2 | GLenum | Yes| +| TEXTURE_BINDING_3D | GLenum | Yes| +| UNPACK_SKIP_IMAGES | GLenum | Yes| +| UNPACK_IMAGE_HEIGHT | GLenum | Yes| +| TEXTURE_3D | GLenum | Yes| +| TEXTURE_WRAP_R | GLenum | Yes| +| MAX_3D_TEXTURE_SIZE | GLenum | Yes| +| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| +| MAX_ELEMENTS_VERTICES | GLenum | Yes| +| MAX_ELEMENTS_INDICES | GLenum | Yes| +| TEXTURE_MIN_LOD | GLenum | Yes| +| TEXTURE_MAX_LOD | GLenum | Yes| +| TEXTURE_BASE_LEVEL | GLenum | Yes| +| TEXTURE_MAX_LEVEL | GLenum | Yes| +| MIN | GLenum | Yes| +| MAX | GLenum | Yes| +| DEPTH_COMPONENT24 | GLenum | Yes| +| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| +| TEXTURE_COMPARE_MODE | GLenum | Yes| +| TEXTURE_COMPARE_FUNC | GLenum | Yes| +| CURRENT_QUERY | GLenum | Yes| +| QUERY_RESULT | GLenum | Yes| +| QUERY_RESULT_AVAILABLE | GLenum | Yes| +| STREAM_READ | GLenum | Yes| +| STREAM_COPY | GLenum | Yes| +| STATIC_READ | GLenum | Yes| +| STATIC_COPY | GLenum | Yes| +| DYNAMIC_READ | GLenum | Yes| +| DYNAMIC_COPY | GLenum | Yes| +| MAX_DRAW_BUFFERS | GLenum | Yes| +| DRAW_BUFFER0 | GLenum | Yes| +| DRAW_BUFFER1 | GLenum | Yes| +| DRAW_BUFFER2 | GLenum | Yes| +| DRAW_BUFFER3 | GLenum | Yes| +| DRAW_BUFFER4 | GLenum | Yes| +| DRAW_BUFFER5 | GLenum | Yes| +| DRAW_BUFFER6 | GLenum | Yes| +| DRAW_BUFFER7 | GLenum | Yes| +| DRAW_BUFFER8 | GLenum | Yes| +| DRAW_BUFFER9 | GLenum | Yes| +| DRAW_BUFFER10 | GLenum | Yes| +| DRAW_BUFFER11 | GLenum | Yes| +| DRAW_BUFFER12 | GLenum | Yes| +| DRAW_BUFFER13 | GLenum | Yes| +| DRAW_BUFFER14 | GLenum | Yes| +| DRAW_BUFFER15 | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| SAMPLER_3D | GLenum | Yes| +| SAMPLER_2D_SHADOW | GLenum | Yes| +| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| +| PIXEL_PACK_BUFFER | GLenum | Yes| +| PIXEL_UNPACK_BUFFER | GLenum | Yes| +| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| +| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| +| FLOAT_MAT2x3 | GLenum | Yes| +| FLOAT_MAT2x4 | GLenum | Yes| +| FLOAT_MAT3x2 | GLenum | Yes| +| FLOAT_MAT3x4 | GLenum | Yes| +| FLOAT_MAT4x2 | GLenum | Yes| +| FLOAT_MAT4x3 | GLenum | Yes| +| SRGB | GLenum | Yes| +| SRGB8 | GLenum | Yes| +| SRGB8_ALPHA8 | GLenum | Yes| +| COMPARE_REF_TO_TEXTURE | GLenum | Yes| +| RGBA32F | GLenum | Yes| +| RGB32F | GLenum | Yes| +| RGBA16F | GLenum | Yes| +| RGB16F | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| +| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| +| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_VARYING_COMPONENTS | GLenum | Yes| +| TEXTURE_2D_ARRAY | GLenum | Yes| +| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| +| R11F_G11F_B10F | GLenum | Yes| +| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| +| RGB9_E5 | GLenum | Yes| +| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| +| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| +| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| +| RASTERIZER_DISCARD | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| +| INTERLEAVED_ATTRIBS | GLenum | Yes| +| SEPARATE_ATTRIBS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| +| RGBA32UI | GLenum | Yes| +| RGB32UI | GLenum | Yes| +| RGBA16UI | GLenum | Yes| +| RGB16UI | GLenum | Yes| +| RGBA8UI | GLenum | Yes| +| RGB8UI | GLenum | Yes| +| RGBA32I | GLenum | Yes| +| RGB32I | GLenum | Yes| +| RGBA16I | GLenum | Yes| +| RGB16I | GLenum | Yes| +| RGBA8I | GLenum | Yes| +| RGB8I | GLenum | Yes| +| RED_INTEGER | GLenum | Yes| +| RGB_INTEGER | GLenum | Yes| +| RGBA_INTEGER | GLenum | Yes| +| SAMPLER_2D_ARRAY | GLenum | Yes| +| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| +| SAMPLER_CUBE_SHADOW | GLenum | Yes| +| UNSIGNED_INT_VEC2 | GLenum | Yes| +| UNSIGNED_INT_VEC3 | GLenum | Yes| +| UNSIGNED_INT_VEC4 | GLenum | Yes| +| INT_SAMPLER_2D | GLenum | Yes| +| INT_SAMPLER_3D | GLenum | Yes| +| INT_SAMPLER_CUBE | GLenum | Yes| +| INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| DEPTH_COMPONENT32F | GLenum | Yes| +| DEPTH32F_STENCIL8 | GLenum | Yes| +| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_DEFAULT | GLenum | Yes| +| UNSIGNED_INT_24_8 | GLenum | Yes| +| DEPTH24_STENCIL8 | GLenum | Yes| +| UNSIGNED_NORMALIZED | GLenum | Yes| +| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| +| READ_FRAMEBUFFER | GLenum | Yes| +| DRAW_FRAMEBUFFER | GLenum | Yes| +| READ_FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_SAMPLES | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| +| MAX_COLOR_ATTACHMENTS | GLenum | Yes| +| COLOR_ATTACHMENT1 | GLenum | Yes| +| COLOR_ATTACHMENT2 | GLenum | Yes| +| COLOR_ATTACHMENT3 | GLenum | Yes| +| COLOR_ATTACHMENT4 | GLenum | Yes| +| COLOR_ATTACHMENT5 | GLenum | Yes| +| COLOR_ATTACHMENT6 | GLenum | Yes| +| COLOR_ATTACHMENT7 | GLenum | Yes| +| COLOR_ATTACHMENT8 | GLenum | Yes| +| COLOR_ATTACHMENT9 | GLenum | Yes| +| COLOR_ATTACHMENT10 | GLenum | Yes| +| COLOR_ATTACHMENT11 | GLenum | Yes| +| COLOR_ATTACHMENT12 | GLenum | Yes| +| COLOR_ATTACHMENT13 | GLenum | Yes| +| COLOR_ATTACHMENT14 | GLenum | Yes| +| COLOR_ATTACHMENT15 | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| +| MAX_SAMPLES | GLenum | Yes| +| HALF_FLOAT | GLenum | Yes| +| RG | GLenum | Yes| +| RG_INTEGER | GLenum | Yes| +| R8 | GLenum | Yes| +| RG8 | GLenum | Yes| +| R16F | GLenum | Yes| +| R32F | GLenum | Yes| +| RG16F | GLenum | Yes| +| RG32F | GLenum | Yes| +| R8I | GLenum | Yes| +| R8UI | GLenum | Yes| +| R16I | GLenum | Yes| +| R16UI | GLenum | Yes| +| R32I | GLenum | Yes| +| R32UI | GLenum | Yes| +| RG8I | GLenum | Yes| +| RG8UI | GLenum | Yes| +| RG16I | GLenum | Yes| +| RG16UI | GLenum | Yes| +| RG32I | GLenum | Yes| +| RG32UI | GLenum | Yes| +| VERTEX_ARRAY_BINDING | GLenum | Yes| +| R8_SNORM | GLenum | Yes| +| RG8_SNORM | GLenum | Yes| +| RGB8_SNORM | GLenum | Yes| +| SIGNED_NORMALIZED | GLenum | Yes| +| COPY_READ_BUFFER | GLenum | Yes| +| COPY_WRITE_BUFFER | GLenum | Yes| +| COPY_READ_BUFFER_BINDING | GLenum | Yes| +| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER | GLenum | Yes| +| UNIFORM_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER_START | GLenum | Yes| +| UNIFORM_BUFFER_SIZE | GLenum | Yes| +| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| +| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| +| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| +| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| +| UNIFORM_TYPE | GLenum | Yes| +| UNIFORM_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_INDEX | GLenum | Yes| +| UNIFORM_OFFSET | GLenum | Yes| +| UNIFORM_ARRAY_STRIDE | GLenum | Yes| +| UNIFORM_MATRIX_STRIDE | GLenum | Yes| +| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| +| UNIFORM_BLOCK_BINDING | GLenum | Yes| +| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| +| INVALID_INDEX | GLenum | Yes| +| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| +| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| +| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| +| OBJECT_TYPE | GLenum | Yes| +| SYNC_CONDITION | GLenum | Yes| +| SYNC_STATUS | GLenum | Yes| +| SYNC_FLAGS | GLenum | Yes| +| SYNC_FENCE | GLenum | Yes| +| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| +| UNSIGNALED | GLenum | Yes| +| SIGNALED | GLenum | Yes| +| ALREADY_SIGNALED | GLenum | Yes| +| TIMEOUT_EXPIRED | GLenum | Yes| +| CONDITION_SATISFIED | GLenum | Yes| +| WAIT_FAILED | GLenum | Yes| +| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| +| ANY_SAMPLES_PASSED | GLenum | Yes| +| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| +| SAMPLER_BINDING | GLenum | Yes| +| RGB10_A2UI | GLenum | Yes| +| INT_2_10_10_10_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK | GLenum | Yes| +| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| +| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| +| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| +| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| +| MAX_ELEMENT_INDEX | GLenum | Yes| +| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| +| TIMEOUT_IGNORED | GLint64 | Yes| +| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| ### Methods -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | -| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | -| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | -| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | -| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | -| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| readBuffer(src: GLenum) | void | -| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | -| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | -| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| getFragDataLocation(program: WebGLProgram, name: string) | GLint | -| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | -| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | -| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | -| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | -| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| vertexAttribI4iv(index: GLuint, values: Int32List) | void | -| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | -| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | -| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | -| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | -| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | -| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | -| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| drawBuffers(buffers: GLenum[]) | void | -| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | -| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | -| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | -| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | -| createQuery() | WebGLQuery \| null | -| deleteQuery(query: WebGLQuery \| null) | void | -| isQuery(query: WebGLQuery \| null) | GLboolean | -| beginQuery(target: GLenum, query: WebGLQuery) | void | -| endQuery(target: GLenum) | void | -| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | -| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | -| createSampler() | WebGLSampler \| null | -| deleteSampler(sampler: WebGLSampler \| null) | void | -| isSampler(sampler: WebGLSampler \| null) | GLboolean | -| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | -| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | -| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | -| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | -| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | -| isSync(sync: WebGLSync \| null) | GLboolean | -| deleteSync(sync: WebGLSync \| null) | void | -| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | -| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | -| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | -| createTransformFeedback() | WebGLTransformFeedback \| null | -| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | -| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | -| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | -| beginTransformFeedback(primitiveMode: GLenum) | void | -| endTransformFeedback() | void | -| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | -| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| pauseTransformFeedback() | void | -| resumeTransformFeedback() | void | -| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | -| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | -| getIndexedParameter(target: GLenum, index: GLuint) | any | -| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | -| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | -| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | -| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | -| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | -| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | -| createVertexArray() | WebGLVertexArrayObject \| null | -| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | -| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | -| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | +| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | +| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | +| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | +| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | +| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | +| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| readBuffer(src: GLenum) | void | +| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | +| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | +| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| getFragDataLocation(program: WebGLProgram, name: string) | GLint | +| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | +| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | +| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | +| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | +| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| vertexAttribI4iv(index: GLuint, values: Int32List) | void | +| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | +| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | +| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | +| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | +| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | +| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | +| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| drawBuffers(buffers: GLenum[]) | void | +| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | +| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | +| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | +| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | +| createQuery() | WebGLQuery \| null | +| deleteQuery(query: WebGLQuery \| null) | void | +| isQuery(query: WebGLQuery \| null) | GLboolean | +| beginQuery(target: GLenum, query: WebGLQuery) | void | +| endQuery(target: GLenum) | void | +| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | +| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | +| createSampler() | WebGLSampler \| null | +| deleteSampler(sampler: WebGLSampler \| null) | void | +| isSampler(sampler: WebGLSampler \| null) | GLboolean | +| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | +| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | +| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | +| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | +| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | +| isSync(sync: WebGLSync \| null) | GLboolean | +| deleteSync(sync: WebGLSync \| null) | void | +| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | +| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | +| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | +| createTransformFeedback() | WebGLTransformFeedback \| null | +| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | +| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | +| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | +| beginTransformFeedback(primitiveMode: GLenum) | void | +| endTransformFeedback() | void | +| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | +| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| pauseTransformFeedback() | void | +| resumeTransformFeedback() | void | +| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | +| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | +| getIndexedParameter(target: GLenum, index: GLuint) | any | +| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | +| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | +| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | +| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | +| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | +| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | +| createVertexArray() | WebGLVertexArrayObject \| null | +| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | +| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | +| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | ## WebGL2RenderingContextOverloads WebGL2RenderingContextOverloads -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | -| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | +| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 92f40c92f26257e614135694d49d69608ea32a23..4a7bee42b6eba3d30626dac89817440efeebff2e 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -1,5 +1,3 @@ - - # @ohos.web.webview (Webview) The **Webview** module provides APIs for web control. @@ -19,6 +17,46 @@ The **Webview** module provides APIs for web control. ```ts import web_webview from '@ohos.web.webview'; ``` + +### once + +once(type: string, callback: Callback\): void + +Registers a one-time callback for web events of the specified type. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | -------------------- | +| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | +| headers | Callback\ | Yes | Callback to register.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +web_webview.once("webInited", () => { + console.log("setCookie") + web_webview.WebCookieManager.setCookie("www.example.com", "a=b") +}) + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebMessagePort Implements a **WebMessagePort** object to send and receive messages. @@ -61,7 +99,7 @@ struct WebComponent { ### postMessageEvent -postMessageEvent(message: string): void +postMessageEvent(message: WebMessage): void Sends a message. For the complete sample code, see [postMessage](#postmessage). @@ -71,7 +109,7 @@ Sends a message. For the complete sample code, see [postMessage](#postmessage). | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :------------- | -| message | string | Yes | Message to send.| +| message | [WebMessage](#webmessage) | Yes | Message to send.| **Error codes** @@ -113,7 +151,7 @@ struct WebComponent { ### onMessageEvent -onMessageEvent(callback: (result: string) => void): void +onMessageEvent(callback: (result: WebMessage) => void): void Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). @@ -123,7 +161,7 @@ Registers a callback to receive messages from the HTML5 side. For the complete s | Name | Type | Mandatory| Description | | -------- | -------- | ---- | :------------------- | -| result | string | Yes | Message received.| +| result | [WebMessage](#webmessage) | Yes | Message received.| **Error codes** @@ -152,7 +190,17 @@ struct WebComponent { try { this.ports = this.controller.createWebMessagePorts(); this.ports[1].onMessageEvent((msg) => { - console.log("received message from html5, on message:" + msg); + if (typeof(msg) == "string") { + console.log("received string message from html5, string is:" + msg); + } else if (typeof(msg) == "object") { + if (msg instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + msg.byteLength); + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } }) } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); @@ -166,13 +214,40 @@ struct WebComponent { ## WebviewController -Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs in the **WebviewController** can be invoked only after it has been bound to the target **\** component. +Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component. + +### initializeWebEngine + +static initializeWebEngine(): void + +Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **\** component is initialized to improve the startup performance. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +The following code snippet exemplifies calling this API after the EntryAbility is created. + +```ts +// xxx.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import web_webview from '@ohos.web.webview'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("EntryAbility onCreate") + web_webview.WebviewController.initializeWebEngine() + globalThis.abilityWant = want + console.log("EntryAbility onCreate done") + } +} +``` ### Creating an Object ```ts // xxx.ets -import web_webview from '@ohos.web.webview' +import web_webview from '@ohos.web.webview'; @Entry @Component @@ -1397,8 +1472,21 @@ struct WebComponent { // 2. Send one of the message ports to the HTML side, which can then save and use the port. this.controller.postMessage('__init_port__', [this.ports[0]], '*'); // 3. Register a callback for the other message port on the application side. - this.ports[1].onMessageEvent((result: string) => { - var msg = 'Got msg from HTML: ' + result; + this.ports[1].onMessageEvent((result: WebMessage) => { + var msg = 'Got msg from HTML:'; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } this.receivedFromHtml = msg; }) } catch (error) { @@ -1456,7 +1544,21 @@ window.addEventListener('message', function (event) { The h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. h5Port.onmessage = function (event) { // 2. Receive the message sent from the eTS side. - var msg = 'Got message from ets:' + event.data; + var msg = 'Got message from ets:'; + var result = event.data; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } output.innerHTML = msg; } } @@ -1759,7 +1861,7 @@ struct WebComponent { getTitle(): string -Obtains the title of the file selector. +Obtains the title of the current web page. **System capability**: SystemCapability.Web.Webview.Core @@ -1767,7 +1869,7 @@ Obtains the title of the file selector. | Type | Description | | ------ | -------------------- | -| string | Title of the file selector.| +| string | Title of the current web page.| **Error codes** @@ -2123,6 +2225,222 @@ struct WebComponent { } ``` +### scrollTo + +scrollTo(x:number, y:number): void + +Scrolls the page to the specified absolute position. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| +| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollTo') + .onClick(() => { + try { + this.controller.scrollTo(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### scrollBy + +scrollBy(deltaX:number, deltaY:number): void + +Scrolls the page by the specified amount. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| +| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollBy') + .onClick(() => { + try { + this.controller.scrollBy(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### slideScroll + +slideScroll(vx:number, vy:number): void + +Simulates a slide-to-scroll action on the page at the specified velocity. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| +| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('slideScroll') + .onClick(() => { + try { + this.controller.slideScroll(500, 500); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + ### getOriginalUrl getOriginalUrl(): string @@ -2244,7 +2562,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 401 | Invalid input parameter. | **Example** @@ -2275,7 +2592,7 @@ struct WebComponent { ### hasImage -hasImage(callback: AsyncCallback): void +hasImage(callback: AsyncCallback\): void Checks whether this page contains images. This API uses an asynchronous callback to return the result. @@ -2294,7 +2611,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 401 | Invalid input parameter. | **Example** @@ -2312,7 +2628,7 @@ struct WebComponent { Button('hasImageCb') .onClick(() => { try { - this.controller.hasImage((err, data) => { + this.controller.hasImage((error, data) => { if (error) { console.info(`hasImage error: ` + JSON.stringify(error)) return; @@ -2331,7 +2647,7 @@ struct WebComponent { ### hasImage -hasImage(): Promise +hasImage(): Promise\ Checks whether this page contains images. This API uses a promise to return the result. @@ -2350,7 +2666,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 401 | Invalid input parameter. | **Example** @@ -2396,7 +2711,7 @@ Clears the cache in the application. This API will clear the cache for all webvi | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------------------------- | -| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **false** means to only clear the cache in the RAM.| +| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.| **Error codes** @@ -2405,7 +2720,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | -| 401 | Invalid input parameter. | **Example** @@ -2483,9 +2797,58 @@ struct WebComponent { } ``` +### customizeSchemes + +static customizeSchemes(schemes: Array\): void + +Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\** component is initialized. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------- | +| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + responseweb: WebResourceResponse = new WebResourceResponse() + scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} + scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} + scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} + + aboutToAppear():void { + try { + web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) + } catch(error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + } + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + return this.responseweb + }) + } + } +} +``` + ## WebCookieManager -Implements a **WebCookie** object to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookie** object. +Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. ### getCookie @@ -3600,7 +3963,7 @@ Implements a **WebAsyncController** object, which can be used to control the beh @Component struct WebComponent { controller: WebController = new WebController(); - webAsyncController: WebAsyncController = new web_webview.WebAsyncController(this.controller) + webAsyncController: web_webview.WebAsyncController = new web_webview.WebAsyncController(this.controller) build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) @@ -3635,8 +3998,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | | callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.| **Example** @@ -3677,14 +4040,14 @@ Stores this web page. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise | Promise used to return the save path if the operation is successful and null otherwise.| +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the save path if the operation is successful and null otherwise. | **Example** @@ -4100,6 +4463,15 @@ Provides the element information of the area being clicked. For details about th | type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.| | extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.| +## WebMessage + +Describes the data types supported for [WebMessagePort](#webmessageport). + +| Type | Description | +| -------- | -------------------------------------- | +| string | String type.| +| ArrayBuffer | Binary type.| + ## WebStorageOrigin Provides usage information of the Web SQL Database. @@ -4143,14 +4515,6 @@ Obtains the page record with the specified index in the history stack. | --------------------------- | ------------ | | [HistoryItem](#historyitem) | Historical page record.| -**Error codes** - -For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). - -| ID| Error Message | -| -------- | ----------------------- | -| 401 | Invalid input parameter | - **Example** ```ts @@ -4172,7 +4536,7 @@ struct WebComponent { let list = this.controller.getBackForwardEntries(); let historyItem = list.getItemAtIndex(list.currentIndex); console.log("HistoryItem: " + JSON.stringify(historyItem)); - this.icon = item.icon; + this.icon = historyItem.icon; } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -4196,4 +4560,14 @@ Describes a historical page record. | historyRawUrl | string | Yes | No | Original URL of the historical page. | | title | string | Yes | No | Title of the historical page. | -### +## WebCustomScheme + +Defines a custom URL scheme. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| -------------- | --------- | ---- | ---- | ---------------------------- | +| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). | +| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | +| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 523758e9caf5ffcba94df7e7efc6756bb5d1fa28..bc1ad05712b63c8b2d990af46c8bf70242134e77 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -248,7 +248,7 @@ Enumerates the color spaces. | Name | Value| Description | | ---------- | ------ | -------------- | -| DEFAULT | 0 | Default gamut.| +| DEFAULT | 0 | Default SRGB gamut.| | WIDE_GAMUT | 1 | Wide-gamut. | ## ScaleOptions9+ @@ -1544,6 +1544,8 @@ moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void Moves this window. This API uses an asynchronous callback to return the result. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1585,6 +1587,8 @@ moveWindowTo(x: number, y: number): Promise<void> Moves this window. This API uses a promise to return the result. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1636,6 +1640,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1683,6 +1689,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1856,7 +1864,7 @@ Obtains the area where this window cannot be displayed, for example, the system | Name| Type| Mandatory| Description| | ---- |----------------------------------| -- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| +| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. | **Return value** @@ -2492,7 +2500,7 @@ Disables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | -------------------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| -| callback | Callback<[Size](#size)> | No | Callback used to return the window size. | +| callback | Callback<[Size](#size7)> | No | Callback used to return the window size. | **Example** @@ -2998,7 +3006,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re | Name| Type| Mandatory| Description| | ---------- | ------------------------- | -- | ----------- | -| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| +| colorSpace | [ColorSpace](#colorspace8) | Yes| Color space to set.| | callback | AsyncCallback<void> | Yes| Callback used to return the result. | **Error codes** @@ -3037,7 +3045,7 @@ Sets a color space for this window. This API uses a promise to return the result | Name| Type| Mandatory| Description| | ---------- | ------------------------- | -- | ------------- | -| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| +| colorSpace | [ColorSpace](#colorspace8) | Yes| Color space to set.| **Return value** @@ -3080,7 +3088,7 @@ Obtains the color space of this window. | Type| Description| | ------------------------- | ------------- | -| [ColorSpace](#colorspace) | Color space obtained.| +| [ColorSpace](#colorspace8) | Color space obtained.| **Error codes** @@ -3721,6 +3729,41 @@ try { ### snapshot9+ +snapshot(callback: AsyncCallback<image.PixelMap>): void + +Captures this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ----------------------------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +windowClass.snapshot((err, pixelMap) => { + if (err.code) { + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}); +``` + +### snapshot9+ + snapshot(): Promise<image.PixelMap> Captures this window. This API uses a promise to return the result. @@ -4041,6 +4084,7 @@ try { } catch (exception) { console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception)); } + ``` ### setBackdropBlurStyle9+ @@ -4282,6 +4326,8 @@ moveTo(x: number, y: number, callback: AsyncCallback<void>): void Moves this window. This API uses an asynchronous callback to return the result. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9) instead. @@ -4315,6 +4361,8 @@ moveTo(x: number, y: number): Promise<void> Moves this window. This API uses a promise to return the result. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9-1) instead. @@ -4358,6 +4406,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9) instead. @@ -4397,6 +4447,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9-1) instead. @@ -4579,7 +4631,7 @@ Obtains the area where this window cannot be displayed, for example, the system | Name | Type | Mandatory | Description | | -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | | callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** @@ -4612,7 +4664,7 @@ Obtains the area where this window cannot be displayed, for example, the system | Name | Type | Mandatory | Description | | ---- | -------------------------------- | --------- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. | **Return value** @@ -5187,7 +5239,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re | Name | Type | Mandatory | Description | | ---------- | ------------------------- | --------- | ----------------------------------- | -| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | +| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -5219,7 +5271,7 @@ Sets a color space for this window. This API uses a promise to return the result | Name | Type | Mandatory | Description | | ---------- | ------------------------- | --------- | ------------------- | -| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | +| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. | **Return value** @@ -5255,7 +5307,7 @@ Obtains the color space of this window. This API uses an asynchronous callback t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. | +| callback | AsyncCallback<[ColorSpace](#colorspace8)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. | **Example** @@ -5286,7 +5338,7 @@ Obtains the color space of this window. This API uses a promise to return the re | Type | Description | | ---------------------------------------- | ----------------------------------------------- | -| Promise<[ColorSpace](#colorspace)> | Promise used to return the current color space. | +| Promise<[ColorSpace](#colorspace8)> | Promise used to return the current color space. | **Example** @@ -5864,12 +5916,12 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Value | Description | -| ---------- | ----- | ---------------------------------------------- | -| FOREGROUND | 1 | The window stage is running in the foreground. | -| ACTIVE | 2 | The window stage gains focus. | -| INACTIVE | 3 | The window stage loses focus. | -| BACKGROUND | 4 | The window stage is running in the background. | +| Name | Value | Description | +| -------- | ----- | ---------------------------------------------- | +| SHOWN | 1 | The window stage is running in the foreground. | +| ACTIVE | 2 | The window stage gains focus. | +| INACTIVE | 3 | The window stage loses focus. | +| HIDDEN | 4 | The window stage is running in the background. | ## WindowStage9+ @@ -5905,9 +5957,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -5952,9 +6006,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -5998,9 +6054,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6042,9 +6100,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6100,9 +6160,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6149,9 +6211,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6195,9 +6259,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6243,9 +6309,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); @@ -6302,9 +6370,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); @@ -6354,9 +6424,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6404,9 +6476,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6452,9 +6526,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6492,9 +6568,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('disableWindowDecor'); windowStage.disableWindowDecor(); @@ -6533,9 +6611,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6659,6 +6739,7 @@ controller.animationForShown = (context : window.TransitionContext) => { ); console.info('complete transition end'); }; + ``` ### animationForHidden9+ @@ -6705,5 +6786,4 @@ controller.animationForHidden = (context : window.TransitionContext) => { ) console.info('complete transition end'); }; -``` - +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md index 46d23a02136a6d042b3f05fb335d5bd620dfd82f..ffae7ffbf0941f4aa79fb0335b853fc281e66476 100644 --- a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -1,4 +1,5 @@ -# Window Animation Management +# @ohos.animation.windowAnimationManager (Window Animation Management) + The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 1b269ea33508c427b9480641ee08210b7906eddc..db8a73c0ff0b29ca6c753073f8ea0d297b19ccb8 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,9 +1,11 @@ -# @ohos.worker +# @ohos.worker (Worker Startup) The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. With the **Worker** module, you can provide a multithreading environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the main thread. A **Worker** instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner. +The **Context** object of the worker thread is different from that of the main thread. The worker thread does not support UI operations. + > **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. @@ -40,13 +42,13 @@ Provides options that can be set for the **Worker** instance to create. ## ThreadWorker9+ -Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [WorkerEventTarget](#workereventtarget9). +Before using the following APIs, you must create a **ThreadWorker** instance. The **ThreadWorker** class inherits from [WorkerEventTarget](#workereventtarget9). ### constructor9+ constructor(scriptURL: string, options?: WorkerOptions) -A constructor used to create a **Worker** instance. +A constructor used to create a **ThreadWorker** instance. **System capability**: SystemCapability.Utils.Lang @@ -59,9 +61,20 @@ A constructor used to create a **Worker** instance. **Return value** -| Type | Description | -| ------ | --------------------------------------------------------- | -| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.| +| Type | Description | +| ------------ | ------------------------------------------------------------ | +| ThreadWorker | Returns the **ThreadWorker** instance created; returns **undefined** if the **ThreadWorker** instance fails to be created.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200003 | Worker initialization failure. | +| 10200007 | The worker file patch is invalid path. | + + **Example** @@ -94,7 +107,7 @@ In the FA model: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -138,6 +151,40 @@ In the stage model: } ``` +### postMessage9+ + +postMessage(message: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); + +workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); +``` ### postMessage9+ @@ -154,6 +201,15 @@ Sends a message to the worker thread. The data type of the message must be seque | message | Object | Yes | Message to be sent to the worker thread. | | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + **Example** ```js @@ -165,7 +221,6 @@ var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` - ### on9+ on(type: string, listener: WorkerEventListener): void @@ -181,6 +236,15 @@ Adds an event listener for the worker thread. This API provides the same functio | type | string | Yes | Type of the event to listen for. | | listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -206,6 +270,15 @@ Adds an event listener for the worker thread and removes the event listener afte | type | string | Yes | Type of the event to listen for. | | listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -231,6 +304,15 @@ Removes an event listener for the worker thread. This API provides the same func | type | string | Yes | Type of the event for which the event listener is to be removed. | | listener | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -248,6 +330,14 @@ Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -270,6 +360,15 @@ Defines the event handler to be called when the worker thread exits. The handler | ------ | ------ | ---- | ------------------ | | code | number | Yes | Code indicating the worker thread exit state.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -301,6 +400,15 @@ Defines the event handler to be called when an exception occurs during worker ex | ------ | ------------------------- | ---- | ---------- | | err | [ErrorEvent](#errorevent) | Yes | Error data.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -325,6 +433,15 @@ Defines the event handler to be called when the host thread receives a message s | ------ | -------------------------------- | ---- | ---------------------- | | event | [MessageEvents](#messageevents9) | Yes | Message received.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -351,6 +468,15 @@ Defines the event handler to be called when the worker thread receives a message | ------ | -------------------------------- | ---- | ---------- | | event | [MessageEvents](#messageevents9) | Yes | Error data.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -360,6 +486,169 @@ workerInstance.onmessageerror= function(e) { } ``` +### addEventListener9+ + +addEventListener(type: string, listener: WorkerEventListener): void + +Adds an event listener for the worker thread. This API provides the same functionality as [on9+](#on9). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ---------------- | +| type | string | Yes | Type of the event to listen for.| +| listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +``` + + +### removeEventListener9+ + +removeEventListener(type: string, callback?: WorkerEventListener): void + +Removes an event listener for the worker thread. This API provides the same functionality as [off9+](#off9). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ---------------------------- | +| type | string | Yes | Type of the event for which the event listener is to be removed. | +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.removeEventListener("alert"); +``` + + +### dispatchEvent9+ + +dispatchEvent(event: Event): boolean + +Dispatches the event defined for the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------- | ---- | ---------------- | +| event | [Event](#event) | Yes | Event to dispatch.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------- | +| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) + +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); +``` + + +### removeAllListener9+ + +removeAllListener(): void + +Removes all event listeners for the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.removeAllListener(); +``` ## WorkerEventTarget9+ @@ -378,6 +667,15 @@ Adds an event listener for the worker thread. This API provides the same functio | type | string | Yes | Type of the event to listen for.| | listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -401,7 +699,15 @@ Removes an event listener for the worker thread. This API provides the same func | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ---------------------------- | | type | string | Yes | Type of the event for which the event listener is to be removed. | -| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | **Example** @@ -434,6 +740,14 @@ Dispatches the event defined for the worker thread. | ------- | ------------------------------- | | boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -450,11 +764,11 @@ workerInstance.addEventListener("alert_add", (e)=>{ }) // The event listener created by once is removed after being executed once. -workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); -// The event listener created by on will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will be always valid and will not be proactively deleted. +// The event listener created by addEventListener will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); @@ -484,6 +798,14 @@ Removes all event listeners for the worker thread. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -499,6 +821,53 @@ workerInstance.removeAllListener(); Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **ThreadWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). +### postMessage9+ + +postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the host thread from the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + +**Example** + +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = function(e) { + // let data = e.data; + console.log("receive data from worker.js"); +} +``` + +```js +// worker.js +import worker from '@ohos.worker'; +const workerPort = worker.workerPort; +workerPort.onmessage = function(e){ + // let data = e.data; + var buffer = new ArrayBuffer(8); + workerPort.postMessage(buffer, [buffer]); +} +``` ### postMessage9+ @@ -515,6 +884,15 @@ Sends a message to the host thread from the worker thread. | message | Object | Yes | Message to be sent to the worker thread. | | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + **Example** ```js @@ -531,10 +909,10 @@ workerInstance.onmessage = function(e) { ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e){ +const workerPort = worker.workerPort; +workerPort.onmessage = function(e){ // let data = e.data; - parentPort.postMessage("receive data from main.js"); + workerPort.postMessage("receive data from main.js"); } ``` @@ -547,6 +925,14 @@ Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -558,16 +944,16 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e) { - parentPort.close() +const workerPort = worker.workerPort; +workerPort.onmessage = function(e) { + workerPort.close() } ``` ### onmessage9+ -onmessage?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void +onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. @@ -578,7 +964,16 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ------------------------ | | this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | -| event | [MessageEvents](#messageevents9) | Yes | Message received.| +| ev | [MessageEvents](#messageevents9) | Yes | Message received.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -592,8 +987,8 @@ workerInstance.postMessage("hello world"); ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e) { +const workerPort = worker.workerPort; +workerPort.onmessage = function(e) { console.log("receive main.js message"); } ``` @@ -601,7 +996,7 @@ parentPort.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (this: ThreadWorkerGlobalScope, event: MessageEvents) => void +onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. @@ -612,7 +1007,16 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | -------------------------------- | ---- | ---------- | | this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | -| event | [MessageEvents](#messageevents9) | Yes | Error data.| +| ev | [MessageEvents](#messageevents9) | Yes | Error data.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -652,6 +1056,15 @@ Implements event listening. | ------------------------------------- | ------------------------------- | | void \| Promise<void> | Returns no value or returns a **Promise**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -701,8 +1114,8 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js") ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort -parentPort.onerror = function(e){ +const workerPort = worker.workerPort +workerPort.onerror = function(e){ console.log("worker.js onerror") } ``` @@ -779,7 +1192,7 @@ In the FA model: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -816,9 +1229,10 @@ In the stage model: } } ``` + ### postMessage(deprecated) -postMessage(message: Object, options?: PostMessageOptions): void +postMessage(message: Object, transfer: ArrayBuffer[]): void; Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). @@ -829,6 +1243,35 @@ Sends a message to the worker thread. The data type of the message must be seque **Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instances that can be transferred.| + +**Example** + +```js +const workerInstance = new worker.Worker("workers/worker.js"); + +workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); +``` + +### postMessage(deprecated) + +postMessage(message: Object, options?: PostMessageOptions): void + +Sends a message to the worker thread. The data type of the message must be sequenceable. For details about the sequenceable data types, see [More Information](#more-information). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9-1) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | message | Object | Yes | Message to be sent to the worker thread. | @@ -840,9 +1283,6 @@ Sends a message to the worker thread. The data type of the message must be seque const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.postMessage("hello world"); - -var buffer = new ArrayBuffer(8); -workerInstance.postMessage(buffer, [buffer]); ``` @@ -1024,7 +1464,7 @@ Defines the event handler to be called when the host thread receives a message s | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------------------- | -| event | [MessageEvent](#messageeventt) | Yes | Message received.| +| event | [MessageEvent](#messageevent)| Yes | Message received.| **Example** @@ -1053,7 +1493,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | -| event | [MessageEvent](#messageeventt) | Yes | Error data.| +| event | [MessageEvent](#messageevent)| Yes | Error data.| **Example** @@ -1166,7 +1606,7 @@ workerInstance.addEventListener("alert_add", (e)=>{ }) // The event listener created by once is removed after being executed once. -workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. // The event listener created by on will not be proactively deleted. workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); @@ -1219,6 +1659,44 @@ Implements communication between the worker thread and the host thread. The **po > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. +### postMessage9+ + +postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the host thread from the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Example** + +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = function(e) { + // let data = e.data; + console.log("receive data from worker.js"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort; +parentPort.onmessage = function(e){ + // let data = e.data; + let buffer = new ArrayBuffer(5) + parentPort.postMessage(buffer, [buffer]); +} +``` + ### postMessage(deprecated) postMessage(messageObject: Object, options?: PostMessageOptions): void @@ -1259,7 +1737,6 @@ parentPort.onmessage = function(e){ } ``` - ### close(deprecated) close(): void @@ -1290,7 +1767,7 @@ parentPort.onmessage = function(e) { ### onmessage(deprecated) -onmessage?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void +onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **postMessage**. The event handler is executed in the worker thread. @@ -1304,7 +1781,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | -| event | [MessageEvent](#messageeventt) | Yes | Message received.| +| ev | [MessageEvent](#messageevent) | Yes | Message received.| **Example** @@ -1326,7 +1803,7 @@ parentPort.onmessage = function(e) { ### onmessageerror(deprecated) -onmessageerror?: (this: DedicatedWorkerGlobalScope, event: MessageEvent) => void +onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. @@ -1340,7 +1817,7 @@ Defines the event handler to be called when the worker thread receives a message | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ---------- | | this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| -| event | [MessageEvent](#messageeventt) | Yes | Error data.| +| ev | [MessageEvent](#messageevent)| Yes | Error data.| **Example** @@ -1376,10 +1853,10 @@ Defines the event. **System capability**: SystemCapability.Utils.Lang -| Name | Type | Readable| Writable| Description | -| --------- | ------ | ---- | ---- | ---------------------------------- | -| type | string | Yes | No | Type of the event. | -| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | -------------------------------------------- | +| type | string | Yes | No | Type of the event. | +| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created. This parameter is not supported yet.| ## EventListener(deprecated) @@ -1525,14 +2002,14 @@ workerInstance.onmessage = function(d) { ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; +const workerPort = worker.workerPort; class MyModel { name = "undefined" Init() { this.name = "MyModel" } } -parentPort.onmessage = function(d) { +workerPort.onmessage = function(d) { console.log("worker.js onmessage"); let data = d.data; let func1 = function() { @@ -1546,14 +2023,14 @@ parentPort.onmessage = function(d) { } } let obj2 = new MyModel(); - // parentPort.postMessage(func1); A serialization error occurs when passing func1. - // parentPort.postMessage(obj1); A serialization error occurs when passing obj1. - parentPort.postMessage(obj2); // No serialization error occurs when passing obj2. + // workerPort.postMessage(func1); A serialization error occurs when passing func1. + // workerPort.postMessage(obj1); A serialization error occurs when passing obj1. + workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. } -parentPort.onmessageerror = function(e) { +workerPort.onmessageerror = function(e) { console.log("worker.js onmessageerror"); } -parentPort.onerror = function(e) { +workerPort.onerror = function(e) { console.log("worker.js onerror"); } ``` @@ -1571,6 +2048,7 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. - Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). +- When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file. ## Sample Code > **NOTE**
@@ -1611,23 +2089,23 @@ workerInstance.onexit = function() { import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. -const parentPort = worker.workerPort +const workerPort = worker.workerPort // In versions earlier than API version 9, use the following to create an object in the worker thread for communicating with the main thread. // const parentPort = worker.parentPort // The worker thread receives information from the main thread. -parentPort.onmessage = function(e) { +workerPort.onmessage = function(e) { // data carries the information sent by the main thread. let data = e.data; console.log("worker.ts onmessage"); // The worker thread sends information to the main thread. - parentPort.postMessage("123") + workerPort.postMessage("123") } // Trigger a callback when an error occurs in the worker thread. -parentPort.onerror= function(e) { +workerPort.onerror= function(e) { console.log("worker.ts onerror"); } ``` @@ -1636,7 +2114,7 @@ Configuration of the **build-profile.json5** file: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -1673,20 +2151,20 @@ workerInstance.onexit = function() { import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. -const parentPort = worker.workerPort +const workerPort = worker.workerPort // The worker thread receives information from the main thread. -parentPort.onmessage = function(e) { +workerPort.onmessage = function(e) { // data carries the information sent by the main thread. let data = e.data; console.log("worker.ts onmessage"); // The worker thread sends information to the main thread. - parentPort.postMessage("123") + workerPort.postMessage("123") } // Trigger a callback when an error occurs in the worker thread. -parentPort.onerror= function(e) { +workerPort.onerror= function(e) { console.log("worker.ts onerror"); } ``` diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index ec3549a4051ea6784a56be33c902fc167e1311a1..2f793c39a2234eb16b30d634d53279d1b1c70de3 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -32,9 +32,16 @@ A constructor used to create an **XmlSerializer** instance. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(2048); +let thatSer = new xml.XmlSerializer(arrayBuffer,"utf-8"); +thatSer.setDeclaration(); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -56,12 +63,19 @@ Sets an attribute. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); -thatSer.setAttributes("importance", "high"); -thatSer.endElement(); +thatSer.setAttributes("importance1", "high1"); +thatSer.endElement(); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -82,10 +96,17 @@ Adds an empty element. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.addEmptyElement("b"); // => +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.addEmptyElement("d"); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -100,10 +121,20 @@ Sets a declaration. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.setDeclaration() // => ; +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -124,13 +155,22 @@ Writes the start tag based on the given element name. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.startElement("notel"); -thatSer.endElement();// => ''; +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` - ### endElement endElement(): void @@ -142,14 +182,20 @@ Writes the end tag of the element. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); -thatSer.startElement("table"); -thatSer.setAttributes("importance", "high"); -thatSer.setText("Happy"); -thatSer.endElement(); // => Happy +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` @@ -171,12 +217,20 @@ Sets the namespace for an element tag. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDeclaration(); -thatSer.setNamespace("h", "https://www.w3.org/TR/html4/"); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("note"); -thatSer.endElement();// = >'\r\n'; +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` ### setComment @@ -196,11 +250,17 @@ Sets the comment. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.startElement("note"); -thatSer.setComment("Hi!"); -thatSer.endElement(); // => '\r\n \r\n'; +thatSer.setComment("Hello, World!"); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //' ``` @@ -221,9 +281,17 @@ Sets CDATA attributes. **Example** ```js -let arrayBuffer = new ArrayBuffer(1028); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.setCDATA('root SYSTEM') // => ''; +thatSer.setCDATA('root SYSTEM') +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //''' ``` @@ -244,12 +312,20 @@ Sets **Text**. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy1"); -thatSer.endElement(); // => 'Happy1'; +thatSer.endElement(); +let result = 'Happy1'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // 'Happy1' ``` @@ -270,9 +346,17 @@ Sets **DocType**. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.setDocType('root SYSTEM'); // => ''; +thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //'' ``` @@ -298,19 +382,40 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa ```js let strXml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; + '' + + ']>' + + '' + + ' ' + + ' ' + + ' John & Hans' + + ' Happy' + + ' Happy' + + ' Work' + + ' Play' + + ' ' + + ' ' + + ' ' + + ' ' + + ' Apples' + + ' Bananas' + + ' ' + + ' ' + + ''; let arrayBuffer = new ArrayBuffer(strXml.length); let bufView = new Uint8Array(arrayBuffer); let strLen = strXml.length; -for (var i = 0; i < strLen; ++i) { - bufView[i] = strXml.charCodeAt(i);// Set the ArrayBuffer mode. +for (let i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i); } -let that = new xml.XmlPullParser(arrayBuffer); +let that = new xml.XmlPullParser(arrayBuffer, 'UTF-8'); +let str1 = ''; +function func1(name, value){ + str1 += name+':'+value; + return true; +} +let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func1} +that.parse(options); +console.log(str1) //'note:company:title:title:lens:lens:a:b:h:table:h:tr:h:td:h:td:' ``` @@ -341,7 +446,7 @@ let strXml = let arrayBuffer = new ArrayBuffer(strXml.length); let bufView = new Uint8Array(arrayBuffer); let strLen = strXml.length; -for (var tmp = 0; tmp < strLen; ++tmp) { +for (let tmp = 0; tmp < strLen; ++tmp) { bufView[tmp] = strXml.charCodeAt(tmp); } let that = new xml.XmlPullParser(arrayBuffer); @@ -399,6 +504,38 @@ Obtains the column line number, starting from 1. | ------ | -------------- | | number | Column number obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getColumnNumber(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:1key:2 value:77key:10 value:81key:2 value:88key:4 value:93key:3 value:101key:10 value:105key:2 value:111key:4 value:115key:3 value:122key:10 value:126key:2 value:132key:4 value:136key:3 value:143key:3 value:150key:1 value:299 +``` ### getDepth @@ -414,6 +551,41 @@ Obtains the depth of this element. | ------ | -------------------- | | number | Depth obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:1key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:3 value:1key:1 value:0 +// Note: +// key indicates the event type, and value indicates the parsing depth. You can learn the specific parsed event based on EVENTTYPE. In this example, key: value means: +// 0(START_DOCUMENT):0 (START_DOCUMENT is being parsed, and the depth is 0), 2(START_TAG):1 (START_TAG is being parsed, and the depth is 1), 10(WHITESPACE):1 (WHITESPACE is being parsed, and the depth is 1), 2(START_TAG):2 (START_TAG is being parsed, and the depth is 2), ... +``` ### getLineNumber @@ -429,6 +601,38 @@ Obtains the current line number, starting from 1. | ------ | -------------- | | number | Line number obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getLineNumber(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:1key:2 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:3 value:1key:1 value:1 +``` ### getName @@ -444,7 +648,38 @@ Obtains the name of this element. | ------ | ------------------ | | string | Element name obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getName(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:notekey:10 value:key:2 value:titlekey:4 value:key:3 value:titlekey:10 value:key:2 value:todokey:4 value:key:3 value:todokey:10 value:key:2 value:todokey:4 value:key:3 value:todokey:3 value:notekey:1 value: +``` ### getNamespace getNamespace(): string @@ -459,7 +694,38 @@ Obtains the namespace of this element. | ------ | ------------------------ | | string | Namespace obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getNamespace(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:3 value:key:1 value: +``` ### getPrefix getPrefix(): string @@ -474,6 +740,38 @@ Obtains the prefix of this element. | ------ | ------------------ | | string | Element prefix obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getPrefix(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:3 value:key:1 value: +``` ### getText @@ -489,7 +787,38 @@ Obtains the text of the current event. | ------ | ------------------------ | | string | Text content obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getText(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value: key:2 value:key:4 value:Happykey:3 value:key:10 value: key:2 value:key:4 value:Workkey:3 value:key:10 value: key:2 value:key:4 value:Playkey:3 value:key:3 value:key:1 value: +``` ### isEmptyElementTag isEmptyElementTag(): boolean @@ -504,7 +833,38 @@ Checks whether the current element is empty. | ------- | ---------------------------- | | boolean | Returns **true** if the element is empty; returns **false** otherwise.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.isEmptyElementTag(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:falsekey:2 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:3 value:falsekey:1 value:false +``` ### isWhitespace isWhitespace(): boolean @@ -519,7 +879,38 @@ Checks whether the current text event contains only whitespace characters. | ------- | -------------------------------------- | | boolean | Returns **true** if the text event contains only whitespace characters; returns **false** otherwise.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.isWhitespace(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:truekey:2 value:falsekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:3 value:truekey:1 value:true +``` ### getAttributeCount getAttributeCount(): number @@ -533,6 +924,38 @@ Obtains the number of attributes for the current start tag. | ------ | ---------------------- | | number | Number of attributes obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getAttributeCount(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:2key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:3 value:0key:1 value:0 +``` ## EventType diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index aa7d700534b09bb582ca96d61740fdd6ff9681b9..8ab71a62ddea41f2ffd92fd323fd46eada2614ad 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,6 +1,6 @@ -# @ohos.zlib +# @ohos.zlib (Zip) -The **zlib** module provides APIs for file compression and decompression. +The **Zip** module provides APIs for file compression and decompression. > **NOTE** > @@ -25,7 +25,7 @@ Zips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | | options | [Options](#options) | Yes | Optional parameters for the zip operation. | @@ -39,6 +39,7 @@ Zips a file. This API uses a promise to return the result. ```typescript // Zip a file. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -59,6 +60,7 @@ zlib.zipFile(inFile, outFile, options).then((data) => { ```typescript // Zip a folder. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/xxx'; let outFile = '/xxx/xxx.zip'; @@ -89,7 +91,7 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options) | Yes | Optional parameters for the unzip operation. | @@ -103,6 +105,7 @@ Unzips a file. This API uses a promise to return the result. ```typescript // Unzip a file. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -131,7 +134,7 @@ Compresses a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -141,14 +144,14 @@ Compresses a file. This API uses an asynchronous callback to return the result. For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). | ID| Error Message | | -------- | --------------------------------------| -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | **Example** ```typescript // Compress a file. -// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -179,7 +182,7 @@ Compresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | @@ -189,12 +192,12 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod | ID| Error Message | | -------- | ------------------------------------- | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | ```typescript // Compress a file. -// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -229,7 +232,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | @@ -240,14 +243,14 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod | ID| Error Message | -------- | --------------------------------------| -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | **Example** ```typescript // Decompress a file. -// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -270,7 +273,7 @@ try { decompressFile(inFile: string, outFile: string, options: Options): Promise\; -Decompress a file. This API uses a promise to return the result. +Decompresses a file. This API uses a promise to return the result. **System capability**: SystemCapability.BundleManager.Zlib @@ -278,7 +281,7 @@ Decompress a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-inner-app-context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | @@ -288,12 +291,12 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod | ID| Error Message | | ------ | ------------------------------------- | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | ```typescript // Decompress a file. -// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; diff --git a/en/application-dev/reference/arkui-js/Readme-EN.md b/en/application-dev/reference/arkui-js/Readme-EN.md index d14e06d8a3a83329a2a6e2b508508e03c93aea4c..c46abd3bd91d1acbf99bb15152d3f55f636483eb 100644 --- a/en/application-dev/reference/arkui-js/Readme-EN.md +++ b/en/application-dev/reference/arkui-js/Readme-EN.md @@ -96,10 +96,9 @@ - Custom Components - [Basic Usage](js-components-custom-basic-usage.md) - - [Style Inheritance](js-components-custom-style.md) - - [Custom Events](js-components-custom-events.md) - [props](js-components-custom-props.md) - - [Event Parameter](js-components-custom-event-parameter.md) + - [Style Inheritance](js-components-custom-style.md) - [slot](js-components-custom-slot.md) - [Lifecycle Definition](js-components-custom-lifecycle.md) -- [Data Type Attributes](js-appendix-types.md) +- [Dynamic Component Creation](js-components-create-elements.md) +- [Data Type Attributes](js-appendix-types.md) diff --git a/en/application-dev/reference/arkui-js/figures/en-us-attributes.gif b/en/application-dev/reference/arkui-js/figures/en-us-attributes.gif new file mode 100644 index 0000000000000000000000000000000000000000..77a11bb928c4b0d6e66073dd844320fc4e10229c Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us-attributes.gif differ diff --git a/en/application-dev/reference/arkui-js/figures/en-us_image1.png b/en/application-dev/reference/arkui-js/figures/en-us_image1.png new file mode 100644 index 0000000000000000000000000000000000000000..971b33355ee838054f24e2a7005c3ef3906a24d1 Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/en-us_image1.png differ diff --git a/en/application-dev/reference/arkui-js/figures/animate-4.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125126.gif similarity index 100% rename from en/application-dev/reference/arkui-js/figures/animate-4.gif rename to en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125126.gif diff --git a/en/application-dev/reference/arkui-js/en-us_image_0000001127284938.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284938.gif similarity index 100% rename from en/application-dev/reference/arkui-js/en-us_image_0000001127284938.gif rename to en/application-dev/reference/arkui-js/figures/en-us_image_0000001127284938.gif diff --git a/en/application-dev/reference/arkui-js/en-us_image_0000001167662852.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167662852.gif similarity index 100% rename from en/application-dev/reference/arkui-js/en-us_image_0000001167662852.gif rename to en/application-dev/reference/arkui-js/figures/en-us_image_0000001167662852.gif diff --git a/en/application-dev/reference/arkui-js/en-us_image_0000001173324703.gif b/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324703.gif similarity index 100% rename from en/application-dev/reference/arkui-js/en-us_image_0000001173324703.gif rename to en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324703.gif diff --git a/en/application-dev/reference/arkui-js/js-components-basic-menu.md b/en/application-dev/reference/arkui-js/js-components-basic-menu.md index 6869a0171e0f22eee17e69c59db699de25bd8532..fe3ba72dcfacbe81173c1a15775df94527fa2a37 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-menu.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-menu.md @@ -41,8 +41,8 @@ The following styles are supported. | font-size | <length> | 30px | No | Font size of the menu. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | letter-spacing | <length> | 0 | No | Character spacing of the menu. | -| font-style | string | normal | No | Font style of the menu. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component. | -| font-weight | number \| string | normal | No | Font weight of the menu. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component. | +| font-style | string | normal | No | Font style of the menu. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| +| font-weight | number \| string | normal | No | Font weight of the menu. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| @@ -92,10 +92,10 @@ The following methods are supported. ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { onMenuSelected(e) { - prompt.showToast({ + promptAction.showToast({ message: e.value }) }, diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index 5a9ace889f60ae6f6c0c891e8d0a8d55b3dadfd1..c167bb26caea50ddf841a538f96d6df46e870144 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -224,8 +224,7 @@ select { ```js // xxx.js -import router from '@system.router'; -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { data: { @@ -253,63 +252,63 @@ export default { }, textonchange(e) { this.textvalue = e.newValue; - prompt.showToast({ + promptAction.showToast({ message: "text:" + e.newValue + ",newSelected:" + e.newSelected }) }, textoncancel(e) { - prompt.showToast({ + promptAction.showToast({ message: "text: textoncancel" }) }, dateonchange(e) { this.datevalue = e.year + "-" + e.month + "-" + e.day; - prompt.showToast({ + promptAction.showToast({ message: "date:" + e.year + "-" + (e.month + 1) + "-" + e.day }) }, dateoncancel() { - prompt.showToast({ + promptAction.showToast({ message: "date: dateoncancel" }) }, timeonchange(e) { if (this.containsecond) { this.timevalue = e.hour + ":" + e.minute + ":" + e.second; - prompt.showToast({ + promptAction.showToast({ message: "Time:" + e.hour + ":" + e.minute + ":" + e.second }) } else { this.timevalue = e.hour + ":" + e.minute; - prompt.showToast({ + promptAction.showToast({ message: "Time:" + e.hour + ":" + e.minute }) } }, timeoncancel() { - prompt.showToast({ + promptAction.showToast({ message: "timeoncancel" }) }, datetimeonchange(e) { this.datetimevalue = e.year + "-" + e.month + "-" + e.day + " " + e.hour + ":" + e.minute; - prompt.showToast({ + promptAction.showToast({ message: "Time:" + (e.month + 1) + "-" + e.day + " " + e.hour + ":" + e.minute }) }, datetimeoncancel() { - prompt.showToast({ + promptAction.showToast({ message: "datetimeoncancel" }) }, multitextonchange(e) { this.multitextvalue = e.newValue; - prompt.showToast({ + promptAction.showToast({ message: "Multi-column text change" + e.newValue }) }, multitextoncancel() { - prompt.showToast({ + promptAction.showToast({ message: "multitextoncancel" }) }, diff --git a/en/application-dev/reference/arkui-js/js-components-basic-rating.md b/en/application-dev/reference/arkui-js/js-components-basic-rating.md index e241e2f64b9ff1c30115f11f326eb0b12985c8fd..1442f9724dc800a31cbe5adc9e21f82c8a3e1101 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-rating.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-rating.md @@ -85,10 +85,10 @@ rating { ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { changeRating(e){ - prompt.showToast({ + promptAction.showToast({ message: e.rating }); } diff --git a/en/application-dev/reference/arkui-js/js-components-basic-textarea.md b/en/application-dev/reference/arkui-js/js-components-basic-textarea.md index 06c37b95715772be3545f73e03b5f6954fc52723..3c7fb55be8981ae1c15363d90610662520f336a7 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-textarea.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-textarea.md @@ -52,8 +52,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | color | <color> | \#e6000000 | No | Text color of the multi-line text box. | | font-size | <length> | 16px | No | Font size of the multi-line text box. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the multi-line text box. This attribute is available when the component type is set to one of the following: text\|email\|date\|time\|number\|password. | -| font-weight | number \| string | normal | No | Font weight. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the multi-line text box. This attribute is available when the component type is set to one of the following: text\|email\|date\|time\|number\|password.| +| font-weight | number \| string | normal | No | Font weight. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md#styles) component.| | font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| | caret-color6+ | <color> | - | No | Color of the caret. | @@ -96,10 +96,10 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { change(e){ - prompt.showToast({ + promptAction.showToast({ message: 'value: ' + e.text + ', lines: ' + e.lines + ', height: ' + e.height, duration: 3000, }); diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 125067139d62be03f2a19995e9181df6010a1f77..f580a31338e6e8d145d963c1b2f7662f1113e06c 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -17,7 +17,7 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse | Name | Type | Description | | ------ | ------ | ------------------------------------------------------------ | | offset | number | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. | -| color | string | Gradient color to set. | +| color | string | Gradient color to set. | **Example** @@ -35,9 +35,9 @@ export default { const el =this.$refs.canvas; const ctx = el.getContext('2d'); const gradient = ctx.createLinearGradient(50,0,300,100); - gradient.addColorStop(0.0, 'red') - gradient.addColorStop(0.5, 'white') - gradient.addColorStop(1.0, 'green') + gradient.addColorStop(0.0, '#ff0000') + gradient.addColorStop(0.5, '#ffffff') + gradient.addColorStop(1.0, '#00ff00') ctx.fillStyle = gradient ctx.fillRect(0, 0, 300, 300) } diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index 0ebefab7d190de7f8ca8bd76b570444c0a2aa70b..8df65d142a4129699c45f44b69c1c5f1fbe96829 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -1682,9 +1682,9 @@ Creates a linear gradient and returns a **CanvasGradient** object. For details, // Linear gradient: start(50,0) end(300,100) var gradient = ctx.createLinearGradient(50,0, 300,100); // Add three color stops - gradient.addColorStop(0.0, 'red'); - gradient.addColorStop(0.5, 'white'); - gradient.addColorStop(1.0, 'green'); + gradient.addColorStop(0.0, '#ff0000'); + gradient.addColorStop(0.5, '#ffffff'); + gradient.addColorStop(1.0, '#00ff00'); // Set the fill style and draw a rectangle ctx.fillStyle = gradient; ctx.fillRect(0, 0, 500, 500); diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-imagedata.md b/en/application-dev/reference/arkui-js/js-components-canvas-imagedata.md index d63949ef2f2295de28337635d567194247f92fdc..7d606efd0afe4c38c9827e4e3fad9f105b74924e 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-imagedata.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-imagedata.md @@ -27,14 +27,14 @@ The **ImageData** object is an object that stores pixel data rendered on a canva ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { onShow() { const el =this.$refs.canvas; const ctx = el.getContext('2d'); ctx.fillRect(0,0,200,200) var imageData = ctx.createImageData(1,1) - prompt.showToast({ + promptAction.showToast({ message:imageData, duration:5000 }) diff --git a/en/application-dev/reference/arkui-js/js-components-common-attributes.md b/en/application-dev/reference/arkui-js/js-components-common-attributes.md index 357385f9747d820873c0c7aebb9ac8a8c2647960..416087236c246f61e692f8b4207d7d9161b31c9f 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-attributes.md +++ b/en/application-dev/reference/arkui-js/js-components-common-attributes.md @@ -31,5 +31,114 @@ Rendering attributes are used to set whether a component is rendered. | if | boolean | - | Whether the element is added or removed.| | show | boolean | - | Whether the element is displayed or hidden.| -> **NOTE**
+> **NOTE** +> > Do not set styles in attribute fields. + +## Example + +### Example 1 + +```html + +
+ + + + {{ $item.value }} + + +
+``` + +```css +/* xxx.css */ +#container { + flex-direction: column; + width: 100%; + margin-top: 10px; +} +.text { + font-size: 50px; + font-weight: 500; + margin-left: 12px; +} +.listItem { + width: 100%; + height: 100px; + line-height: 60px; + border-bottom: 1px solid #DEDEDE; + font-size: 20px; +} +.btn{ + width: 280px; + font-size: 26px; + margin: 10px 0; +} +``` + +```js +// xxx.js +export default { + data: { + visible: true, + display: true, + title: "", + i: 4, + array: [ + {"value": "Item 0"}, + {"value": "Item 1"}, + {"value": "Item 2"}, + {"value": "Item 3"}, + ], + }, + toggleShow: function() { + this.array.push ({"value": "Item" + this.i }) + this.i++ + }, + toggleDisplay: function() { + this.display = !this.display + }, +} +``` + +![en-us-attributes](figures/en-us-attributes.gif) + +### Example 2 + +```html + +
+
+ hello world +
+
+ hello world +
+
+``` + +```css +/* xxx.css */ +.container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 100%; +} +.text1{ + width: 90%; + height: 100px; + background-color: aqua; +} +.text2{ + width: 90%; + height: 100px; + background-color: blue; +} +``` + +![en-us_image1](figures/en-us_image1.png) diff --git a/en/application-dev/reference/arkui-js/js-components-common-customizing-font.md b/en/application-dev/reference/arkui-js/js-components-common-customizing-font.md index 4054548e00f9e9b80e8d3fff5abc9d3cf209c2b4..f57ab118948791263a353c2d1da63d08ecc6466e 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-customizing-font.md +++ b/en/application-dev/reference/arkui-js/js-components-common-customizing-font.md @@ -11,8 +11,8 @@ The custom font can be loaded from the font file in a project. The font file mus ``` @font-face { - font-family: HWfont; - src: url('/common/HWfont.ttf'); + font-family: font; + src: url('/common/font.ttf'); } ``` @@ -48,10 +48,10 @@ Page style: ```css /*xxx.css*/ @font-face { - font-family: HWfont; - src: url("/common/HWfont.ttf"); + font-family: font; + src: url("/common/font.ttf"); } .demo-text { - font-family: HWfont; + font-family: font; } ``` diff --git a/en/application-dev/reference/arkui-js/js-components-common-styles.md b/en/application-dev/reference/arkui-js/js-components-common-styles.md index b32dbc08734817999f0968ebb47bfd41cea2e693..611529aec1de7dc133ff4fab8c784622cb60591a 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-styles.md +++ b/en/application-dev/reference/arkui-js/js-components-common-styles.md @@ -42,7 +42,7 @@ You can set universal styles for components in the **style** attribute or **.css | backdrop-filter5+ | string | - | Syntax: backdrop-filter: blur(px)
Radius of the background blur area within the component layout. If this style is not set, the default value **0** (no blur) is used. Percentage values are not supported.
Example:
- backdrop-filter: blur(10px) | | window-filter5+ | string | - | Syntax: window-filter: blur(percent), style5+
Blur degree and style for windows within the component layout. If this style is not set, the default value **0%** (no blur area) is used. Different blur degrees and styles for multiple blur areas are not supported. Available values of **style** are as follows: small_light (default value), medium_light, large_light, xlarge_light, small_dark, medium_dark, large_dark, xlarge_dark
Example:
- window-filter: blur(50%)
- window-filter: blur(10%), large_light | | opacity | number | 1 | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. | -| display | string | flex | Type of the box containing an element. Available values are as follows:
- **flex**: flexible layout
- **none**: not rendered
- **grid**: grid layout (available only **div** supports the **display** style)| +| display | string | flex | Type of the box containing an element. Available values are as follows:
- **flex**: flexible layout
- **none**: not rendered
- **grid**: grid layout (available only for the **\
** component) | | visibility | string | visible | Whether to display the box containing an element. The invisible box occupies layout space. (To remove the box, set the **display** attribute to **none**.) Available values are as follows:
- **visible**: The element is visible.
- **hidden**: The box is hidden but still takes up space.
If both **visibility** and **display** are set, only **display** takes effect.| | flex | number \| string | - | How to divide available space of the parent component for each child component.
You can set one, two5+, or three5+ values for this style.
Set one value in either of the following ways:
- A unitless number to set **flex-grow**.
- A valid width value5+ to set **flex-basis**.
Set two values5+ in the following ways:
The first value must be a unitless number used to set **flex-grow**. The second value must be either of the following:
- A unitless number to set **flex-shrink**.
- A valid width value to set **flex-basis**.
Set three values5+ in the following ways:
The first value must be a unitless number used to set **flex-grow**. The second value must be a unitless number used to set **flex-shrink**. The third value must be a valid width value used to set **flex-basis**.
This style takes effect only when the container is any of the following components: **\
**, **\**, **\**, **\**, and **\5+**.| | flex-grow | number | 0 | How much a child component will grow. The value specifies allocation of the remaining space on the main axis of the parent component. Size of available space = Container size - Total size of all child components. Value **0** indicates that the child component does not grow.
This style takes effect only when the container is any of the following components: **\
**, **\**, **\**, **\**, and **\5+**.| diff --git a/en/application-dev/reference/arkui-js/js-components-container-dialog.md b/en/application-dev/reference/arkui-js/js-components-container-dialog.md index a37adca994facb60950bc6d072541108509680c8..05262db3033500e0249b22d4e889e202a21a6084 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-dialog.md +++ b/en/application-dev/reference/arkui-js/js-components-container-dialog.md @@ -132,30 +132,30 @@ The following methods are supported. The [universal methods](../arkui-js/js-comp ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { showDialog() { this.$element('simpledialog').show() }, cancelDialog() { - prompt.showToast({ + promptAction.showToast({ message: 'Dialog cancelled' }) }, cancelSchedule() { this.$element('simpledialog').close() - prompt.showToast({ + promptAction.showToast({ message: 'Successfully cancelled' }) }, setSchedule() { this.$element('simpledialog').close() - prompt.showToast({ + promptAction.showToast({ message: 'Successfully confirmed' }) }, doubleclick(){ - prompt.showToast({ + promptAction.showToast({ message: 'doubleclick' }) } diff --git a/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md b/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md index 1a9fa13727b5fbd31d257379ede19e045df95cfa..f624bc744807f1e8fc5e621eb4ada060f29150b8 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md +++ b/en/application-dev/reference/arkui-js/js-components-container-list-item-group.md @@ -27,7 +27,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ---- | ------ | ------- | ---- | ---------------------------------------- | -| type | string | default | No | Type of the list item group. A list supports multiple list item group types. The same type of list item groups must have the same view layout after being rendered. If the type is fixed, replace the **if** attribute with the **show** attribute to ensure that the view layout remains unchanged.| +| type | string | default | No | Type of the list-item-group. A list supports multiple list-item-group types. The same type of list-item-groups must have the same view layout after being rendered. If the type is fixed, replace the **if** attribute with the **show** attribute to ensure that the view layout remains unchanged.| > **NOTE** > @@ -48,11 +48,11 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -| Name | Name | Description | +| Name | Parameter | Description | | ------------- | ---------------------------------- | ---------------------------------------- | | groupclick | { groupid: string } | Triggered when a group is clicked.
**groupid**: ID of the group that is clicked. | -| groupcollapse | { groupid: string } | Triggered when a group is collapsed.
**groupid**: ID of the group that is collapsed.
If the parameter is not carried or **groupid** is left empty, all groups are collapsed.| -| groupexpand | { groupid: string } | Triggered when a group is expanded.
**groupid**: ID of the group that is expanded.
If the parameter is not carried or **groupid** is left empty, all groups are expanded.| +| groupcollapse | { groupid: string } | Triggered when a group is collapsed.
**groupid**: ID of the group collapsed.
If the parameter is not carried or **groupid** is left empty, all groups are collapsed.| +| groupexpand | { groupid: string } | Triggered when a group is expanded.
**groupid**: ID of the group expanded.
If the parameter is not carried or **groupid** is left empty, all groups are expanded.| ## Methods @@ -124,7 +124,7 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support ```js // xxx.js -import prompt from '@system.prompt'; +import promptAction from '@ohos.promptAction'; export default { data: { direction: 'column', @@ -158,12 +158,12 @@ export default { this.$element('mylist').expandGroup() }, collapse(e) { - prompt.showToast({ + promptAction.showToast({ message: 'Close ' + e.groupid }) }, expand(e) { - prompt.showToast({ + promptAction.showToast({ message: 'Open ' + e.groupid }) } diff --git a/en/application-dev/reference/arkui-js/js-components-container-popup.md b/en/application-dev/reference/arkui-js/js-components-container-popup.md index 46d661972f887b2ed6601523198618d7a831d380..6203c94c195855a5f76c275b4f03eccc725cf769 100644 --- a/en/application-dev/reference/arkui-js/js-components-container-popup.md +++ b/en/application-dev/reference/arkui-js/js-components-container-popup.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -The **\** component is used to display a pop-up to offer instructions after a user clicks a bound component. + The **\** component is used to display a pop-up to offer instructions after a user clicks a bound component or calls the specific API. ## Required Permissions @@ -23,9 +23,9 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | | target | string | - | Yes| ID of the target element. Dynamic switch is not supported.| -| placement | string | bottom | No| Position of the pop-up. Available values are as follows:
- **left**: The pop-up is displayed on the left of the target item.
- **right**: The pop-up is displayed on the right of the target item.
- **top**: The pop-up is displayed at the top of the target item.
- **bottom**: The pop-up is displayed at the bottom of the target item.
- **topLeft**: The pop-up is displayed on the upper left of the target item.
- **topRight**: The pop-up is displayed on the upper right of the target item.
- **bottomLeft**: The pop-up is displayed on the bottom left of the target item.
- **bottomRight**: The pop-up is displayed on the bottom right of the target item.| +| placement | string | bottom | No| Position of the pop-up relative to the target element. Available values are as follows:
- **left**: on the left of the target element.
- **right**: on the right of the target element.
- **top**: at the top of the target element;
- **bottom**: at the bottom of the target element.
- **topLeft**: in the upper left corner of the target element.
- **topRight**: in the upper right corner of the target element.
- **bottomLeft**: in the lower left corner of the target element.
- **bottomRight**: in the lower right corner of the target element.| | keepalive5+ | boolean | false | No| Whether to retain this pop-up. **true**: The pop-up does not disappear when users tap other areas or switch the page. To hide the pop-up, call the **hide** method.
**false**: The pop-up disappears when users tap other areas or switch the page.| -| clickable5+ | boolean | true | No| Whether to display the pop-up when users click the bound control. If this parameter is set to **false**, the pop-up can be triggered only by a method call.| +| clickable5+ | boolean | true | No| Whether to display the pop-up when the user clicks the target element. If this attribute is set to **false**, the pop-up can be triggered only by an API call.| | arrowoffset5+ | <length> | 0 | No| Offset of the pop-up arrow. By default, the arrow is centered. A positive value means that the arrow moves along the language direction (LTR or RTL), and a negative value means that the arrow moves along the opposite direction of the language direction.| > **NOTE** @@ -111,10 +111,10 @@ The following methods are supported. ```js // xxx.js -import prompt from '@system.prompt' +import promptAction from '@ohos.promptAction' export default { visibilitychange(e) { - prompt.showToast({ + promptAction.showToast({ message: 'visibility change visibility: ' + e.visibility, duration: 3000 }); diff --git a/en/application-dev/reference/arkui-js/js-components-create-elements.md b/en/application-dev/reference/arkui-js/js-components-create-elements.md new file mode 100644 index 0000000000000000000000000000000000000000..b0afebfa68e40737f66361e501c67536472df8ac --- /dev/null +++ b/en/application-dev/reference/arkui-js/js-components-create-elements.md @@ -0,0 +1,145 @@ +# Dynamic Component Creation + +You can dynamically add components with specified attributes and styles to pages. + +> **NOTE** +> +> This API is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. + + +## createElement + +createElement(tag: string): Element + +Creates a component object. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------ | ---- | ------- | +| tag | string | Yes | Component name.| + +**Return value** + +| Type | Description | +| ----------- | ------------- | +| Element | Component object corresponding to the value of **tag**.| + +```js +let newImage = dom.createElement('image') +``` + + +## setAttribute + +setAttribute(name: string, value: string): void + +Dynamically sets the attributes of this component. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------ | ---- | ------- | +| name | string | Yes | Attribute name.| +| value | string | Yes | Attribute value.| + +```js +newImage.setAttribute('src', 'common/testImage.jpg') +``` + + +## setStyle + +setStyle(name: string, value: string): boolean + +Dynamically sets the style of this component. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------ | ---- | ------- | +| name | string | Yes | Style name.| +| value | string | Yes | Style value.| + +**Return value** + +| Type | Description | +| ----------- | ------------- | +| boolean | Returns **true** if the setting is successful; returns **false** otherwise.| + +```js +newImage.setStyle('width', '120px') +``` + + +## addChild + +addChild(child: Element): void + +Adds a dynamically created component to the parent component. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------ | ---- | ------- | +| child | Element | Yes | Component object.| + +```js +newDiv.addChild(newImage) +``` + + +## Example + +```html + +
+
+ + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + align-items: center; + width: 100%; +} + +.parent { + flex-direction: column; +} + +.btn { + width: 70%; + height: 60px; + margin: 15px; +} +``` + +```js +// xxx.js +let newDiv = null +let newImage = null + +export default { + appendDiv() { + let parent = this.$element('parentDiv') + newDiv = dom.createElement('div') + newDiv.setStyle('width', '150px') + newDiv.setStyle('height', '150px') + newDiv.setStyle('backgroundColor', '#AEEEEE') + newDiv.setStyle('marginTop', '15px') + parent.addChild(newDiv) + }, + appendImage() { + newImage = dom.createElement('image') + newImage.setAttribute('src', 'common/testImage.jpg') + newImage.setStyle('width', '120px') + newImage.setStyle('height', '120px') + newDiv.addChild(newImage) + } +} +``` diff --git a/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md b/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md index 8ae629cba3025d8d6b6d9f3ea4597678a6c1d138..b6f659f069b4e7c5f6dc6347664552a8c6a82e4d 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-basic-usage.md @@ -1,6 +1,7 @@ -# Basic Usage +# Basic Usage of Custom Components + +Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can import a custom component to the host page through **element** as shown in the following code snippet: -Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can introduce a custom component to the host page through **element** as shown in the following code snippet: ```html
@@ -8,8 +9,8 @@ Custom components are existing components encapsulated based on service requirem
``` +The following is an example of using a custom component with **if-else**, which displays **comp1** when **showComp1** is set to **true** and displays **comp2** otherwise. -The following is an example of using a custom component with **if-else**: ```html @@ -19,18 +20,142 @@ The following is an example of using a custom component with **if-else**:
``` +The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default. + + +## Custom Events + +To bind an event to a custom child component, use the **(on|@)event-name="bindParentVmMethod"** syntax. **this.$emit('eventName', { params: 'passedParameters' })** is used in the child component to trigger the event and pass parameters to the parent component. The parent component then calls the **bindParentVmMethod** API and receives parameters passed by the child component. + +> **NOTE** +> +> For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** in the parent component instead of **childrenEvent** used in the child component. + +**Example 1 with parameters passed** + +The following example describes how to define a child component **comp**: + +```html + +
+ Click here to view the hidden text. + hello world +
+``` + +```css +/* comp.css */ +.item { + width: 700px; + flex-direction: column; + height: 300px; + align-items: center; + margin-top: 100px; +} +.text-style { + font-weight: 500; + font-family: Courier; + font-size: 40px; +} +``` + +```js +// comp.js +export default { + data: { + showObj: false, + }, + childClicked () { + this.$emit('eventType1'); + this.showObj = !this.showObj; + }, +} +``` + +The following example describes how to import **comp** to the parent component: + +```html + + +
+ +
+``` + +```css +/* xxx.css */ +.container { + background-color: #f8f8ff; + flex: 1; + flex-direction: column; + align-content: center; +} +``` + +```js +// xxx.js +export default { + textClicked () {} +} +``` + +**Example 2 with no parameters passed** + +The following example describes how to define a child component **comp**: + +```html + +
+ Click here to view the hidden text. + hello world +
+``` + +```js +// comp.js +export default { + childClicked () { + this.$emit('eventType1', { text: 'Receive the parameters from the child component.' }); + this.showObj = !this.showObj; + }, +} +``` + +In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**: + +```html + + +
+ Parent component: {{text}} + +
+``` + +```js +// xxx.js +export default { + data: { + text: 'Start' + }, + textClicked (e) { + this.text = e.detail.text; + }, +} +``` + +![EventParameters](figures/EventParameters.gif) + + +## Custom Component Data -- The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default. -- Event binding: Use **(on|@)***child1* syntax to bind a child component event to a custom component. In the child component, use **this.$emit('***child1***', {params:'***parameter to pass***'})** for event triggering and value transferring. In the parent component, call **bindParentVmMethod** method and receive the parameters passed from the child component. - > **NOTE** - > - > For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** instead of **childrenEvent**: **\@children-event="bindParentVmMethod"**. +In the JS file of a custom component, you can define, pass, and process data by declaring fields such as **data**, **props**, and **computed**. For details about how to use **props** and **computed**, see [Data Transfer and Processing](js-components-custom-props.md). -**Table 1** Objects +**Table 1** Custom component data -| Name | Type | Description | +| Name | Type | Description | | -------- | --------------- | ---------------------------------------- | -| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).
Do not use this attribute and **private** or **public** at the same time.(Rich) | -| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.| -| computed | Object | Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.| +| data | Object \| Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**).
Do not use this attribute and **private** or **public** at the same time.| +| props | Array \| Object | Used for communication between components. This attribute can be passed to components through **\**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**) in the name. Currently, **props** does not support functions.| +| computed | Object | Used for pre-processing for reading and setting parameters. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.| diff --git a/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md b/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md deleted file mode 100644 index 55131eddc7e7613ae7fa58086ca5c59cc9ee35c9..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md +++ /dev/null @@ -1,51 +0,0 @@ -# Event Parameter - -A child component can also pass parameters to an upper-layer component through the bound event. The following example describes how to pass parameters through the custom event: - - -```html - -
- Click to View Hidden Text - hello world -
-``` - - -```js -// comp.js -export default { - childClicked () { - this.$emit('eventType1', {text: 'Received parameters from the child component.'}); - this.showObj = !this.showObj; - }, -} -``` - - -In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**: - - -```html - - -
- Parent component: {{text}} - -
-``` - - -```js -// xxx.js -export default { - data: { - text: 'Start' - }, - textClicked (e) { - this.text = e.detail.text; - }, -} -``` - -![EventParameters](figures/EventParameters.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-custom-events.md b/en/application-dev/reference/arkui-js/js-components-custom-events.md deleted file mode 100644 index cf2f81a31dc62c4023a2a85591f9468e6fca097d..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/arkui-js/js-components-custom-events.md +++ /dev/null @@ -1,76 +0,0 @@ -# Custom Events - -The following example describes how to define a child component **comp**: - - -```html - -
- Click here to view the hidden text. - hello world -
-``` - - -```css -/* comp.css */ -.item { - width: 700px; - flex-direction: column; - height: 300px; - align-items: center; - margin-top: 100px; -} -.text-style { - font-weight: 500; - font-family: Courier; - font-size: 40px; -} -``` - - -```js -// comp.js -export default { - data: { - showObj: false, - }, - childClicked () { - this.$emit('eventType1'); - this.showObj = !this.showObj; - }, -} -``` - - -The following example describes how to introduce the child component: - - -```html - - -
- -
-``` - - -```css -/* xxx.css */ -.container { - background-color: #f8f8ff; - flex: 1; - flex-direction: column; - align-content: center; -} -``` - - -```js -// xxx.js -export default { - textClicked () {}, -} -``` - -For more information, see [Basic Usage](./js-components-custom-basic-usage.md). diff --git a/en/application-dev/reference/arkui-js/js-components-custom-props.md b/en/application-dev/reference/arkui-js/js-components-custom-props.md index f2a3a4c4faf87d3230de6d128c9c55ad20548f9d..c9c496b57842c628eabb96377c8096c6a9cc1f9c 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-props.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-props.md @@ -1,22 +1,25 @@ -# props +# Data Transfer and Processing -You can use **props** to declare attributes of a custom component and pass the attributes to the child component. The supported types of **props** include String, Number, Boolean, Array, Object, and Function. Note that a camel case attribute name \(**compProp**\) should be converted to the kebab case format \(**comp-prop**\) when you reference the attribute in an external parent component. You can add **props** to a custom component, and pass the attribute to the child component. -``` +## props + +You can use **props** to declare attributes of a custom component and pass the attributes to the child component. The supported types of **props** include String, Number, Boolean, Array, Object, and Function. Note that a camel case attribute name (**compProp**) should be converted to the kebab case format (**comp-prop**) when you reference the attribute in an external parent component. The following is sample for adding **props** to a custom component and passing the attribute to the child component. + +```html
{{compProp}}
``` -``` +```js // comp.js export default { props: ['compProp'], } ``` -``` +```html
@@ -24,21 +27,22 @@ export default {
``` ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The name of a custom attribute cannot start with reserved keywords such as **on**, **@**, **on:**, and **grab:**. +> **NOTE** +> +> The name of a custom attribute cannot start with reserved keywords such as **on**, **@**, **on:**, and **grab:**. -## Default Value +### Default Value -You can set the default value for a child component attribute via **default**. The default value is used if the parent component does not have **default** set. In this case, the **props** attribute must be in object format instead of an array. +You can set the default value for a child component attribute via **default**. The default value is used if the parent component does not have **default** set. In this case, the **props** attribute must be in object format instead of an array. -``` +```html
{{title}}
``` -``` +```js // comp.js export default { props: { @@ -49,21 +53,21 @@ export default { } ``` -In this example, a **** component is added to display the title. The title content is a custom attribute, which displays the text specified by a user. If the user has not set a title, the default text will be displayed. Add the attribute when referencing the custom component. +In this example, a **\** component is added to display the title. The title content is a custom attribute, which displays the text specified by a user. If the user has not set a title, the default text will be displayed. Add the attribute when referencing the custom component. -``` +```html
- +
``` -## Unidirectional Value Transfer +### Unidirectional Value Transfer -Data can be transferred only from the parent component to child components. You are not allowed to change the value passed to the child component. However, you can receive the value passed by **props** as a default value in **data**, and then change the **data** value. +Data can be transferred only from the parent component to child components. You are not allowed to change the value passed to the child component. However, you can receive the value passed by **props** as a default value in **data**, and then change the **data** value. -``` +```js // comp.js export default { props: ['defaultCount'], @@ -78,11 +82,11 @@ export default { } ``` -## Monitoring Data Changes by **$watch** +### Monitoring Data Changes by **$watch** -To listen for attribute changes in a component, you can use the **$watch** method to add a callback. The following code snippet shows how to use **$watch**: +To listen for attribute changes in a component, you can use the **$watch** method to add a callback. The following code snippet shows how to use **$watch**: -``` +```js // comp.js export default { props: ['title'], @@ -90,16 +94,17 @@ export default { this.$watch('title', 'onPropertyChange'); }, onPropertyChange(newV, oldV) { - console.info('title attribute changed'+ newV + ' ' + oldV) + console.info('title attribute changed'+ newV + ' ' + oldV) }, } ``` -## Computed Property -To improve the development efficiency, you can use a computed property to pre-process an attribute in a custom component before reading or setting the attribute. In the **computed** field, you can set a getter or setter to be triggered when the attribute is read or written, respectively. The following is an example: +## computed -``` +To improve the development efficiency, you can use a computed property to pre-process an attribute in a custom component before reading or setting the attribute. In the **computed** field, you can set a getter or setter to be triggered when the attribute is read or written, respectively. The following is an example: + +```js // comp.js export default { props: ['title'], @@ -129,5 +134,4 @@ export default { } ``` -The first computed property **message** has only a getter. The value of **message** changes depending on the **objTitle** value. The getter can only read but cannot set the value. You need a setter \(such as **notice** in the sample code\) to set the value of the computed property. - +The first computed property **message** has only a getter. The value of **message** changes depending on the **objTitle** value. The getter can only read but cannot set the value (such as **time** defined during initialization in **data**). You need a setter (such as **notice** in the sample code) to set the value of the computed property. diff --git a/en/application-dev/reference/arkui-js/js-components-custom-slot.md b/en/application-dev/reference/arkui-js/js-components-custom-slot.md index b65cfd01d2603195100ed8c0709289dd7b59b692..50c5b9ed0d1ad181567945134be95e0f9c229fed 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-slot.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-slot.md @@ -1,13 +1,15 @@ -# slot +# slot ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Default Slot -You can use the **** tag to create a slot inside a custom component to fill the content defined in the parent component. The sample code is as follows: +## Default Slot -``` +You can use the **\** tag to create a slot inside a custom component to fill the content defined in the parent component. The sample code is as follows: + +```html
The following uses the content defined in the parent component. @@ -16,22 +18,22 @@ You can use the **** tag to create a slot inside a custom component to ``` The following references the custom component: - -``` +```html
- Content defined in the parent component + Content defined in the parent component
``` -## Named Slot -When multiple slots are need inside a custom component, you can name them, so that you can specify the slot in which you want to fill content by setting the **** attribute. +## Named Slot -``` +When multiple slots are need inside a custom component, you can name them, so that you can specify the slot in which you want to fill content by setting the **** attribute. + +```html
The following uses the content defined in the parent component. @@ -41,8 +43,7 @@ When multiple slots are need inside a custom component, you can name them, so th ``` The following references the custom component: - -``` +```html
@@ -53,6 +54,6 @@ The following references the custom component:
``` ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->**** and **** do not support dynamic data binding. - +> **NOTE** +> +> **\** and **\** do not support dynamic data binding. diff --git a/en/application-dev/reference/arkui-js/js-components-custom-style.md b/en/application-dev/reference/arkui-js/js-components-custom-style.md index 37e0770cdeec8de1e3bd3c89360c56973353cea4..ba8644e3e347e700b523ea0c7f2ab02159faeca7 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-style.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-style.md @@ -1,16 +1,19 @@ # Style Inheritance + > **NOTE**
-> The APIs of this module are supported since API 9. Updates will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. A custom component has the **inherit-class** attribute, which is defined in the following table. -| Name | Type | Default Value| Mandatory| Description | -| ------------ | ------ | ------ | ---- | ------------------------------------------------------ | -| inherit-class | string | - | No | Class styles inherited from the parent component, seperated by spaces.| +| Name | Type | Default Value | Mandatory | Description | +| ------------- | ------ | ---- | ---- | -------------------------------- | +| inherit-class | string | - | No | Class styles inherited from the parent component, separated by spaces.| To enable a custom component to inherit the styles of its parent component, set the **inherit-calss** attribute for the custom component. -The example below is a code snippet in the HML file of the parent page that references a custom component named **comp**. This component uses the **inherit-class** attribute to inherit the styles of its parent component: **parent-class1** and **parent-class2**. +The example below is a code snippet in the HML file of the parent component that references a custom component named **comp**. This component uses the **inherit-class** attribute to inherit the styles of its parent component: **parent-class1** and **parent-class2**. + ```html @@ -20,9 +23,10 @@ The example below is a code snippet in the HML file of the parent page that refe
``` -Code snippet in the CSS file of the parent page: -```html -// xxx.css +Code snippet in the CSS file of the parent component: + +```css +/* xxx.css */ .parent-class1 { background-color:red; border:2px; @@ -34,6 +38,7 @@ Code snippet in the CSS file of the parent page: ``` Code snippet in the HML file of the custom component, where **parent-class1** and **parent-class2** are styles inherited from the parent component: + ```html
diff --git a/en/application-dev/reference/arkui-js/js-components-svg-animate.md b/en/application-dev/reference/arkui-js/js-components-svg-animate.md index 0d298e588c1de3e69e0eea10aed2a3381688ff32..e90d520cb36057ac385917e4df3d532c8669e97d 100644 --- a/en/application-dev/reference/arkui-js/js-components-svg-animate.md +++ b/en/application-dev/reference/arkui-js/js-components-svg-animate.md @@ -52,7 +52,7 @@ Not supported ``` -![zh-cn_image_0000001173324703](figures/en-us_image_0000001173324703.gif) +![en-us_image_0000001173324703](figures/en-us_image_0000001173324703.gif) ```html @@ -68,7 +68,7 @@ Not supported ``` -![zh-cn_image_0000001167662852](figures/en-us_image_0000001167662852.gif) +![en-us_image_0000001167662852](figures/en-us_image_0000001167662852.gif) ```html @@ -83,7 +83,7 @@ Not supported ``` -![zh-cn_image_0000001127284938](figures/en-us_image_0000001127284938.gif) +![en-us_image_0000001127284938](figures/en-us_image_0000001127284938.gif) ```html @@ -117,4 +117,4 @@ Not supported ``` -![animate-4](figures/animate-4.gif) +![en-us_image_0000001127125126](figures/en-us_image_0000001127125126.gif) diff --git a/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md index c97b123b4bc071d0209bbf6c3e8aad9984f7e914..8eebde2cacb7dc2e2409a8c1f6a8274ac4e38390 100644 --- a/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md @@ -14,7 +14,7 @@ In addition to the attributes that are supported by **CanvasRenderingContext2D** | Name | Type | Description | | ------ | ------ | ---------------------------------------- | -| filter | string | Image filter.
Available options are as follows:
- **blur**: applies the Gaussian blur for the image.
- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.
- **contrast**: adjusts the image contrast.
- **drop-shadow**: sets a shadow effect for the image.
- **grayscale**: converts the image to a grayscale image.
- **hue-rotate**: applies hue rotation to the image.
- **invert**: inverts the input image.
- **opacity**: sets the opacity of the image.
- **saturate**: sets the saturation of the image.
- **sepia**: converts the image to dark brown. | +| filter | string | Image filter.
Available options are as follows:
- **blur**: applies the Gaussian blur for the image.
- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.
- **contrast**: adjusts the image contrast.
- **drop-shadow**: sets a shadow effect for the image.
- **grayscale**: converts the image to a grayscale image.
- **hue-rotate**: applies hue rotation to the image.
- **invert**: inverts the image.
- **opacity**: sets the image opacity.
- **saturate**: sets the image saturation.
- **sepia**: converts the image to sepia.| **Example** ```html @@ -199,13 +199,13 @@ export default { var offscreenCanvasCtx = offscreen.getContext("2d"); offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0); - offscreenCanvasCtx.fillStyle = 'gray'; + offscreenCanvasCtx.fillStyle = '#a9a9a9'; offscreenCanvasCtx.fillRect(40, 40, 50, 20); offscreenCanvasCtx.fillRect(40, 90, 50, 20); // Non-skewed rectangles offscreenCanvasCtx.resetTransform(); - offscreenCanvasCtx.fillStyle = 'red'; + offscreenCanvasCtx.fillStyle = '#ff0000'; offscreenCanvasCtx.fillRect(40, 40, 50, 20); offscreenCanvasCtx.fillRect(40, 90, 50, 20); diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index 7061cde570c5bf521e9eddc4ef232af1e3a8050b..25736a22dced9dd795af1edd130de06ab02248cf 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -102,7 +102,6 @@ - [Counter](ts-container-counter.md) - [Flex](ts-container-flex.md) - [FlowItem](ts-container-flowitem.md) - - [GridContainer](ts-container-gridcontainer.md) - [GridCol](ts-container-gridcol.md) - [GridRow](ts-container-gridrow.md) - [Grid](ts-container-grid.md) @@ -124,25 +123,25 @@ - [TabContent](ts-container-tabcontent.md) - [WaterFlow](ts-container-waterflow.md) - Media Components - - [Video](ts-media-components-video.md) + - [Video](ts-media-components-video.md) - Drawing Components - - [Circle](ts-drawing-components-circle.md) - - [Ellipse](ts-drawing-components-ellipse.md) - - [Line](ts-drawing-components-line.md) - - [Polyline](ts-drawing-components-polyline.md) - - [Polygon](ts-drawing-components-polygon.md) - - [Path](ts-drawing-components-path.md) - - [Rect](ts-drawing-components-rect.md) - - [Shape](ts-drawing-components-shape.md) + - [Circle](ts-drawing-components-circle.md) + - [Ellipse](ts-drawing-components-ellipse.md) + - [Line](ts-drawing-components-line.md) + - [Polyline](ts-drawing-components-polyline.md) + - [Polygon](ts-drawing-components-polygon.md) + - [Path](ts-drawing-components-path.md) + - [Rect](ts-drawing-components-rect.md) + - [Shape](ts-drawing-components-shape.md) - Canvas Components - - [Canvas](ts-components-canvas-canvas.md) - - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - - [CanvasGradient](ts-components-canvas-canvasgradient.md) - - [ImageBitmap](ts-components-canvas-imagebitmap.md) - - [ImageData](ts-components-canvas-imagedata.md) - - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) - - [Path2D](ts-components-canvas-path2d.md) - - [Lottie](ts-components-canvas-lottie.md) + - [Canvas](ts-components-canvas-canvas.md) + - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) + - [CanvasGradient](ts-components-canvas-canvasgradient.md) + - [ImageBitmap](ts-components-canvas-imagebitmap.md) + - [ImageData](ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) + - [Path2D](ts-components-canvas-path2d.md) + - [Lottie](ts-components-canvas-lottie.md) - Animation - [AnimatorProperty](ts-animatorproperty.md) - [Explicit Animatio](ts-explicit-animation.md) diff --git a/en/application-dev/reference/arkui-ts/figures/alphabet.gif b/en/application-dev/reference/arkui-ts/figures/alphabet.gif new file mode 100644 index 0000000000000000000000000000000000000000..5a5a3e4bab1f7f104afd27199125972c6cb611c0 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/alphabet.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif index cc49b51652e53b6caa3888b054dbea94c2f498eb..35b1bf68c0e0c323eb4c5171be6fbf368c6eb576 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264378.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001189634870.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001189634870.gif new file mode 100644 index 0000000000000000000000000000000000000000..cba972ca736015ad30288b21bb8069cb540414c2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001189634870.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378392.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378392.gif deleted file mode 100644 index 438c67b65f13bfcd1ee3eb19e4f0c1265ae16278..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212378392.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219864159.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219864159.gif new file mode 100644 index 0000000000000000000000000000000000000000..badadbdb856c478fdb2ec53f70015b29bb10041f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219864159.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058403.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058403.gif deleted file mode 100644 index c7532ed87726ac7591901514a7396b617daa10f0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058403.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138339.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138339.gif deleted file mode 100644 index 557213e5ff5c63c5f3b3db7ffbd56e80eef688f1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138339.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/relativecontainer.png b/en/application-dev/reference/arkui-ts/figures/relativecontainer.png index 574fcaa48023d14a579eaa843ebc59f1b961a29f..eff44d4efadaeb8dc94da8d166333c5956878f27 100644 Binary files a/en/application-dev/reference/arkui-ts/figures/relativecontainer.png and b/en/application-dev/reference/arkui-ts/figures/relativecontainer.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index 4bdc96f244d22a65d2689971492f84103f8f134e..e3fb8a003e68f5e54f3a48d4b9b8b15db5de3358 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission. | +| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability. Before loading images, the application must [request the required permissions](../../file-management/medialibrary-overview.md#requesting-permissions).
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission.| ## Attributes @@ -38,7 +38,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported. | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.
Default value: **ImageFit.Cover** | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.
Default value: **ImageRepeat.NoRepeat**
**NOTE**
This attribute is not applicable to SVG images.| -| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
**NOTE**
This attribute is not applicable to SVG images and **PixelMap** objects. | +| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.
Default value: **ImageInterpolation.None**
**NOTE**
This attribute is not applicable to SVG images.
This attribute is not applicable to **PixelMap** objects.| | renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.
Default value: **ImageRenderMode.Original**
**NOTE**
This attribute is not applicable to SVG images.| | sourceSize | {
width: number,
height: number
} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.
**NOTE**
This attribute is not applicable to **PixelMap** objects.| | matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.
Default value: **false** | @@ -48,6 +48,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**| | colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.| +| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**| > **NOTE** > @@ -74,11 +75,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the In addition to the [universal events](ts-universal-events-click.md), the following events are supported. -| Name | Description | +| Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status. | -| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels. | -| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. | +| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,
componentHeight: number, loadingStatus: number }) => void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.
- **width**: width of the image, in pixels.
- **height**: height of the image, in pixels.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.
- **loadingStatus**: image loading status.
| +| onError(callback: (event?: { componentWidth: number, componentHeight: number , message9+: string }) => void) | Triggered when an exception occurs during image loading.
- **componentWidth**: width of the container component, in pixels.
- **componentHeight**: height of the container component, in pixels.| +| onFinish(event: () => void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.| ## Example @@ -161,7 +162,7 @@ The default network timeout period is 5 minutes for loading online images. When ```tsx // @ts-nocheck import http from '@ohos.net.http'; -import ResponseCode from '@ohos.net.http'; +import ResponseCode from '@ohos.net.http' import image from '@ohos.multimedia.image' @@ -176,7 +177,7 @@ struct Index { Column({space: 10}) { Button ("Get Online Image") .onClick(() => { - this.httpRequest(); + this.httpRequest() }) Image(this.image).height(100).width(100) } @@ -187,7 +188,7 @@ struct Index { // Request an online image. private httpRequest() { - let httpRequest = http.createHttp(); + let httpRequest = http.createHttp() httpRequest.request( "https://www.example.com/xxx.png", // Enter a specific URL of the online image. @@ -198,7 +199,7 @@ struct Index { let code = data.responseCode if(ResponseCode.ResponseCode.OK == code) { let imageSource = image.createImageSource(data.result) - let options = {alphaType: 0, // Transparency + let options = {alphaType: 0, // Opacity editable: false, // Whether the image is editable pixelFormat: 3, // Pixel format scaleMode: 1, // Scale mode @@ -207,7 +208,7 @@ struct Index { this.image = pixelMap }) } else { - console.log("response code: " + code); + console.log("response code: " + code) } } } @@ -216,9 +217,9 @@ struct Index { } ``` -> **NOTE** -> -> For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module. +> **NOTE** +> +> For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module. ### Setting Attributes @@ -355,9 +356,9 @@ struct ImageExample3 { ### Rendering Sandbox Images ```ts -import fileio from '@ohos.fileio' +import fileio from '@ohos.fileio'; import fs from '@ohos.file.fs'; -import context from '@ohos.application.context' +import context from '@ohos.app.ability.context'; @Entry @Component diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index eb276513bad3c1f1f1c911f15f14f5f3c74f7dba..25743606575892d60be19fa31fd0e60055d01fb9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -27,7 +27,7 @@ ImageAnimator() | duration | number | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.
Default value: **1000**| | reverse | boolean | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.
Default value: **false**| | fixedSize | boolean | Whether the image size is the same as the component size.
**true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.
**false**: The width, height, top, and left attributes of each image must be set separately.
Default value: **true**| -| preDecode | number | Whether to enable pre-decoding. The default value **0** indicates that pre-decoding is disabled. The value **2** indicates that two images following the currently playing frame will be cached in advance to improve performance.
Default value: **0**| +| preDecode(deprecated) | number | Number of pre-decoded images. The value **2** indicates that two images following the currently playing page will be pre-decoded to improve performance.
This API is deprecated since API version 9.
Default value: **0**| | fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after the animation starts. For details about the options, see **FillMode**.
Default value: **FillMode.Forwards**| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| @@ -102,7 +102,7 @@ struct ImageAnimatorExample { left: 0 } ]) - .state(this.state).reverse(this.reverse).fixedSize(false).preDecode(2) + .state(this.state).reverse(this.reverse).fixedSize(false) .fillMode(FillMode.None).iterations(this.iterations).width(340).height(240) .margin({ top: 100 }) .onStart(() => { @@ -119,6 +119,7 @@ struct ImageAnimatorExample { }) .onFinish(() => { console.info('Finish') + this.state = AnimationStatus.Stopped }) Row() { Button('start').width(100).padding(5).onClick(() => { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 0e9b480a1326760e25e56bca698bd8e8581bbb68..e2afb3e5eaa55dfb4d4509db3c87ba55821cd748 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -467,13 +467,13 @@ Sets whether to enable geolocation access. By default, this feature is enabled. mediaPlayGestureAccess(access: boolean) -Sets whether a manual click is required for video playback. +Sets whether video playback must be started by user gestures. This API is not applicable to videos that do not have an audio track or whose audio track is muted. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ------ | ------- | ---- | ---- | ----------------- | -| access | boolean | Yes | true | Whether a manual click is required for video playback.| +| access | boolean | Yes | true | Whether video playback must be started by user gestures.| **Example** @@ -522,6 +522,109 @@ Sets whether to enable the multi-window permission. } ``` +### horizontalScrollBarAccess9+ + +horizontalScrollBarAccess(horizontalScrollBar: boolean) + +Sets whether to display the horizontal scrollbar, including the system default scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ----------- | ------- | ---- | ----- | ------------ | +| horizontalScrollBar | boolean | Yes | true | Whether to display the horizontal scrollbar.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .horizontalScrollBarAccess(true) + } + } + } + ``` + + ```html + + + + + Demo + + + + Scroll Test + + + ``` + +### verticalScrollBarAccess9+ + +verticalScrollBarAccess(verticalScrollBar: boolean) + +Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ----------- | ------- | ---- | ----- | ------------ | +| verticalScrollBarAccess | boolean | Yes | true | Whether to display the vertical scrollbar.| + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .verticalScrollBarAccess(true) + } + } + } + ``` + + ```html + + + + + Demo + + + + Scroll Test + + + ``` + + ### cacheMode cacheMode(cacheMode: CacheMode) @@ -707,13 +810,13 @@ Sets whether to block online downloads. defaultFixedFontSize(size: number) -Sets the default fixed font size of the web page. +Sets the default fixed font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ---------------------------- | -| size | number | Yes | 13 | Default fixed font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 13 | Default fixed font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -724,11 +827,11 @@ Sets the default fixed font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 16 + @State fontSize: number = 16 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .defaultFixedFontSize(this.size) + .defaultFixedFontSize(this.fontSize) } } } @@ -738,13 +841,13 @@ Sets the default fixed font size of the web page. defaultFontSize(size: number) -Sets the default font size of the web page. +Sets the default font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ------------------------ | -| size | number | Yes | 16 | Default font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 16 | Default font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -755,11 +858,11 @@ Sets the default font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 13 + @State fontSize: number = 13 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .defaultFontSize(this.size) + .defaultFontSize(this.fontSize) } } } @@ -769,13 +872,44 @@ Sets the default font size of the web page. minFontSize(size: number) -Sets the minimum font size of the web page. +Sets the minimum font size for the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ------------------------ | +| size | number | Yes | 8 | Minimum font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State fontSize: number = 13 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .minFontSize(this.fontSize) + } + } + } + ``` + +### minLogicalFontSize9+ + +minLogicalFontSize(size: number) + +Sets the minimum logical font size for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ------------------------ | -| size | number | Yes | 8 | Minimum font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| +| size | number | Yes | 8 | Minimum logical font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. | **Example** @@ -786,27 +920,28 @@ Sets the minimum font size of the web page. @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController() - @State size: number = 13 + @State fontSize: number = 13 build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) - .minFontSize(this.size) + .minLogicalFontSize(this.fontSize) } } } ``` + ### webFixedFont9+ webFixedFont(family: string) -Sets the fixed font family of the web page. +Sets the fixed font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | --------- | ---------------------------- | -| family | string | Yes | monospace | Fixed font family of the web page.| +| family | string | Yes | monospace | Fixed font family to set.| **Example** @@ -831,13 +966,13 @@ Sets the fixed font family of the web page. webSansSerifFont(family: string) -Sets the sans serif font family of the web page. +Sets the sans serif font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ---------- | --------------------------------- | -| family | string | Yes | sans-serif | Sans serif font family of the web page.| +| family | string | Yes | sans-serif | Sans serif font family to set.| **Example** @@ -862,13 +997,13 @@ Sets the sans serif font family of the web page. webSerifFont(family: string) -Sets the serif font family of the web page. +Sets the serif font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value| Description | | ------ | -------- | ---- | ------ | ---------------------------- | -| family | string | Yes | serif | Serif font family of the web page.| +| family | string | Yes | serif | Serif font family to set.| **Example** @@ -893,13 +1028,13 @@ Sets the serif font family of the web page. webStandardFont(family: string) -Sets the standard font family of the web page. +Sets the standard font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ---------- | ------------------------------- | -| family | string | Yes | sans serif | Standard font family of the web page.| +| family | string | Yes | sans serif | Standard font family to set.| **Example** @@ -924,13 +1059,13 @@ Sets the standard font family of the web page. webFantasyFont(family: string) -Sets the fantasy font family of the web page. +Sets the fantasy font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ------- | ------------------------------ | -| family | string | Yes | fantasy | Fantasy font family of the web page.| +| family | string | Yes | fantasy | Fantasy font family to set.| **Example** @@ -955,13 +1090,13 @@ Sets the fantasy font family of the web page. webCursiveFont(family: string) -Sets the cursive font family of the web page. +Sets the cursive font family for the web page. **Parameters** | Name| Type| Mandatory| Default Value | Description | | ------ | -------- | ---- | ------- | ------------------------------ | -| family | string | Yes | cursive | Cursive font family of the web page.| +| family | string | Yes | cursive | Cursive font family to set.| **Example** @@ -982,6 +1117,100 @@ Sets the cursive font family of the web page. } ``` +### darkMode9+ + +darkMode(mode: WebDarkMode) + +Sets the web dark mode. By default, web dark mode is disabled. When it is enabled, the **\** component enables the dark theme defined for web pages if the theme has been defined in **prefer-color-scheme** of a media query, and remains unchanged otherwise. To enable the forcible dark mode, use this API with [forceDarkAccess](#forcedarkaccess9). + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ----------- | ---- | --------------- | ------------------ | +| mode | [WebDarkMode](#webdarkmode9) | Yes | WebDarkMode.Off | Web dark mode to set.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State mode: WebDarkMode = WebDarkMode.On + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .darkMode(this.mode) + } + } + } + ``` + +### forceDarkAccess9+ + +forceDarkAccess(access: boolean) + +Sets whether to enable forcible dark mode for the web page. By default, this feature is turned off. This API is applicable only when dark mode is enabled in [darkMode](#darkmode9). + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | ------- | ---- | ----- | ------------------ | +| access | boolean | Yes | false | Whether to enable forcible dark mode for the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State mode: WebDarkMode = WebDarkMode.On + @State access: boolean = true + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .darkMode(this.mode) + .forceDarkAccess(this.access) + } + } + } + ``` + +### pinchSmooth9+ + +pinchSmooth(isEnabled: boolean) + +Sets whether to enable smooth pinch mode for the web page. + +**Parameters** + +| Name | Type| Mandatory| Default Value| Description | +| --------- | -------- | ---- | ------ | -------------------------- | +| isEnabled | boolean | Yes | false | Whether to enable smooth pinch mode for the web page.| + +**Example** + + ```ts +// xxx.ets +import web_webview from '@ohos.web.webview' +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .pinchSmooth(true) + } + } +} + ``` + ## Events The universal events are not supported. @@ -998,7 +1227,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1056,7 +1285,7 @@ Triggered when this page is about to exit after the user refreshes or closes the | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1117,7 +1346,7 @@ Triggered when **confirm()** is invoked by the web page. | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1177,7 +1406,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul | ------- | --------------------- | --------------- | | url | string | URL of the web page where the dialog box is displayed.| | message | string | Message displayed in the dialog box. | -| result | [JsResult](#jsresult) | The user's operation. | +| result | [JsResult](#jsresult) | User operation. | **Return value** @@ -1361,7 +1590,7 @@ Triggered when an HTTP error (the response code is greater than or equal to 400) | Name | Type | Description | | ------- | ---------------------------------------- | --------------- | | request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | -| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.| +| response | [WebResourceResponse](#webresourceresponse) | Encapsulation of a resource response.| **Example** @@ -1564,7 +1793,7 @@ Triggered when loading of the web page is complete. This API is used by an appli } ``` -### onRenderExited +### onRenderExited9+ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) @@ -1831,7 +2060,7 @@ Invoked when an HTTP authentication request is received. | Name | Type | Description | | ------- | ------------------------------------ | ---------------- | -| handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. | +| handler | [HttpAuthHandler](#httpauthhandler9) | User operation. | | host | string | Host to which HTTP authentication credentials apply.| | realm | string | Realm to which HTTP authentication credentials apply. | @@ -1900,7 +2129,7 @@ Invoked when an SSL error occurs during resource loading. | Name | Type | Description | | ------- | ------------------------------------ | -------------- | -| handler | [SslErrorHandler](#sslerrorhandler9) | The user's operation.| +| handler | [SslErrorHandler](#sslerrorhandler9) | User operation.| | error | [SslError](#sslerror9) | Error code. | **Example** @@ -1945,7 +2174,7 @@ Invoked when an SSL error occurs during resource loading. ### onClientAuthenticationRequest9+ -onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\, issuers : Array\}) => void) +onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array, issuers : Array}) => void) Invoked when an SSL client certificate request is received. @@ -1953,11 +2182,11 @@ Invoked when an SSL client certificate request is received. | Name | Type | Description | | -------- | ---------------------------------------- | --------------- | -| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation. | +| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | User operation. | | host | string | Host name of the server that requests a certificate. | | port | number | Port number of the server that requests a certificate. | -| keyTypes | Array\ | Acceptable asymmetric private key types. | -| issuers | Array\ | Issuer of the certificate that matches the private key.| +| keyTypes | Array | Acceptable asymmetric private key types. | +| issuers | Array | Issuer of the certificate that matches the private key.| **Example** ```ts @@ -2008,7 +2237,7 @@ Invoked when a permission request is received. | Name | Type | Description | | ------- | ---------------------------------------- | -------------- | -| request | [PermissionRequest](#permissionrequest9) | The user's operation.| +| request | [PermissionRequest](#permissionrequest9) | User operation.| **Example** @@ -2051,7 +2280,7 @@ Invoked when a permission request is received. onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean) -Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link). +Shows a context menu after the user clicks the right mouse button or long presses a specific element, such as an image or a link. **Parameters** @@ -2131,7 +2360,7 @@ Registers a callback for receiving a request to obtain the geolocation informati | Name | Type | Description | | ----------- | ------------------------------- | -------------- | | origin | string | Index of the origin. | -| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.| +| geolocation | [JsGeolocation](#jsgeolocation) | User operation.| **Example** @@ -2285,6 +2514,7 @@ Registers a callback for window creation. ```ts // xxx.ets + import web_webview from '@ohos.web.webview' @Entry @Component struct WebComponent { @@ -2626,7 +2856,7 @@ Notifies the **\** component of the user's confirm operation in the dialog ## FullScreenExitHandler9+ -Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see onFullScreenEnter. +Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9). ### exitFullScreen9+ @@ -2830,15 +3060,15 @@ Obtains the MIME type of the resource response. ### setResponseData9+ -setResponseData(data: string) +setResponseData(data: string | number) Sets the data in the resource response. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | ----------- | -| data | string | Yes | - | Resource response data to set.| +| Name| Type | Mandatory| Default Value| Description | +| ------ | ---------------- | ---- | ------ | ------------------------------------------------------------ | +| data | string \| number | Yes | - | Resource response data to set. When set to a number, the value indicates a file handle.| ### setResponseEncoding9+ @@ -2900,6 +3130,18 @@ Sets the status code of the resource response. | ---- | ------ | ---- | ---- | ------------- | | code | number | Yes | - | Status code to set.| +### setResponseIsReady9+ + +setResponseIsReady(IsReady: boolean) + +Sets whether the resource response data is ready. + +**Parameters** + +| Name | Type| Mandatory| Default Value| Description | +| ------- | -------- | ---- | ------ | -------------------------- | +| IsReady | boolean | Yes | true | Whether the resource response data is ready.| + ## FileSelectorResult9+ Notifies the **\** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9). @@ -3098,11 +3340,46 @@ Grants the permission for resources requested by the web page. | Name | Type | Mandatory | Default Value | Description | | --------- | --------------- | ---- | ---- | ------------- | -| resources | Array\ | Yes | - | List of accessible resources requested by the web page.| +| resources | Array\ | Yes | - | List of resources that can be requested by the web page with the permission to grant.| + +## ContextMenuSourceType9+ +| Name | Description | +| -------------------- | ---------- | +| None | Other event sources. | +| Mouse | Mouse event. | +| LongPress | Long press event. | + +## ContextMenuMediaType9+ + +| Name | Description | +| ------------ | ----------- | +| None | Non-special media or other media types.| +| Image | Image. | + +## ContextMenuInputFieldType9+ + +| Name | Description | +| ------------ | ----------- | +| None | Non-input field. | +| PlainText | Plain text field, such as the text, search, or email field. | +| Password | Password field. | +| Number | Numeric field. | +| Telephone | Phone number field.| +| Other | Field of any other type. | + +## ContextMenuEditStateFlags9+ + +| Name | Description | +| ------------ | ----------- | +| NONE | Editing is not allowed. | +| CAN_CUT | The cut operation is allowed. | +| CAN_COPY | The copy operation is allowed. | +| CAN_PASTE | The paste operation is allowed. | +| CAN_SELECT_ALL | The select all operation is allowed.| ## WebContextMenuParam9+ -Provides the information about the context menu that is displayed when a page element is long pressed. For the sample code, see [onContextMenuShow](#oncontextmenushow9). +Implements a context menu, which is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### x9+ @@ -3176,9 +3453,81 @@ Checks whether image content exists. | ------- | ------------------------- | | boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.| +### getMediaType9+ + +getMediaType(): ContextMenuMediaType + +Obtains the media type of this web page element. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuMediaType](#contextmenumediatype9) | Media type of the web page element.| + +### getSelectionText9+ + +getSelectionText(): string + +Obtains the selected text. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| string | Selected text for the context menu. If no text is selected, null is returned.| + +### getSourceType9+ + +getSourceType(): ContextMenuSourceType + +Obtains the event source of the context menu. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuSourceType](#contextmenusourcetype9) | Event source of the context menu.| + +### getInputFieldType9+ + +getInputFieldType(): ContextMenuInputFieldType + +Obtains the input field type of this web page element. + +**Return value** + +| Type | Description | +| ---------------------------------------- | ----------- | +| [ContextMenuInputFieldType](#contextmenuinputfieldtype9) | Input field type.| + +### isEditable9+ + +isEditable(): boolean + +Checks whether this web page element is editable. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| boolean | Returns **true** if the web page element is editable; returns **false** otherwise.| + +### getEditStateFlags9+ + +getEditStateFlags(): number + +Obtains the edit state flag of this web page element. + +**Return value** + +| Type | Description | +| ------- | ------------------------- | +| number | Edit state flag of the web page element. For details, see [ContextMenuEditStateFlags](#contextmenueditstateflags9).| + ## WebContextMenuResult9+ -Implements a **WebContextMenuResult** object. For the sample code, see onContextMenuShow. +Implements a **WebContextMenuResult** object. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### closeContextMenu9+ @@ -3192,6 +3541,30 @@ copyImage(): void Copies the image specified in **WebContextMenuParam**. +### copy9+ + +copy(): void + +Performs the copy operation related to this context menu. + +### paste9+ + +paste(): void + +Performs the paste operation related to this context menu. + +### cut9+ + +cut(): void + +Performs the cut operation related to this context menu. + +### selectAll9+ + +selectAll(): void + +Performs the select all operation related to this context menu. + ## JsGeolocation Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow). @@ -3208,24 +3581,28 @@ Sets the geolocation permission status of a web page. | ------ | ------- | ---- | ---- | ---------------------------------------- | | origin | string | Yes | - | Index of the origin. | | allow | boolean | Yes | - | Geolocation permission status. | -| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.| +| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. You can manage the geolocation permissions saved to the system through [GeolocationPermissions9+](../apis/js-apis-webview.md#geolocationpermissions).| ## WebController Implements a **WebController** to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component. +This API is deprecated since API version 9. You are advised to use [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller). + ### Creating an Object ``` webController: WebController = new WebController() ``` -### requestFocus +### requestFocus(deprecated) requestFocus() Requests focus for this web page. +This API is deprecated since API version 9. You are advised to use [requestFocus9+](../apis/js-apis-webview.md#requestfocus). + **Example** ```ts @@ -3247,12 +3624,14 @@ Requests focus for this web page. } ``` -### accessBackward +### accessBackward(deprecated) accessBackward(): boolean Checks whether going to the previous page can be performed on the current page. +This API is deprecated since API version 9. You are advised to use [accessBackward9+](../apis/js-apis-webview.md#accessbackward). + **Return value** | Type | Description | @@ -3281,12 +3660,14 @@ Checks whether going to the previous page can be performed on the current page. } ``` -### accessForward +### accessForward(deprecated) accessForward(): boolean Checks whether going to the next page can be performed on the current page. +This API is deprecated since API version 9. You are advised to use [accessForward9+](../apis/js-apis-webview.md#accessforward). + **Return value** | Type | Description | @@ -3315,12 +3696,14 @@ Checks whether going to the next page can be performed on the current page. } ``` -### accessStep +### accessStep(deprecated) accessStep(step: number): boolean Performs a specific number of steps forward or backward from the current page. +This API is deprecated since API version 9. You are advised to use [accessStep9+](../apis/js-apis-webview.md#accessstep). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3356,12 +3739,14 @@ Performs a specific number of steps forward or backward from the current page. } ``` -### backward +### backward(deprecated) backward(): void Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. +This API is deprecated since API version 9. You are advised to use [backward9+](../apis/js-apis-webview.md#backward). + **Example** ```ts @@ -3383,12 +3768,14 @@ Goes to the previous page based on the history stack. This API is generally used } ``` -### forward +### forward(deprecated) forward(): void Goes to the next page based on the history stack. This API is generally used together with **accessForward**. +This API is deprecated since API version 9. You are advised to use [forward9+](../apis/js-apis-webview.md#forward). + **Example** ```ts @@ -3444,12 +3831,14 @@ Performs a specific number of steps forward or backward on the current page base } ``` -### deleteJavaScriptRegister +### deleteJavaScriptRegister(deprecated) deleteJavaScriptRegister(name: string) Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API. +This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister9+](../apis/js-apis-webview.md#deletejavascriptregister). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3478,12 +3867,14 @@ Deletes a specific application JavaScript object that is registered with the win } ``` -### getHitTest +### getHitTest(deprecated) getHitTest(): HitTestType Obtains the element type of the area being clicked. +This API is deprecated since API version 9. You are advised to use [getHitTest9+](../apis/js-apis-webview.md#gethittest). + **Return value** | Type | Description | @@ -3678,7 +4069,7 @@ Obtains the default user agent of the current web page. } ``` -### loadData +### loadData(deprecated) loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }) @@ -3688,6 +4079,8 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the ** If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\** component as a non-encoded string in a manner similar to **loadUrl**. +This API is deprecated since API version 9. You are advised to use [loadData9+](../apis/js-apis-webview.md#loaddata). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3723,7 +4116,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces } ``` -### loadUrl +### loadUrl(deprecated) loadUrl(options: { url: string | Resource, headers?: Array\ }) @@ -3733,6 +4126,8 @@ The object injected through **loadUrl** is valid only in the current document. I The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. +This API is deprecated since API version 9. You are advised to use [loadUrl9+](../apis/js-apis-webview.md#loadurl). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -3761,12 +4156,14 @@ The object injected through **registerJavaScriptProxy** is still valid on a new } ``` -### onActive +### onActive(deprecated) onActive(): void Invoked when the **\** component enters the active state. +This API is deprecated since API version 9. You are advised to use [onActive9+](../apis/js-apis-webview.md#onactive). + **Example** ```ts @@ -3788,12 +4185,14 @@ Invoked when the **\** component enters the active state. } ``` -### onInactive +### onInactive(deprecated) onInactive(): void Invoked when the **\** component enters the inactive state. +This API is deprecated since API version 9. You are advised to use [onInactive9+](../apis/js-apis-webview.md#oninactive). + **Example** ```ts @@ -3815,11 +4214,13 @@ Invoked when the **\** component enters the inactive state. } ``` -### zoom +### zoom(deprecated) zoom(factor: number): void Sets a zoom factor for the current web page. +This API is deprecated since API version 9. You are advised to use [zoom9+](../apis/js-apis-webview.md#zoom). + **Parameters** | Name | Type | Mandatory | Description | @@ -3914,12 +4315,14 @@ Zooms out of this web page by 20%. } ``` -### refresh +### refresh(deprecated) refresh() Invoked when the **\** component refreshes the web page. +This API is deprecated since API version 9. You are advised to use [refresh9+](../apis/js-apis-webview.md#refresh). + **Example** ```ts @@ -3941,11 +4344,13 @@ Invoked when the **\** component refreshes the web page. } ``` -### registerJavaScriptProxy +### registerJavaScriptProxy(deprecated) registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\ }) -Registers a JavaScript object and invokes the methods of the object in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. +Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. + +This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy9+](../apis/js-apis-webview.md#registerjavascriptproxy). **Parameters** @@ -4007,12 +4412,14 @@ Registers a JavaScript object and invokes the methods of the object in the windo ``` -### runJavaScript +### runJavaScript(deprecated) runJavaScript(options: { script: string, callback?: (result: string) => void }) Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. +This API is deprecated since API version 9. You are advised to use [runJavaScript9+](../apis/js-apis-webview.md#runjavascript). + **Parameters** | Name | Type | Mandatory | Default Value | Description | @@ -4066,12 +4473,14 @@ Executes a JavaScript script. This API uses an asynchronous callback to return t ``` -### stop +### stop(deprecated) stop() Stops page loading. +This API is deprecated since API version 9. You are advised to use [stop9+](../apis/js-apis-webview.md#stop). + **Example** ```ts @@ -4093,12 +4502,14 @@ Stops page loading. } ``` -### clearHistory +### clearHistory(deprecated) clearHistory(): void Clears the browsing history. +This API is deprecated since API version 9. You are advised to use [clearHistory9+](../apis/js-apis-webview.md#clearhistory). + **Example** ```ts @@ -4626,7 +5037,7 @@ Obtains the cookie value corresponding to the specified URL. Column() { Button('getCookie') .onClick(() => { - let value = webview.WebCookieManager.getCookie('www.example.com') + let value = web_webview.WebCookieManager.getCookie('www.example.com') console.log("value: " + value) }) Web({ src: 'www.example.com', controller: this.controller }) @@ -4676,44 +5087,10 @@ Sets a cookie value for the specified URL. } ``` -### saveCookieSync9+ -saveCookieSync(): boolean - -Saves the cookies in the memory to the drive. This API returns the result synchronously. - -**Return value** - -| Type | Description | -| ------- | -------------------- | -| boolean | Operation result.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('saveCookieSync') - .onClick(() => { - let result = web_webview.WebCookieManager.saveCookieSync() - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - ### saveCookieAsync9+ saveCookieAsync(): Promise\ -Saves cookies in the memory to the drive. This API uses a promise to return the value. +Saves the cookies in the memory to the drive. This API uses a promise to return the value. **Return value** @@ -4752,7 +5129,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the ### saveCookieAsync9+ saveCookieAsync(callback: AsyncCallback\): void -Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the result. +Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. **Parameters** @@ -4998,158 +5375,7 @@ Deletes all session cookies. Column() { Button('deleteSessionCookie') .onClick(() => { - webview.WebCookieManager.deleteSessionCookie() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebDataBase9+ -Implements the **WebDataBase** object. - -### existHttpAuthCredentials9+ - -static existHttpAuthCredentials(): boolean - -Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. - -**Return value** - -| Type | Description | -| ------- | ---------------------------------------- | -| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('existHttpAuthCredentials') - .onClick(() => { - let result = web_webview.WebDataBase.existHttpAuthCredentials() - console.log('result: ' + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### deleteHttpAuthCredentials9+ - -static deleteHttpAuthCredentials(): void - -Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('deleteHttpAuthCredentials') - .onClick(() => { - web_webview.WebDataBase.deleteHttpAuthCredentials() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getHttpAuthCredentials9+ - -static getHttpAuthCredentials(host: string, realm: string): Array\ - -Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ----- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host to which HTTP authentication credentials apply.| -| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | - -**Return value** - -| Type | Description | -| --------------- | ---------------------- | -| Array\ | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - host: string = "www.spincast.org" - realm: string = "protected example" - username_password: string[] - build() { - Column() { - Button('getHttpAuthCredentials') - .onClick(() => { - this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm) - console.log('num: ' + this.username_password.length) - ForEach(this.username_password, (item) => { - console.log('username_password: ' + item) - }, item => item) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### saveHttpAuthCredentials9+ - -static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void - -Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host to which HTTP authentication credentials apply.| -| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | -| username | string | Yes | - | User name. | -| password | string | Yes | - | Password. | - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - host: string = "www.spincast.org" - realm: string = "protected example" - build() { - Column() { - Button('saveHttpAuthCredentials') - .onClick(() => { - web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche") + web_webview.WebCookieManager.deleteSessionCookie() }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -5157,783 +5383,88 @@ Saves HTTP authentication credentials for a given host and realm. This API retur } ``` -## GeolocationPermissions9+ - -Implements a **GeolocationPermissions** object. - -### allowGeolocation9+ - -static allowGeolocation(origin: string): void - -Allows the specified origin to use the geolocation information. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| - -**Example** +## MessageLevel - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('allowGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.allowGeolocation(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Name | Description | +| ----- | :---- | +| Debug | Debug level.| +| Error | Error level.| +| Info | Information level.| +| Log | Log level.| +| Warn | Warning level. | -### deleteGeolocation9+ +## RenderExitReason -static deleteGeolocation(origin: string): void +Enumerates the reasons why the rendering process exits. -Clears the geolocation permission status of a specified origin. +| Name | Description | +| -------------------------- | ----------------- | +| ProcessAbnormalTermination | The rendering process exits abnormally. | +| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| +| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | +| ProcessOom | The program memory is running low. | +| ProcessExitUnknown | Other reason. | -**Parameters** +## MixedMode -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| +| Name | Description | +| ---------- | ---------------------------------- | +| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| +| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | +| None | HTTP and HTTPS hybrid content cannot be loaded. | -**Example** +## CacheMode +| Name | Description | +| ------- | ------------------------------------ | +| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| +| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | +| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | +| Only | The cache alone is used to load the resources. | - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('deleteGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.deleteGeolocation(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +## FileSelectorMode +| Name | Description | +| -------------------- | ---------- | +| FileOpenMode | Open and upload a file. | +| FileOpenMultipleMode | Open and upload multiple files. | +| FileOpenFolderMode | Open and upload a folder.| +| FileSaveMode | Save a file. | -### deleteAllGeolocation9+ + ## HitTestType -static deleteAllGeolocation(): void +| Name | Description | +| ------------- | ------------------------ | +| EditText | Editable area. | +| Email | Email address. | +| HttpAnchor | Hyperlink whose **src** is **http**. | +| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| +| Img | HTML::img tag. | +| Map | Geographical address. | +| Phone | Phone number. | +| Unknown | Unknown content. | -Clears the geolocation permission status of all sources. +## SslError9+ -**Example** +Enumerates the error codes returned by **onSslErrorEventReceive** API. - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('deleteAllGeolocation') - .onClick(() => { - web_webview.GeolocationPermissions.deleteAllGeolocation() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Name | Description | +| ------------ | ----------- | +| Invalid | Minor error. | +| HostMismatch | The host name does not match. | +| DateInvalid | The certificate has an invalid date. | +| Untrusted | The certificate issuer is not trusted.| -### getAccessibleGeolocation9+ +## ProtectedResourceType9+ -static getAccessibleGeolocation(origin: string, callback: AsyncCallback\): void +| Name | Description | Remarks | +| --------- | ------------- | -------------------------- | +| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| -Obtains the geolocation permission status of the specified source. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------------------------ | ---- | ---- | ---------------------------------------- | -| origin | string | Yes | - | Index of the origin. | -| callback | AsyncCallback\ | Yes | - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('getAccessibleGeolocationAsync') - .onClick(() => { - web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { - if (error) { - console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)) - return - } - console.log('getAccessibleGeolocationAsync result: ' + result) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getAccessibleGeolocation9+ - -static getAccessibleGeolocation(origin: string): Promise\ - -Obtains the geolocation permission status of the specified source. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ---------- | -| origin | string | Yes | - | Index of the origin.| - -**Return value** - -| Type | Description | -| ------------------ | ---------------------------------------- | -| Promise\ | Promise used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "file:///" - build() { - Column() { - Button('getAccessibleGeolocationPromise') - .onClick(() => { - web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => { - console.log('getAccessibleGeolocationPromise result: ' + result) - }).catch(error => { - console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getStoredGeolocation9+ - -static getStoredGeolocation(callback: AsyncCallback\\>): void - -Obtains the geolocation permission status of all sources. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | -------------------------------- | ---- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('getStoredGeolocationAsync') - .onClick(() => { - web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { - if (error) { - console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)) - return - } - let origins_str: string = origins.join() - console.log('getStoredGeolocationAsync origins: ' + origins_str) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### getStoredGeolocation9+ - -static getStoredGeolocation(): Promise\\> - -Obtains the geolocation permission status of all sources. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Default Value | Description | -| -------- | -------------------------------- | ---- | ---- | -------------------- | -| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.| - -**Return value** - -| Type | Description | -| -------------------------- | -------------------------------- | -| Promise\\> | Promise used to return the geolocation permission status of all sources.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('getStoredGeolocationPromise') - .onClick(() => { - web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => { - let origins_str: string = origins.join() - console.log('getStoredGeolocationPromise origins: ' + origins_str) - }).catch(error => { - console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -## WebStorage9+ -Implements the **WebStorage** object, which can be used to manage the Web SQL and the HTML5 Web Storage API. All **\** components in an application share one **WebStorage**. -### deleteAllData9+ -static deleteAllData(): void - -Deletes all data in the Web SQL Database. - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('deleteAllData') - .onClick(() => { - web_webview.WebStorage.deleteAllData() - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### deleteOrigin9+ -static deleteOrigin(origin : string): void - -Deletes all data in the specified origin. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getHttpAuthCredentials') - .onClick(() => { - web_webview.WebStorage.deleteOrigin(this.origin) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOrigins9+ -static getOrigins(callback: AsyncCallback\>) : void - -Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the information about the origins. For details, see **WebStorageOrigin**.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOrigins') - .onClick(() => { - web_webview.WebStorage.getOrigins((error, origins) => { - if (error) { - console.log('error: ' + error) - return - } - for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin) - console.log('usage: ' + origins[i].usage) - console.log('quota: ' + origins[i].quota) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOrigins9+ -static getOrigins() : Promise\> - -Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. - -**Return value** - -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise> | Promise used to return the information about the origins. For details, see **WebStorageOrigin**.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOrigins') - .onClick(() => { - web_webview.WebStorage.getOrigins() - .then(origins => { - for (let i = 0; i < origins.length; i++) { - console.log('origin: ' + origins[i].origin) - console.log('usage: ' + origins[i].usage) - console.log('quota: ' + origins[i].quota) - } - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginQuota9+ -static getOriginQuota(origin : string, callback : AsyncCallback\) : void - -Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | --------- | -| origin | string | Yes | Index of the origin.| -| callback | AsyncCallback\ | Yes | Callback used to return the storage quota of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { - if (error) { - console.log('error: ' + error) - return - } - console.log('quota: ' + quota) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginQuota9+ -static getOriginQuota(origin : string) : Promise\ - -Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Return value** - -| Type | Description | -| ---------------- | ----------------------- | -| Promise\ | Promise used to return the storage quota of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginQuota(this.origin) - .then(quota => { - console.log('quota: ' + quota) - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginUsage9+ -static getOriginUsage(origin : string, callback : AsyncCallback\) : void - -Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | ---- | ---------- | -| origin | string | Yes | Index of the origin.| -| callback | AsyncCallback\ | Yes | Callback used to return the storage usage of the origin. | - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginUsage') - .onClick(() => { - web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { - if (error) { - console.log('error: ' + error) - return - } - console.log('usage: ' + usage) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -### getOriginUsage9+ -static getOriginUsage(origin : string) : Promise\ - -Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| - -**Return value** - -| Type | Description | -| ---------------- | ---------------------- | -| Promise\ | Promise used to return the storage usage of the origin.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - origin: string = "origin" - build() { - Column() { - Button('getOriginQuota') - .onClick(() => { - web_webview.WebStorage.getOriginUsage(this.origin) - .then(usage => { - console.log('usage: ' + usage) - }) - .catch(error => { - console.log('error: ' + error) - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .databaseAccess(true) - } - } - } - ``` - -## WebStorageOrigin9+ - -Provides usage information about the Web SQL Database. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------- | -| origin | string | Yes | Index of the origin.| -| usage | number | Yes | Storage usage of the origin. | -| quota | number | Yes | Storage quota of the origin. | - -## MessageLevel - -| Name | Description | -| ----- | :---- | -| Debug | Debug level.| -| Error | Error level.| -| Info | Information level.| -| Log | Log level.| -| Warn | Warning level. | - -## RenderExitReason - -Enumerates the reasons why the rendering process exits. - -| Name | Description | -| -------------------------- | ----------------- | -| ProcessAbnormalTermination | The rendering process exits abnormally. | -| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.| -| ProcessCrashed | The rendering process crashes due to segmentation or other errors. | -| ProcessOom | The program memory is running low. | -| ProcessExitUnknown | Other reason. | - -## MixedMode - -| Name | Description | -| ---------- | ---------------------------------- | -| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.| -| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. | -| None | HTTP and HTTPS hybrid content cannot be loaded. | - -## CacheMode +## WebDarkMode9+ | Name | Description | | ------- | ------------------------------------ | -| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| -| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. | -| Online | The cache is not used to load the resources. All resources are obtained from the Internet. | -| Only | The cache alone is used to load the resources. | - -## FileSelectorMode -| Name | Description | -| -------------------- | ---------- | -| FileOpenMode | Open and upload a file. | -| FileOpenMultipleMode | Open and upload multiple files. | -| FileOpenFolderMode | Open and upload a folder.| -| FileSaveMode | Save a file. | - - ## HitTestType - -| Name | Description | -| ------------- | ------------------------ | -| EditText | Editable area. | -| Email | Email address. | -| HttpAnchor | Hyperlink whose **src** is **http**. | -| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| -| Img | HTML::img tag. | -| Map | Geographical address. | -| Phone | Phone number. | -| Unknown | Unknown content. | - -## SslError9+ - -Enumerates the error codes returned by **onSslErrorEventReceive** API. - -| Name | Description | -| ------------ | ----------- | -| Invalid | Minor error. | -| HostMismatch | The host name does not match. | -| DateInvalid | The certificate has an invalid date. | -| Untrusted | The certificate issuer is not trusted.| - -## ProtectedResourceType9+ - -| Name | Description | Remarks | -| --------- | ------------- | -------------------------- | -| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| - -## WebAsyncController - -Implements the **WebAsyncController** object, which can be used to control the behavior of a **\** component with asynchronous callbacks. A **WebAsyncController **object controls one **\** component. - -### Creating an Object - -``` -webController: WebController = new WebController(); -webAsyncController: WebAsyncController = new WebAsyncController(webController); -``` - -### storeWebArchive9+ - -storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback): void - -Stores this web page. This API uses an asynchronous callback to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. -| callback | AsyncCallback | Yes | Callback used to return the save path if the operation is successful and null otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Button('saveWebArchive') - .onClick(() => { - let webAsyncController = new web_webview.WebAsyncController(this.controller) - webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { - if (filename != null) { - console.info(`save web archive success: ${filename}`) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### storeWebArchive9+ - -storeWebArchive(baseName: string, autoName: boolean): Promise - -Stores this web page. This API uses a promise to return the result. - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null. -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. - -**Return value** - -| Type | Description | -| --------------- | -------------------------------- | -| Promise | Promise used to return the save path if the operation is successful and null otherwise.| - -**Example** - - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController(); - build() { - Column() { - Button('saveWebArchive') - .onClick(() => { - let webAsyncController = new web_webview.WebAsyncController(this.controller); - webAsyncController.storeWebArchive("/data/storage/el2/base/", true) - .then(filename => { - if (filename != null) { - console.info(`save web archive success: ${filename}`) - } - }) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` +| Off | The web dark mode is disabled. | +| On | The web dark mode is enabled. | +| Auto | The web dark mode setting follows the system settings. | ## WebMessagePort9+ @@ -6158,7 +5689,7 @@ Sets the message port in this object. For the complete sample code, see [postMes ## DataResubmissionHandler9+ -Implements the **DataResubmissionHandler** for resubmitting or canceling the web form data. +Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data. ### resend9+ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index 5430e54558a7cfd30a7bc139820d130316a1ad97..f775992c63793b3f41e30d819fab405be931be90 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -6,27 +6,26 @@ The **\** can accept and display the EGL/OpenGL ES and media data in > > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - - ## Child Components - Child components are not supported when **type** is set to **"surface"**.\ - Since API version 9, child components are supported when **type** is set to **"component"**. +Child components are not supported when **type** is set to **"surface"**. + +Since API version 9, child components are supported when **type** is set to **"component"**. ## APIs - XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) +XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ----- | -| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.| -| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.| -| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.| -| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke the methods of the component. This parameter is valid only when the component type is **"surface"**. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | +| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.| +| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.| +| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| -> **NOTE**
+> **NOTE** > > When **type** is set to **"component"**, the **\** functions as a container, where child components are laid out vertically. > @@ -46,7 +45,7 @@ The **\** can accept and display the EGL/OpenGL ES and media data in ## Events -The following events are supported only when **type** is set to **"surface"**. The [universal events and gestures](./Readme-EN.md) are not supported. +The following events are supported only when **type** is set to **"surface"**. The [universal events](ts-universal-events-click.md) and [universal gestures](ts-gesture-settings.md) are not supported. ### onLoad @@ -56,9 +55,9 @@ Triggered when the plug-in is loaded. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------ | ---- | ----------------------- | -| event | object | No | Context of the **\** object. The APIs contained in the context are defined at the C++ layer by developers.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| event | object | No | Context of the **\** object. The APIs contained in the context are defined at the C++ layer by developers.| ### onDestroy @@ -99,7 +98,7 @@ Sets the width and height of the surface held by the **\**. This API **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ------------- | ------ | ---- | ----------------------- | | surfaceWidth | number | Yes | Width of the surface held by the **\**.| | surfaceHeight | number | Yes | Height of the surface held by the **\**.| diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index d0c3c2e1860d77390c679134eefc540ddcae238d..7c8b95655a9470ea7fd1951132f7b2c7974a45da 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -41,9 +41,9 @@ struct Page45 { .backgroundColor('#ffff00') .onReady(() => { var grad = this.context.createLinearGradient(50, 0, 300, 100) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') this.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500) }) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index bbfdaa6a6a21679e5612634c6fa490ef0ceee187..6bb371dfa5dc1e8cb3c88c9b1618e035caf8294c 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -27,34 +27,35 @@ loadAnimation( path: string, container: object, render: string, loop: boolean, autoplay: boolean, name: string ): AnimationItem -Loads an animation. Before calling this API, declare the **Animator('__lottie_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**. +Loads an animation. Before calling this API, declare the **Animator('__lottie_ets')** object and make sure the canvas layout is complete. This API can be used together with the lifecycle callback **onReady()** of the **Canvas** component. **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | --------------------------- | ---- | ---------------------------------------- | -| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| -| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| -| render | string | Yes | Rendering type. The value can only be **"canvas"**. | -| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| -| autoplay | boolean | No | Whether to automatically play the animation.
Default value: **true** | +| Name | Type | Mandatory| Description | +| -------------- | --------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**| +| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| +| render | string | Yes | Rendering type. The value can only be **"canvas"**. | +| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| +| autoplay | boolean | No | Whether to automatically play the animation.
Default value: **true** | | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation.
Default value: null | -| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | +| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | ## lottie.destroy destroy(name: string): void -Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. +Destroys the animation. This API must be called when a page exits. This API can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| +| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** API. By default, all animations are destroyed. | **Example** + ```ts // xxx.ets import lottie from '@ohos/lottieETS' @@ -133,7 +134,7 @@ Plays a specified animation. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| +| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** API. By default, all animations are played. | **Example** @@ -152,7 +153,7 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused. | **Example** @@ -165,13 +166,13 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani togglePause(name: string): void -Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. +Pauses or plays a specified animation. This API is equivalent to the switching between **lottie.play()** and **lottie.pause()**. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused or played. | **Example** @@ -190,7 +191,7 @@ Stops the specified animation. The next time **lottie.play()** is called, the an | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are stopped. | **Example** @@ -209,8 +210,8 @@ Sets the playback speed of the specified animation. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | -| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.| -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. | **Example** @@ -230,7 +231,7 @@ Sets the direction in which the specified animation plays. | Name | Type | Mandatory | Description | | --------- | ------------------ | ---- | ---------------------------------------- | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
AnimationDirection: 1 \| -1 | -| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| +| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. | **Example** @@ -241,7 +242,7 @@ Sets the direction in which the specified animation plays. ## AnimationItem -Defines an **AnimationItem** object, which is returned by the **loadAnimation** interface and has attributes and interfaces. The attributes are described as follows: +Defines an **AnimationItem** object, which is returned by the **loadAnimation** API and has attributes and APIs. The attributes are described as follows: | Name | Type | Description | | ----------------- | ---------------------------------------- | ---------------------------------------- | @@ -253,18 +254,18 @@ Defines an **AnimationItem** object, which is returned by the **loadAnimation** | totalFrames | number | Total number of frames in the animation segment that is being played. | | frameRate | number | Frame rate (frame/s). | | frameMult | number | Frame rate (frame/ms). | -| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| -| playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). | +| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | +| playDirection | number | Playback direction.
**1**: forward.
**-1**: backward. | | playCount | number | Number of times the animation plays. | | isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. | -| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing.| -| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | +| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** API needs to be called to start playing. | +| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | | renderer | any | Animation rendering object, which depends on the rendering type. | | animationID | string | Animation ID. | | timeCompleted | number | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**.| | segmentPos | number | ID of the current animation segment. The value is a positive integer greater than or equal to 0. | | isSubframeEnabled | boolean | Whether the precision of **currentFrame** is a floating point number. | -| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | +| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | ## AnimationItem.play @@ -309,7 +310,7 @@ Destroys an animation. pause(name?: string): void -Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. +Pauses an animation. When the **play** API is called next time, the animation is played from the current frame. **Parameters** @@ -328,7 +329,7 @@ Pauses an animation. When the **play** interface is called next time, the animat togglePause(name?: string): void -Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. +Pauses or plays an animation. This API is equivalent to the switching between **play** and **pause**. **Parameters** @@ -347,7 +348,7 @@ Pauses or plays an animation. This method is equivalent to the switching between stop(name?: string): void -Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. +Stops an animation. When the **play** API is called next time, the animation is played from the first frame. **Parameters** @@ -372,7 +373,7 @@ Sets the playback speed of an animation. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | -| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| +| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | **Example** @@ -411,8 +412,8 @@ Sets the animation to stop at the specified frame or time. | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | -| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress.
Default value: **false** | -| name | string | No | Name of the target animation. By default, the value is null. | +| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress.
Default value: **false** | +| name | string | No | Name of the target animation. By default, the value is null. | **Example** @@ -435,8 +436,8 @@ Sets the animation to start from the specified frame or time progress. | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | -| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress.
Default value: **false** | -| name | string | No | Name of the target animation. By default, the value is null. | +| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress.
Default value: **false** | +| name | string | No | Name of the target animation.
Default value: null | **Example** @@ -459,7 +460,7 @@ Sets the animation to play only the specified segment. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | ---------------------------------------- | | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle.| -| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | +| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | **Example** @@ -475,7 +476,7 @@ Sets the animation to play only the specified segment. resetSegments(forceFlag: boolean): void -Resets the settings configured by the **playSegments** method to play all the frames. +Resets the settings configured by the **playSegments** API to play all the frames. **Parameters** @@ -526,7 +527,7 @@ Sets the precision of the **currentFrame** attribute to display floating-point n getDuration(inFrames?: boolean): void -Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. +Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** API. **Parameters** @@ -545,7 +546,7 @@ Obtains the duration (irrelevant to the playback speed) or number of frames for addEventListener<T = any>(name: AnimationEventName, callback: AnimationEventCallback<T>): () => void -Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. +Adds an event listener. After the event is complete, the specified callback is triggered. This API returns the function object that can delete the event listener. **Parameters** @@ -578,7 +579,7 @@ Removes an event listener. | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| -| callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | +| callback | AnimationEventCallback<T> | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | **Example** diff --git a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md index 1b9fba3579fe3c18a8a7d8225e65bdcc2e3d163c..97b08d90ca88b2cef08ac931cc6a6405c2236dd5 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md @@ -134,7 +134,7 @@ struct AlphabetIndexerSample { .selectedFont({size: 16, weight: FontWeight.Bolder}) // Font style of the selected text. .popupFont({ size: 30, weight: FontWeight.Bolder}) // Font style of the pop-up text. .itemSize(28) // Size of an item in the alphabetic index bar. - .alignStyle(IndexerAlign.Left) // Position of the pop-up window relative to the center of the indexer bar's top border, which is left in this example. + .alignStyle(IndexerAlign.Left) // The pop-up window is displayed on the right of the alphabetic index bar. .onSelect((index: number) => { console.info(this.value[index] + ' Selected!') }) @@ -162,4 +162,4 @@ struct AlphabetIndexerSample { } ``` -![en-us_image_0000001212378392](figures/en-us_image_0000001212378392.gif) +![alphabet](figures/alphabet.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-flex.md b/en/application-dev/reference/arkui-ts/ts-container-flex.md index 5b8c2e1044dc7bc5dcf45e95386adb1d7f30651c..a2de237b09f26589ff262ea1cabe89273bec72d9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/arkui-ts/ts-container-flex.md @@ -4,7 +4,7 @@ The **\** component allows for flexible layout of child components. > **NOTE** > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -> - The **\** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[Column](ts-container-column.md)** or **[Row](ts-container-row.md)** instead under scenarios where consistently high performance is required. +> - The **\** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[\](ts-container-column.md)** or **[\](ts-container-row.md)** instead under scenarios where consistently high performance is required. ## Required Permissions @@ -30,7 +30,7 @@ Creates a standard **\** component. | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | - | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| + | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-gridcol.md b/en/application-dev/reference/arkui-ts/ts-container-gridcol.md index e808617b90335ce1aaa8dddbb8304124a85a3540..33870e0f047cd048aad3f5e1e049da82cbe1202c 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-gridcol.md +++ b/en/application-dev/reference/arkui-ts/ts-container-gridcol.md @@ -1,6 +1,6 @@ # GridCol -The **\** component must be used as a child component of the [GridRow](ts-container-gridrow.md) container. +The **\** component must be used as a child component of the **[\](ts-container-gridrow.md)** container. > **NOTE** > @@ -15,11 +15,11 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------------------------------------------ | -| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.
Default value: **1**| -| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid
Default value: **0** | -| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| span | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.
Default value: **1**| +| offset | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of offset columns relative to the previous child component of the grid
Default value: **0** | +| order | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index ae044f9ddfddc305898c6c6bc65fb1dd90b845de..9de0b8a25a4bf88c91c0883561cc9ff61b63c086 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -22,20 +22,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| sticky | [Sticky](#sticky)| Sticky effect of the list item.
Default value: **Sticky.None**| -| editable | boolean \| [EditMode](#editmode)| Whether to enter editing mode, where the list item can be deleted or moved.
Default value: **false**| +| sticky(deprecated) | [Sticky](#stickydeprecated) | Sticky effect of the list item.
Default value: **Sticky.None**
This API is deprecated since API version 9. You are advised to use **sticky** of the [\](ts-container-list.md#attributes) component. | +| editable(deprecated) | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.
This API is deprecated since API version 9.
Default value: **false**| | selectable8+ | boolean | Whether the current list item is selectable by mouse drag.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| | swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Component displayed when the list item is swiped out from the screen edge.
- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).
- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
| -## Sticky +## Sticky(deprecated) +This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\** component. | Name| Description| | -------- | -------- | | None | The list item is not sticky.| | Normal | The list item is sticky with no special effects.| | Opacity | The list item is sticky with opacity changes.| -## EditMode - +## EditMode(deprecated) +This API is deprecated since API version 9. | Name | Description | | ------ | --------- | | None | The editing operation is not restricted. | @@ -63,41 +64,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the @Component struct ListItemExample { private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - @State editFlag: boolean = false build() { Column() { List({ space: 20, initialIndex: 0 }) { - ListItem() { - Text('sticky:Normal , click me edit list') - .width('100%').height(40).fontSize(12).fontColor(0xFFFFFF) - .textAlign(TextAlign.Center).backgroundColor(0x696969) - .onClick(() => { - this.editFlag = !this.editFlag - }) - }.sticky(Sticky.Normal) - ForEach(this.arr, (item) => { ListItem() { Text('' + item) .width('100%').height(100).fontSize(16) .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) - }.editable(this.editFlag) + } }, item => item) - } - .editMode(true) - .onItemDelete((index: number) => { - console.info(this.arr[index - 1] + 'Delete') - this.arr.splice(index - 1,1) - this.editFlag = false - return true - }).width('90%') + }.width('90%') }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) } } ``` -![en-us_image_0000001257138339](figures/en-us_image_0000001257138339.gif) +![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif) ```ts // xxx.ets diff --git a/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md b/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md index 06c65aa8f4147948d57226c034da55dd5e1e4840..f0e9f85f122e630c6f73f5443d0d4260abaaf5cf 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-relativecontainer.md @@ -16,7 +16,7 @@ The **\** component is used for element alignment in complex * A child component can set the container or another child component as the anchor. * To show in the **\**, child components must have an ID. The container ID is fixed at **__container__**. * Three positions of the child component in a direction can use three positions of the container or another child components in the same direction as anchors. If anchors are set for more than two positions in a single direction, the third position is skipped. - * The child component size set on the frontend page is not affected by the **\** rules. + * The child component size set on the frontend page is not affected by the **\** rules. If two or more **alignRules** values are set for one direction of the child component, you are not advised to set the size for this direction. * If offset is required after the alignment, it can be set through **offset**. * Exceptions * When a mutual or circular dependency occurs, none of the child components in the container are drawn. @@ -39,62 +39,60 @@ RelativeContainer() struct Index { build() { Row() { - Button("Extra button").width(100).height(50) RelativeContainer() { - Button("Button 1") - .width(120) - .height(30) + Row().width(100).height(100) + .backgroundColor("#FF3333") .alignRules({ - middle: { anchor: "__container__", align: HorizontalAlign.Center }, + top: {anchor: "__container__", align: VerticalAlign.Top}, + left: {anchor: "__container__", align: HorizontalAlign.Start} }) - .id("bt1") - .borderWidth(1) - .borderColor(Color.Black) + .id("row1") - Text("This is text 2") - .fontSize(20) - .padding(10) + Row().width(100).height(100) + .backgroundColor("#FFCC00") .alignRules({ - bottom: { anchor: "__container__", align: VerticalAlign.Bottom }, - top: { anchor: "bt1", align: VerticalAlign.Bottom }, - right: { anchor: "bt1", align: HorizontalAlign.Center } + top: {anchor: "__container__", align: VerticalAlign.Top}, + right: {anchor: "__container__", align: HorizontalAlign.End} }) - .id("tx2") - .borderWidth(1) - .borderColor(Color.Black) - .height(30) - - Button("Button 3") - .width(100) - .height(100) + .id("row2") + + Row().height(100) + .backgroundColor("#FF6633") .alignRules({ - left: { anchor: "bt1", align: HorizontalAlign.End }, - top: { anchor: "tx2", align: VerticalAlign.Center }, - bottom: { anchor: "__container__", align: VerticalAlign.Bottom } + top: {anchor: "row1", align: VerticalAlign.Bottom}, + left: {anchor: "row1", align: HorizontalAlign.End}, + right: {anchor: "row2", align: HorizontalAlign.Start} }) - .id("bt3") - .borderWidth(1) - .borderColor(Color.Black) + .id("row3") - Text("This is text 4") - .fontSize(20) - .padding(10) + Row() + .backgroundColor("#FF9966") .alignRules({ - left: { anchor: "tx2", align: HorizontalAlign.End }, - right: { anchor: "__container__", align: HorizontalAlign.End }, - top: { anchor: "__container__", align: VerticalAlign.Top }, - bottom: { anchor: "bt3", align: VerticalAlign.Top } + top: {anchor: "row3", align: VerticalAlign.Bottom}, + bottom: {anchor: "__container__", align: VerticalAlign.Bottom}, + left: {anchor: "__container__", align: HorizontalAlign.Start}, + right: {anchor: "row1", align: HorizontalAlign.End} }) - .id("tx4") - .borderWidth(1) - .borderColor(Color.Black) + .id("row4") + + Row() + .backgroundColor("#FF66FF") + .alignRules({ + top: {anchor: "row3", align: VerticalAlign.Bottom}, + bottom: {anchor: "__container__", align: VerticalAlign.Bottom}, + left: {anchor: "row2", align: HorizontalAlign.Start}, + right: {anchor: "__container__", align: HorizontalAlign.End} + }) + .id("row5") } - .width(200).height(200) - .backgroundColor(Color.Orange) + .width(300).height(300) + .margin({left: 100}) + .border({width:2, color: "#6699FF"}) } .height('100%') } } + ``` ![relative container](figures/relativecontainer.png) diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 24021435e468e24216d765a0d60ffad2e2d3824c..849218cf45e69fd423b020dd8dd26381933c1fe3 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -54,7 +54,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## SwiperController -Controller of the **\** component. You can bind this object to the **** component and use it to control page switching. +Controller of the **\** component. You can bind this object to the **\** component and use it to control page switching. ### showNext @@ -76,7 +76,7 @@ Stops an animation. **Parameters** -| Name | Type | Mandatory.| Description| +| Name | Type | Mandatory | Description| | --------- | ---------- | ------ | -------- | | callback | () => void | No | Callback invoked when the animation stops.| @@ -88,6 +88,10 @@ onChange(event: (index: number) => void) Triggered when the index of the currently displayed child component changes. +> **NOTE** +> +> When the **\** component is used together with **LazyForEach**, the subpage UI cannot be refreshed in the **onChange** event. + **Return value** | Name | Type | Description| diff --git a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md index daf2238308091eaab298b7a757f0ef6e844eceb3..b2802444ab2e297ffc599263910afea57fee2465 100644 --- a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -20,7 +20,7 @@ animateTo(value: AnimateParam, event: () => void): void | -------- | -------- | -------- | | duration | number | Animation duration, in ms.
Default value: **1000**| | tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.
Default value: **1.0**| -| curve | Curve \| Curves | Animation curve.
Default value: **Curve.Linear**| +| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.
Default value: **Curve.Linear**| | delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.
Default value: **0**| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| | playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.
Default value: **PlayMode.Normal**| diff --git a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 4c6a674c969dcbbfdacdafbf39ccc008bdeb178d..22e6077c68daf2b9cc835c9af1b514ed7670e57e 100644 --- a/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -1674,7 +1674,7 @@ struct Fill { region.lineTo(270, 90) region.closePath() // Fill path - this.offContext.fillStyle = 'green' + this.offContext.fillStyle = '#00ff00' this.offContext.fill(region, "evenodd") var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -2534,7 +2534,7 @@ struct CanvasExample { .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.save() // save the default state - this.offContext.fillStyle = "green" + this.offContext.fillStyle = "#00ff00" this.offContext.fillRect(20, 20, 100, 100) this.offContext.restore() // restore to the default state this.offContext.fillRect(150, 75, 100, 100) @@ -2575,7 +2575,7 @@ struct CanvasExample { .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.save() // save the default state - this.offContext.fillStyle = "green" + this.offContext.fillStyle = "#00ff00" this.offContext.fillRect(20, 20, 100, 100) this.offContext.restore() // restore to the default state this.offContext.fillRect(150, 75, 100, 100) @@ -2625,9 +2625,9 @@ Creates a linear gradient. .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.offContext.createLinearGradient(50,0, 300,100) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') this.offContext.fillStyle = grad this.offContext.fillRect(0, 0, 500, 500) var image = this.offContext.transferToImageBitmap() @@ -2679,9 +2679,9 @@ Creates a linear gradient. .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.offContext.createRadialGradient(200,200,50, 200,200,200) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') + grad.addColorStop(0.0, '#ff0000') + grad.addColorStop(0.5, '#ffffff') + grad.addColorStop(1.0, '#00ff00') this.offContext.fillStyle = grad this.offContext.fillRect(0, 0, 500, 500) var image = this.offContext.transferToImageBitmap() diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index ecdaffd3f3407f079e1044031caaf43a9d2af843..2256aa963c944561e69ccbf110a656347afd448a 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -8,7 +8,7 @@ The framework provides four pixel units, with vp as the reference data unit. | px | Physical pixel unit of the screen. | | vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified.| | fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**. For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels.| +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | ## Pixel Unit Conversion diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 8425cf29444183671c4fd8e3389bd0ffa28840f9..a603c54bc5f16e877420e80c1714ac16f70e2123 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -17,7 +17,7 @@ The location attributes set the alignment mode, layout direction, and position o | position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| | markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} | | offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} | -| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| +| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container. This attribute is valid only when the container is [\](ts-container-relativecontainer.md).
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md index 2c8ba7c33a29b398ae2144c6435fe0d6a10671a6..2e0e8610515d57f66aa28d424140c657da95f368 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-area-change-event.md @@ -42,4 +42,4 @@ struct AreaExample { } ``` -![en-us_image_0000001257058403](figures/en-us_image_0000001257058403.gif) +![en-us_image_0000001189634870](figures/en-us_image_0000001189634870.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md b/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md index 6230df00006aae28708d76f6662ced618a3a8351..7b1db0758f125113d863399d75a7672db10c302a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md @@ -12,14 +12,14 @@ The show/hide event is triggered when a component is mounted or unmounted from t | Name | Bubbling Supported| Description | | ------------------------------------------------ | -------- | -------------------------- | | onAppear(event: () => void) | No | Triggered when the component is displayed.| -| onDisappear(event: () => void) | No | Triggered when the component is hidden. | +| onDisAppear(event: () => void) | No | Triggered when the component is hidden.| ## Example ```ts // xxx.ets -import prompt from '@ohos.prompt' +import promptAction from '@ohos.promptAction' @Entry @Component @@ -38,14 +38,14 @@ struct AppearExample { Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold) .onAppear(() => { this.changeAppear = 'Hide Text' - prompt.showToast({ + promptAction.showToast({ message: 'The text is shown', duration: 2000 }) }) .onDisAppear(() => { this.changeAppear = 'Show Text' - prompt.showToast({ + promptAction.showToast({ message: 'The text is hidden', duration: 2000 }) diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index c7321b0cf5becf80f21786e52ae8d807ae892049..be5c9602bb092bc06f992c8502d00e36dcb2a94a 100644 --- a/en/application-dev/reference/errorcodes/Readme-EN.md +++ b/en/application-dev/reference/errorcodes/Readme-EN.md @@ -12,6 +12,7 @@ - [Event Error Codes](errorcode-CommonEventService.md) - [DistributedNotificationService Error Codes](errorcode-DistributedNotificationService.md) - UI Page + - [Animator Error Codes](errorcode-animator.md) - [promptAction Error Codes](errorcode-promptAction.md) - [Router Error Codes](errorcode-router.md) - Graphics @@ -33,10 +34,15 @@ - Security - [Ability Access Control Error Codes](errorcode-access-token.md) - [HUKS Error Codes](errorcode-huks.md) + - [User Authentication Error Codes](errorcode-useriam.md) - Data Management - [RDB Error Codes](errorcode-data-rdb.md) + - [DataShare Error Codes](errorcode-datashare.md) + - [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md) - [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) - [Preferences Error Codes](errorcode-preferences.md) +- File Management + - [File Management Error Codes](errorcode-filemanagement.md) - Network Management - [Upload and Download Error Codes](errorcode-request.md) - Connectivity @@ -68,9 +74,10 @@ - [Vibrator Error Codes](errorcode-vibrator.md) - [System Parameter Error Codes](errorcode-system-parameterV9.md) - [USB Error Codes](errorcode-usb.md) + - [Update Error Codes](errorcode-update.md) - Customization Management - [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md) -- Language Base Class Library +- Utils - [Utils Error Codes](errorcode-utils.md) - Test - [UiTest Error Codes](errorcode-uitest.md) diff --git a/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md b/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md index be39f168e05c7b753f20ce07481d35b32f8df032..fc58fc8c6dcc0f1fd3351338bf38c9aa65f8e6b4 100644 --- a/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md +++ b/en/application-dev/reference/errorcodes/errorcode-CommonEventService.md @@ -3,125 +3,160 @@ ## 1500001 Want Action Is Null **Error Message** + Want action is null **Description** -This error code is reported when the **Action** attribute in the **want** is null for the event to send. + +This error code is reported when the **Action** attribute in the **want** object is null for the event to send. **Possible Causes** -The **Action** attribute in the **want** is null for the event to send. + +The **Action** attribute in the **want** object is null for the event to send. **Solution** -Make sure the **Action** attribute in the **want** is not null. + +Make sure the **Action** attribute in the **want** object is not null. ## 1500002 Failed to Send Common Events from a Sandbox Application **Error Message** + sandbox application can not send common event **Description** + This error code is reported when an attempt is made to send a common event from a sandbox application. **Possible Causes** + Common events from a sandbox application are blocked. **Solution** + Check whether the application used to send a common event is a sandbox application. If so, switch to another application. ## 1500003 Event Sending Frequency Is Too High **Error Message** + common event send frequency too high **Description** + This error code is reported when the application sends common events too frequently. **Possible Causes** + The number of common events sent by the application in a given time frame has reached the maximum. **Solution** + Do not send common events too frequently. ## 1500004 Failed to Send System Common Events **Error Message** + not System services or System app **Description** + This error code is reported when the application cannot send system common events. **Possible Causes** + The application is not a system application or system service. **Solution** + Make sure the application to send system common events is a system application or system service. ## 1500005 Subscriber Not Found **Error Message** + subscriber can not found **Description** + This error code is reported when the subscriber cannot be found. **Possible Causes** + The subscriber is deleted. **Solution** + Check whether the subscription has already been canceled. If the subscription has been canceled, the subscriber is deleted. ## 1500006 Invalid User ID **Error Message** -usreId is invalid + +userId is invalid **Description** + This error code is reported when the user ID is invalid. **Possible Causes** -The user ID is different from the system user ID, or the application is not a system application or subsystem process. -**Solution** -Check whether the current user ID is the same as the system user ID. If they are different, check whether the application is a system application or subsystem process +The user ID is different from the system user ID, or the application is not a system application or system service. +**Solution** +1. Make sure the current user ID is the same as the system user ID. +2. Make sure the application is a system application or system service. ## 1500007 Failed to Send a Request Through IPC **Error Message** + message send error **Description** + This error code is reported when the attempt to send a request through IPC fails. **Possible Causes** + The connection object fails to be created. **Solution** + Do not set up connections frequently. Try again later. ## 1500008 Failed to Read Data **Error Message** + CEMS error **Description** + This error code is reported when an error occurs on the server. **Possible Causes** + A service exception occurs when the server processes data. **Solution** + Try again later. ## 1500009 System Error **Error Message** + system error **Description** + This error code is reported when an exception occurs in the system during service processing, for example, when the current system time fails to be obtained. **Possible Causes** + A system fault occurs. **Solution** -Try again later. + +Try again later. \ No newline at end of file diff --git a/en/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md b/en/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md index 6d7570ee5f63d167ba114d0fb7cbd2954d025dbb..9ecc659b536a7fe844ada31138d292593e0dc41a 100644 --- a/en/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md +++ b/en/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md @@ -8,11 +8,11 @@ Internal Error. **Description** -This error code is reported when an internal processing error occurs, such as a memory allocation or multi-thread processing error. +This error code is reported when an internal error occurs, such as a memory allocation or multi-thread processing error. **Possible Causes** -1. Common kernel errors such as memory allocation and multi-thread processing errors occur. +A common kernel error, such as a memory allocation or multi-thread processing error, occurs. **Solution** @@ -36,8 +36,9 @@ This error code is reported when a serialization or deserialization error occurs **Solution** -1. Make sure the input parameter value is within the valid range. -2. Make sure the notification subsystem is not being started. +1. Make sure the input parameter value length is within the valid range. +2. Make sure the input parameter value is valid. +3. Make sure the notification subsystem has been started. ## 1600003 Failed to Connect to the Service @@ -47,7 +48,7 @@ Failed to connect to service. **Description** -This error code is reported when the notification subsystem is abnormal due to a service connection failure. +This error code is reported when the connection with the notification subsystem fails. **Possible Causes** @@ -66,15 +67,15 @@ Notification is not enabled. **Description** -This error code is reported when the notification function is disabled. +This error code is reported when the notification feature is disabled. **Possible Causes** -The notification function is set to its default state (default) or manually disabled. +The notification feature is not enabled manually. By default, this feature is disabled. **Solution** -Enable the notification function. +Enable the notification feature. ## 1600005 Notification Slot Is Disabled @@ -102,16 +103,16 @@ Notification is not allowed to remove. **Description** -This error code is reported when **isUnremoveable** is set to **true** and an attempt is made to remove all notifications or when **isRemoveAllowed** is set to **false** and an attempt is made to remove a specific notification. +This error code is reported when the notification removal does not comply with the permission settings. **Possible Causes** -1. When **isUnremoveable** is set to **true**, notifications can only be removed on a one-by-one basis. -2. When **isRemoveAllowed** is set to **false**, no notification can be deleted. +1. When **isUnremovable** is set to **true**, notifications can only be removed on a one-by-one basis. +2. When **isRemoveAllowed** is set to **false**, no notification can be removed. **Solution** -1. Check whether **unremovable** is set to **true**. +1. Check whether **isUnremovable** is set to **true** 2. Check whether **isRemoveAllowed** is set to **false**. ## 1600007 Notification Not Found @@ -131,7 +132,7 @@ This error code is reported when the target notification is not found. **Solution** -Make sure the notification exists. +1. Make sure the notification exists. ## 1600008 User Not Found @@ -208,7 +209,7 @@ This error code is reported when the template configuration file fails to be rea **Solution** 1. Check for the **/system/etc/notification_template/external.json** file. -2. Update the version to 3.2 or later. +2. Update the system version to 3.2 or later. ## 17700001 Bundle Name Not Found @@ -228,4 +229,5 @@ This error code is reported when the specified bund name is not found. **Solution** 1. Verify the bundle name. -2. Make sure the application has been installed. + +2. Make sure the application has been installed. \ No newline at end of file diff --git a/en/application-dev/reference/errorcodes/errorcode-ability.md b/en/application-dev/reference/errorcodes/errorcode-ability.md index f6dc19fb54d8e0a69fdec022f7f9eaa4dcf55bf4..8c7aa0c06ccc996e96b05514e6f85ccfe8d22a69 100644 --- a/en/application-dev/reference/errorcodes/errorcode-ability.md +++ b/en/application-dev/reference/errorcodes/errorcode-ability.md @@ -4,7 +4,7 @@ **Error Message** -Input error. The specified ability name does not exist. +Incorrect Ability name. The specified Ability name does not exist. **Description** @@ -23,7 +23,7 @@ The ability to query does not exist. **Error Message** -Ability type error. The specified ability type is wrong. +Incorrect Ability type. **Description** @@ -42,7 +42,7 @@ The ability with the specified type does not support the API invocation. **Error Message** -Input error. The specified id does not exist. +Input error. The specified ID does not exist. **Description** @@ -78,7 +78,7 @@ Check whether the application meets the visibility restriction of the started ap **Error Message** -Can not cross user operations. +Cross-user operations are not allowed. **Description** @@ -96,7 +96,7 @@ Do not perform a cross-user operation. **Error Message** -Service busyness. There are concurrent tasks, waiting for retry. +Service busy, please wait and try again. **Description** @@ -114,7 +114,7 @@ Try again later. **Error Message** -Crowdtest App Expiration. +Crowdtest App Expired. **Description** @@ -132,7 +132,7 @@ Check whether the crowdtesting application has expired. **Error Message** -Can not start ability in wukong mode. +Ability cannot be started or sotpped in Wukong mode. **Description** @@ -150,7 +150,7 @@ Do not start or stop an ability in Wukong mode. **Error Message** -Can not operation with continue flag. +The call with the continuation flag is forbidden. **Description** @@ -168,7 +168,7 @@ Remove the continuation flag. **Error Message** -Context does not exist. +The context does not exist. **Description** @@ -186,7 +186,7 @@ Use the correct context. **Error Message** -Internal Error. +Internal error. **Description** @@ -204,7 +204,7 @@ Ensure sufficient sytem memory. **Error Message** -Network error. The network is abnormal. +Network error. **Description** @@ -222,7 +222,7 @@ Try again later or reconnect to the network. **Error Message** -Free install not support. The applicaiotn dose not support free install. +Installation-free is not supported. **Description** @@ -240,7 +240,7 @@ Check whether the application supports installation-free. **Error Message** -Not top ability. The application is not top ability. +The ability is not on the top of UI. **Description** @@ -258,7 +258,7 @@ Ensure that the ability is displayed on the top of the UI. **Error Message** -Free install busyness. There are concurrent tasks, waiting for retry. +Installation-free service is busy, please wait and try again later. **Description** @@ -276,7 +276,7 @@ Try again later. **Error Message** -Free install timeout. +Installation-free time out. **Description** @@ -294,7 +294,7 @@ Try again later. **Error Message** -Can not free install other ability. +Installation-free is not allowed for other applications. **Description** @@ -312,7 +312,7 @@ Apply installation-free only for the current application. **Error Message** -Not support cross device free install. +Cross-device installation-free is not supported. **Description** @@ -330,7 +330,7 @@ Use installation-free on the same device. **Error Message** -execute shell command failed. +Failed to run the shell command. **Description** @@ -348,7 +348,7 @@ Use a valid shell command. **Error Message** -Invalid wantagent object. +Invalid wantAgent object. **Description** @@ -366,7 +366,7 @@ Pass a valid **wantAgent** object in the API. **Error Message** -wantAgent object not found. +the wantAgent object does not exist. **Description** @@ -384,7 +384,7 @@ Pass a valid **wantAgent** object in the API. **Error Message** -wangAgent object canceled. +wangAgent object has been canceled. **Description** @@ -402,7 +402,7 @@ Pass a valid **wantAgent** object in the API. **Error Message** -Input error. The specified uri does not exist. +The ability with the specified URI does not exist. **Description** @@ -420,7 +420,7 @@ Check the ability with the specified URI. **Error Message** -Ability type error. The specified ability type is wrong. +Incorrect ability type. **Description** @@ -428,7 +428,7 @@ This error code is reported when the ability type invoked by the API is incorrec **Possible Causes** -The ability with the specified type does not support the API call. +The ability with the specified type does not support the API invocation. **Solution** @@ -439,7 +439,7 @@ The ability with the specified type does not support the API call. **Error Message** -Caller released. The caller has been released. +The caller has been released. **Description** @@ -457,7 +457,7 @@ Register a valid caller again. **Error Message** -Callee Invalid. The callee does not exist. +The callee does not exist. **Description** @@ -493,7 +493,7 @@ Check whether the caller has registered. **Error Message** -Method registered. The method has registered. +The method has registered. **Description** @@ -511,7 +511,7 @@ Check whether the method has been registered. **Error Message** -Method not registered. The method has not registered. +The method is not registered. **Description** @@ -529,7 +529,7 @@ Check whether the method has been registered. **Error Message** -Mission id error. The specified mission id does not exist. +The specified mission id does not exist. **Description** @@ -547,7 +547,7 @@ Check the mission ID. **Error Message** -Input error. The specified mission listener id does not exist. +The specified mission listener does not exist. **Description** @@ -565,7 +565,7 @@ Check the mission listener ID. **Error Message** -The specified bundleName is invalid. +Invalid bundle name. **Description** @@ -583,7 +583,7 @@ Check whether the bundle has been installed. **Error Message** -The specified hqf is invalid. Hqf may not exist or inaccessible. +Invalid patch package. **Description** @@ -602,7 +602,7 @@ The patch package does not exist or is inaccessible. **Error Message** -Deploy hqf failed. +Failed to deploy the patch. **Description** @@ -626,7 +626,7 @@ Check whether the patch package complies with the deployment rules. **Error Message** -Switch hqf failed. +Failed to enable the patch package. **Description** @@ -644,7 +644,7 @@ Check the state of the patch package. **Error Message** -Delete hqf failed. +Failed to enable the patch package. **Description** @@ -662,7 +662,7 @@ Check the state of the patch package. **Error Message** -Load patch failed. +Failed to load the patch. **Description** @@ -680,7 +680,7 @@ Check whether the patch package is correct. **Error Message** -Unload patch failed. +Failed to unload the patch. **Description** @@ -702,7 +702,7 @@ Internal error. **Description** -This error code is returned when an error occurs during internal processing, such as memory application or multi-thread processing. +This error code is reported when an error occurs during internal processing, such as memory application or multi-thread processing. **Possible Causes** @@ -710,4 +710,4 @@ Common kernel errors such as memory application and multi-thread processing erro **Solution** -Ensure sufficient system memory. +Ensure sufficient sytem memory. diff --git a/en/application-dev/reference/errorcodes/errorcode-avsession.md b/en/application-dev/reference/errorcodes/errorcode-avsession.md index 98b811bd159ccf0be5eed06746622a3686e96bce..a072aa68d0d35b21470b3c68e55b06a856466932 100644 --- a/en/application-dev/reference/errorcodes/errorcode-avsession.md +++ b/en/application-dev/reference/errorcodes/errorcode-avsession.md @@ -4,7 +4,7 @@ **Error Message** -Session service exception +Session service exception. **Description** @@ -24,7 +24,7 @@ The session service is killed during session restart. **Error Message** -The session does not exist +The session does not exist. **Description** @@ -44,7 +44,7 @@ The session has been destroyed, and no session record exists on the server. **Error Message** -The session controller does not exist +The session controller does not exist. **Description** @@ -62,7 +62,7 @@ Query the session record and create the corresponding controller. **Error Message** -The remote session connection failed +The remote session connection failed. **Description** @@ -80,7 +80,7 @@ Stop sending control commands to the session. Subscribe to output device changes **Error Message** -Invalid session command +Invalid session command. **Description** @@ -98,7 +98,7 @@ Stop sending the command or event. Query the commands supported by the session, **Error Message** -The session not active +The session is not activated. **Description** @@ -116,7 +116,7 @@ Stop sending the command or event. Subscribe to the session activation status, a **Error Message** -Command or event overload +Too many commands or events. **Description** diff --git a/en/application-dev/reference/errorcodes/errorcode-backgroundTaskMgr.md b/en/application-dev/reference/errorcodes/errorcode-backgroundTaskMgr.md index 401e5446fd45bd892cb487f6265fa598e320c04d..ffd2abc37593135bd0d1b921d98cbec3319501b2 100644 --- a/en/application-dev/reference/errorcodes/errorcode-backgroundTaskMgr.md +++ b/en/application-dev/reference/errorcodes/errorcode-backgroundTaskMgr.md @@ -71,7 +71,6 @@ Continuous task verification failed. 2. The application repeatedly cancels a continuous task. 3. The value of **bgMode** is invalid because no continuous task type is configured for **backgroundModes** in the application's configuration file. 4. A non-PC device requests the continuous task **KEEPING_TASK**, which is available only for PCs. -5. A third-party application requests the continuous task **WIFI_INTERACTION** or **VOIP**, which is available only for system applications. **Solution** diff --git a/en/application-dev/reference/errorcodes/errorcode-bundle.md b/en/application-dev/reference/errorcodes/errorcode-bundle.md index 24ae7aa6133720292e8ba686342e492bb87b2434..54c246c0d0d23b2bc301910be46b407710e7bdfa 100644 --- a/en/application-dev/reference/errorcodes/errorcode-bundle.md +++ b/en/application-dev/reference/errorcodes/errorcode-bundle.md @@ -9,6 +9,7 @@ The specified bundle name is not found. When a query API is called, the bundle name passed in does not exist. **Possible Causes** + 1. The bundle name is misspelled. 2. The corresponding bundle is not installed. @@ -42,11 +43,11 @@ When a query API is called, the ability name passed in does not exist. **Possible Causes** 1. The ability name is misspelled. -2. The corresponding bundle is not installed. +2. The application does not have the ability specified by **abilityName**. **Solution** 1. Check whether the spelling of the ability name is correct. -2. Check whether the ability is installed. +2. Check whether the application has the ability specified by **abilityName**. ## 17700004 User ID Does Not Exist @@ -57,16 +58,17 @@ The specified user ID is not found. When a user-related API is called, the user ID passed in does not exist. **Possible Causes** -The user ID is incorrect. The user does not exist. +1. Incorrect username. +2. The user does not exist in the system. **Solution** 1. Check whether the user ID is correct. 2. Check whether the user exists. -## 17700005 Application ID Does Not Exist +## 17700005 appId Is an Empty String **Error Message** -The specified app ID is not found. +The specified app ID is empty string. **Description** When an API of the **appControl** module is called, the application ID passed in does not exist. @@ -124,7 +126,7 @@ When the **install** API of the **installer** module is called, the HAP passed i **Solution** 1. Check whether the HAP is in ZIP format. -2. Check whether the configuration file is in [JSON format](../../quick-start/stage-structure.md). +2. Check whether the configuration file is in [JSON format](../../quick-start/application-configuration-file-overview-stage.md). 3. Check whether an error message is displayed when DevEco Studio compiles the HAP. If necessary fields are missing, an error message will be displayed. ## 17700011 Bundle Installation Failure Due to Signature Verification Failure @@ -144,8 +146,9 @@ Calling the **install** API of the **installer** module to install the bundle fa **Solution** 1. Check whether the HAP is signed. -2. Check whether the same certificate is used for signing multiple HAPs. -3. Check whether the certificate used for signing the upgrade HAP is the same as the certificate used for signing the installed HAP. +2. Ensure that the signature certificate of the HAP is applied for from the application market. +3. Check whether the same certificate is used for signing multiple HAPs. +4. Check whether the certificate used for signing the upgrade HAP is the same as the certificate used for signing the installed HAP. ## 17700012 Bundle Installation Failure Due to Invalid File Path or Too Large File @@ -165,7 +168,7 @@ Calling the **install** API of the **installer** module to install the bundle fa 2. Check whether the HAP is read only or executable. 3. Check whether the size of the HAP exceeds 4 GB. -## 17700015 Bundle Installation Failure Due to Different Configuration Information of Multiple HAP Packages +## 17700015 Bundle Installation Failure Due to Different Configuration Information of Multiple HAPs **Error Message** Failed to install the HAPs because they have different configuration information. @@ -205,7 +208,7 @@ Calling the **install** API of the **installer** module to install the bundle fa The version number is earlier than the version in use. **Solution** -Ensure that the version of the bundle to install is later than the version in use. +Ensure that the version of the bundle to install is not earlier than the version in use. ## 17700020 Failure to Uninstall Preinstalled Applications @@ -298,7 +301,8 @@ When an API of the **defaultAppManager** module is called, the type passed in is 2. The type passed in the API does not exist. **Solution** -Check whether the spelling of type is correct. +1. Check whether the spelling of type is correct. +2. Enter a type that exists. ## 17700026 Bundle Disabled @@ -368,4 +372,6 @@ The application is a system application and the **AllowAppDataNotCleared** field **Solution** 1. Check whether the application is a system application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **isSystemApp** is **true**. -2. Check whether the **AllowAppDataNotCleared** field is configured for the application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **userDataClearable** is **true**. +2. Check whether the **AllowAppDataNotCleared field** is configured for the application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **userDataClearable** is **true**. + + diff --git a/en/application-dev/reference/errorcodes/errorcode-datashare.md b/en/application-dev/reference/errorcodes/errorcode-datashare.md new file mode 100644 index 0000000000000000000000000000000000000000..1dae1ebbae1af4b9940ffa6a81e9130eeaa4a94d --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-datashare.md @@ -0,0 +1,21 @@ +# DataShare Error Codes + +## 15700010 Failed to Create a DataShareHelper + +**Error Message** + +The dataShareHelper is not initialized successfully. + +**Description** + +The **DataShareHelper** class fails to be created. + +**Possible Causes** + +1. The **uri** specified in **createDataHelper** is incorrect. +2. The **context** specified in **createDataHelper** is incorrect. **DataShare** supports only the stage model. + +**Solution** + +1. Obtain the correct URI. +2. Check that the context of the stage model is used. diff --git a/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md new file mode 100644 index 0000000000000000000000000000000000000000..0ebad934ac37ea27b349fa9e2b0c0d4941f83ca3 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md @@ -0,0 +1,19 @@ +# Distributed Data Object Error Codes + +## 15400001 Failed to Create the In-Memory Database + +**Error Message** + +Create table failed. + +**Description** + +The in-memory database fails to be created. + +**Possible Causes** + +An object with the same session ID already exists. + +**Solution** + +Check for the object has been added to the same session. diff --git a/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md b/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md index da3088db9008d5077568765065e62efa5e1bbd11..5d1c22ab4c978474af0f12f896d0159857e271a8 100644 --- a/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md +++ b/en/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @@ -66,20 +66,20 @@ Not found. **Description** -Related data is found when **deleteKVStore()**, **delete()**, **deleteBatch()**, or **get()** is called. +Related data is not found when **deleteKVStore()**, **sync()**, or **get()** is called. **Possible Causes** The possible causes are as follows: 1. The KV store to delete does not exist or has been deleted. 2. The data queried does not exist or has been deleted. -3. The data to delete does not exist or has been deleted. +3. The KV store specified for the data synchronization operation does not exist or has been deleted. **Solution** 1. Before deleting a KV store, check that the KV store exists. 2. When querying data in a KV store, check whether the query keywords are correct. -3. When deleting data from a KV store, check that the keyword for the deletion is correct and the data to delete exists. +3. Before synchronizing data, check that the related KV store is available. ## 15100005 KV Store or Result Set Closed diff --git a/en/application-dev/reference/errorcodes/errorcode-filemanagement.md b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md new file mode 100644 index 0000000000000000000000000000000000000000..42192691a4127493dfe94fbef0d67135f870a253 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-filemanagement.md @@ -0,0 +1,721 @@ +# File Management Error Codes +The error codes of the file management subsystem consist of the following: + +- Basic file I/O error codes +- User data management error codes +- User file access error codes +- Spatial statistics error codes + +## Basic File I/O Error Codes + +### 13900001 Operation Not Permitted + +**Error Message** +Operation not permitted + +**Possible Causes** +The current operation on the file is not allowed. + +**Solution** +Check the permission for the file. + +### 13900002 File or Directory Not Exist + +**Error Message** +No such file or directory + +**Possible Causes** +The file or directory does not exist. + +**Solution** +Check whether the file directory exists. + +### 13900003 Process Not Exist + +**Error Message** +No such process + +**Possible Causes** +The process does not exist. + +**Solution** +1. Check whether the process is killed unexpectedly. +2. Check whether the service related to the process has started. + +### 13900004 System Call Interrupted + +**Error Message** +Interrupted system call + +**Possible Causes** +The system call is interrupted by another thread. + +**Solution** +1. Check the multi-thread code logic. +2. Invoke the system call again. + +### 13900005 I/O Error + +**Error Message** +I/O error + +**Possible Causes** +The I/O request is invalid. + +**Solution** +Initiate the I/O request again. + +### 13900006 Device or Address Not Exist + +**Error Message** +No such device or address + +**Possible Causes** +The device information or address is incorrect. + +**Solution** +Check that the device information or address is correct. + +### 13900007 Long Parameter List + +**Error Message** +Arg list too long + +**Possible Causes** +The parameter list is too long. + +**Solution** +Reduce the number of parameters. + +### 13900008 Invalid File Descriptor + +**Error Message** +Bad file descriptor + +**Possible Causes** +This file descriptor is closed. + +**Solution** +Check whether the file descriptor is closed. + +### 13900009 Child Process Not Exist + +**Error Message** +No child processes + +**Possible Causes** +The child process cannot be created. + +**Solution** +Check the maximum number of processes in the system. + +### 13900010 Resource Unavailable + +**Error Message** +Try again + +**Possible Causes** +The resources are blocked. + +**Solution** +Request resources. + +### 13900011 Memory Overflow + +**Error Message** +Out of memory + +**Possible Causes** +A memory overflow occurs. + +**Solution** +1. Check the memory overhead. +2. Control the memory overhead. + +### 13900012 Permission Denied + +**Error Message** +Permission denied + +**Possible Causes** +1. You do not have the permission to operate the file. +2. The file sandbox path is incorrect. + +**Solution** +1. Check that you have the permission to operate the file. +2. Check that the file sandbox path is correct. + +### 13900013 Incorrect Address + +**Error Message** +Bad address + +**Possible Causes** +The address is incorrect. + +**Solution** +Check that the address is correct. + +### 13900014 Device or Resource Not Available + +**Error Message** +Device or resource busy + +**Possible Causes** +The requested resource is unavailable. + +**Solution** +Request the resource again. + +### 13900015 File Already Exists + +**Error Message** +File exists + +**Possible Causes** +The file to be created already exists. + +**Solution** +Check whether the file path is correct. + +### 13900016 Invalid Cross-Device Link + +**Error Message** +Cross-device link + +**Possible Causes** +The link between devices is incorrect. + +**Solution** +Check the devices and create the link correctly. + +### 13900017 Device Not Exist + +**Error Message** +No such device + +**Possible Causes** +The device is not identified. + +**Solution** +Check the connection to the target device. + +### 13900018 Invalid Directory + +**Error Message** +Not a directory + +**Possible Causes** +The specified directory is invalid. + +**Solution** +Check that the directory is correct. + +### 13900019 The Specified Object Is a Directory + +**Error Message** +Is a directory + +**Possible Causes** +The specified object is a directory. + +**Solution** +Check that the specified data is correct. + +### 13900020 Invalid Parameter + +**Error Message** +Invalid argument + +**Possible Causes** +Invalid input parameter is detected. + +**Solution** +Check that the input parameters are valid. + +### 13900021 Too Many File Descriptors Opened + +**Error Message** +File table overflow + +**Possible Causes** +The number of file descriptors opened has reached the limit. + +**Solution** +Close the file descriptors that are no longer required. + +### 13900022 Too Many Files Opened + +**Error Message** +Too many open files + +**Possible Causes** +The number of files opened has reached the limit. + +**Solution** +Close the files that are not required. + +### 13900023 Text File Not Respond + +**Error Message** +Text file busy + +**Possible Causes** +The executable file of the program is in use. + +**Solution** +Close the program that is being debugged. + +### 13900024 File Oversized + +**Error Message** +File too large + +**Possible Causes** +The file size exceeds the limit. + +**Solution** +Check whether the file size exceeds the limit. + +### 13900025 Insufficient Space on the Device + +**Error Message** +No space left on device + +**Possible Causes** +The device storage space is insufficient. + +**Solution** +Clear the space of the device. + +### 13900026 Invalid Shift + +**Error Message** +Illegal seek + +**Possible Causes** +Seek is used in pipe or FIFO. + +**Solution** +Check the use of seek. + +### 13900027 Read-Only File System + +**Error Message** +Read-only file system + +**Possible Causes** +The file system allows read operations only. + +**Solution** +Check whether the file is read-only. + +### 13900028 Links Reach the Limit + +**Error Message** +Too many links + +**Possible Causes** +The number of links to the file has reached the limit. + +**Solution** +Delete the links that are no longer required. + +### 13900029 Resource Deadlock + +**Error Message** +Resource deadlock would occur + +**Possible Causes** +Resource deadlock occurs. + +**Solution** +Terminate the deadlock process. + +### 13900030 Long File Name + +**Error Message** +Filename too Long + +**Possible Causes** +The length of the path or file name exceeds the limit. + +**Solution** +Modify the path or file name. + +### 13900031 Function Not Implemented + +**Error Message** +Function not implemented + +**Possible Causes** +The function is not supported by the system. + +**Solution** +Check the system version and update the system if required. + +### 13900032 Directory Not Empty + +**Error Message** +Directory not empty + +**Possible Causes** +The specified directory is not empty. + +**Solution** +1. Check the directory. +2. Ensure that the directory is empty. + +### 13900033 Too Many Symbol Links + +**Error Message** +Too many symbolic links + +**Possible Causes** +There are too many symbolic links. + +**Solution** +Delete unnecessary symbol links. + +### 13900034 Operation Blocked + +**Error Message** +Operation would block + +**Possible Causes** +The operation is blocked. + +**Solution** +Perform the operation again. + +### 13900035 Invalid File Descriptor + +**Error Message** +Invalid request desecriptor + +**Possible Causes** +The requested file descriptor is invalid. + +**Solution** +Check that the file descriptor is valid. + +### 13900036 Target Is Not a Character Stream Device + +**Error Message** +Device not a stream + +**Possible Causes** +The device pointed to by the file descriptor is not a character stream device. + +**Solution** +Check whether the file descriptor points to a stream device. + +### 13900037 No Data Available + +**Error Message** +No data available + +**Possible Causes** +The required data is not available. + +**Solution** +Request the data again. + +### 13900038 Value Mismatches the Data Type + +**Error Message** +Value too large for defined data type + +**Possible Causes** +The specified value is out of the range defined for the data type. + +**Solution** +Modify the data type. + +### 13900039 File Descriptor Corrupted + +**Error Message** +File descriptor in bad state + +**Possible Causes** +The file descriptor is corrupted. + +**Solution** +Check that the file descriptor is valid. + +### 13900040 System Call Interrupted + +**Error Message** +Interrupted systen call should be restarted + +**Possible Causes** +The system call is interrupted. + +**Solution** +Invoke the system call again. + +### 13900041 Disk Quota Exceeded + +**Error Message** +Quota exceeded + +**Possible Causes** +The disk space is insufficient. + +**Solution** +Clear disk space. + +### 13900042 Unknown Error + +**Error Message** +Unknown error + +**Possible Causes** +The error is unidentified. + +**Solution** +1. Call the API again. +2. Restart the service. + +## User Data Management Error Codes + +### 14000001 Invalid File Name + +**Error Message** +Invalid display name + +**Possible Causes** +The file name contains invalid characters. + +**Solution** +Modify the file name. + +### 14000002 Invalid URI + +**Error Message** +Invalid uri + +**Possible Causes** +The URI is invalid. + +**Solution** +Use the obtained URI. + +### 14000003 Invalid File Name Extension + +**Error Message** +Invalid file extension + +**Possible Causes** +The file name extension is incorrect. + +**Solution** +Modify the file name extension. + +### 14000004 File in Recycle Bin + +**Error Message** +File has been put into trash bin + +**Possible Causes** +The file is moved to the Recycle Bin. + +**Solution** +Check whether the file is in the Recycle Bin. + +## Spatial Statistics Error Codes + +### 13600001 IPC Failed + +**Error Message** +IPC error + +**Possible Causes** +The called service does not exist. + +**Solution** +Check whether the service is started. + +### 13600002 File System Not Supported + +**Error Message** +Not supported filesystem + +**Possible Causes** +The file system is not supported. + +**Solution** +Use a supported file system. + +### 13600003 Mount Failed + +**Error Message** +Failed to mount + +**Possible Causes** +The **mount** command fails. + +**Solution** +Remove the card and run the **mount** command again. + +### 13600004 Unmount Failed + +**Error Message** +Failed to unmount + +**Possible Causes** +The device does not respond. + +**Solution** +Check whether the file is being used. If yes, kill the thread that uses the file. + +### 13600005 Incorrect Volume State + +**Error Message** +Incorrect volume state + +**Possible Causes** +The volume state is incorrect. + +**Solution** +Check whether the current volume state is correct. + +### 13600006 Failed to Create a Directory or Node + +**Error Message** +Prepare directory or node error + +**Possible Causes** +The directory or node to be created already exists. + +**Solution** +Check whether the directory or node to be created already exists. + +### 13600007 Failed to Delete a Directory or Node + +**Error Message** +Delete directory or node error + +**Possible Causes** +The specified directory or node has been deleted. + +**Solution** +Check whether the specified directory or node exists. + +### 13600008 Object Not Exist + +**Error Message** +No such object + +**Possible Causes** +1. The specified volume ID is incorrect. +2. The specified bundle name is incorrect. + +**Solution** +1. Check whether the specified volume exists. +2. Check whether the specified bundle name exists. + +### 13600009 Invalid User ID + +**Error Message** +User id out of range + +**Possible Causes** +The specified user ID is incorrect. + +**Solution** +Check that the user ID is correct. + +## User File Access Error Codes + +### 14300001 IPC Failed + +**Error Message** +IPC error + +**Possible Causes** +1. The server service does not exist. +2. The extension mechanism is abnormal. + +**Solution** +Check that the server service exists. + +### 14300002 Incorrect URI Format + +**Error Message** +Invalid uri + +**Possible Causes** +The URI is invalid. + +**Solution** +Check that the URI is in correct format. + +### 14300003 Failed to Obtain the Server Ability Information + +**Error Message** +Fail to get fileextension info + +**Possible Causes** +The BMS interface is abnormal. + +**Solution** +Check for basic system capability errors. + +### 14300004 Incorrect Result Returned by js-server + +**Error Message** +Get wrong result + +**Possible Causes** +The data returned by the server is incorrect. + +**Solution** +Check the data returned by the server. + +### 14300005 Failed to Register Notify + +**Error Message** +Fail to register notification + +**Possible Causes** +1. The server service does not exist. +2. The extension mechanism is abnormal. + +**Solution** +Check that the server service exists. + +### 14300006 Failed to Unregister Notify + +**Error Message** +Fail to remove notification + +**Possible Causes** +1. The server service does not exist. +2. The extension mechanism is abnormal. + +**Solution** +Check that the server service exists. + +### 14300007 Failed to Initialize the Notify Agent + +**Error Message** +Fail to init notification agent + +**Possible Causes** +The specified Notify agent has not been registered. + +**Solution** +Check whether the specified Notify agent is registered. + +### 14300008 Failed to Notify the Agent + +**Error Message** +Fail to notify agent + +**Possible Causes** +1. The service does not exist. +2. The extension mechanism is abnormal. + +**Solution** +Check whether the client is normal. diff --git a/en/application-dev/reference/errorcodes/errorcode-i18n.md b/en/application-dev/reference/errorcodes/errorcode-i18n.md index 71555203e62a93f1c8cdfcfaf5f46ed04832c681..8a1392286491b7e7173d26a2e62c740de4abdbdf 100644 --- a/en/application-dev/reference/errorcodes/errorcode-i18n.md +++ b/en/application-dev/reference/errorcodes/errorcode-i18n.md @@ -1,4 +1,4 @@ -# I18N Error Codes +# i18n Error Codes ## 890001 Incorrect Parameter Type diff --git a/en/application-dev/reference/errorcodes/errorcode-time.md b/en/application-dev/reference/errorcodes/errorcode-time.md new file mode 100644 index 0000000000000000000000000000000000000000..d63b3914ad6f480fdaa3808cf98ba25e390c7ebc --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-time.md @@ -0,0 +1,25 @@ +# Time and Time Zone Service Error Codes + +## -1 Screen Unlock Error + +**Error Message** + +The parameter check failed or permission denied or system error. + +**Description** + +This error code is reported when a parameter check failure, permission verification failure, or system operation error occurs. + +**Possible Cause** + + +1. The input parameter is invalid. +2. The required permission is not configured. For example, **ohos.permission.SET_TIME** is not configured for setting the time or **ohos.permission.SET_TIME_ZONE** is not configured for setting the time zone. +3. The system is not running properly due to a common kernel error, such as a memory allocation and multi-thread processing error. + +**Solution** + +1. Make sure input parameters are passed in as required. +2. Configure the **ohos.permission.SET_TIME** permission for setting the time and the **ohos.permission.SET_TIME_ZONE** permission for setting the time zone. +3. Make sure the memory is sufficient. + diff --git a/en/application-dev/reference/errorcodes/errorcode-useriam.md b/en/application-dev/reference/errorcodes/errorcode-useriam.md new file mode 100644 index 0000000000000000000000000000000000000000..2e84641a549af91c9101e94da86b54cf0db9d712 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-useriam.md @@ -0,0 +1,163 @@ +# User Authentication Error Codes + +## 201 Permission Verification Failed + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 202 Invoker Is Not a System Application + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 401 Parameter Check Failed. + +For details, see [Universal Error Codes](./errorcode-universal.md). + +## 12500001 Authentication Failed + +**Error Message** + +Authentication failed. + +**Possible Causes** + +The credential does not match the credential enrolled. + +**Solution** + +Initiate authentication again. + +## 12500002 General Operation Error + +**Error Message** + +General operation error. + +**Possible Causes** + +1. An error occurs when the NAPI layer parses parameters. +2. The process of the user authentication service is not started. +3. The proxy client fails to write data over IPC. +4. The stub server fails to parse data over IPC. +5. The driver service is not obtained. + +**Solution** + +Call the API again later or restart the device. + +## 12500003 Authentication Canceled + +**Error Message** + +Authentication canceled. + +**Possible Causes** + +The authentication operation has been canceled. + +**Solution** + +Initiate the authentication again. + +## 12500004 Authentication Timed Out + +**Error Message** + +Authentication timeout. + +**Possible Causes** + +The authentication is not complete within the specified time. + +**Solution** + +Initiate the authentication again. + +## 12500005 Unsupported Authentication Type + +**Error Message** + +The authentication type is not supported. + +**Possible Causes** + +1. The input authentication type parameter is not supported. For example, if the authentication type passed in **getAvailableStatus** of the **userAuth** module is not **FACE** or **FINGERPRINT**, error code 12500005 is returned. +2. The device does not support the authentication type. For example, if fingerprint authentication is initiated on a device that has no fingerprint sensor, error code 12500005 is returned. + +**Solution** + +Check the authentication type parameter and call the API again. + +## 12500006 Unsupported Authentication Trust Level + +**Error Message** + +The authentication trust level is not supported. + +**Possible Causes** + +1. The **authTrustLevel** value in **getAvailableStatus** or **getAuthInstance** of the **userAuth** module is not in the range [ATL1, ATL2, ATL3, ATL4]. +2. The device does not support the authentication trust level. For example, if facial authentication for payment is initiated on a device that has only 2D cameras, error code 12500006 is returned. + +**Solution** + +Check that the **authTrustLevel** passed in is within the value range, and the device supports the specified authentication trust level. + +## 12500007 Authentication Service Unavailable + +**Error Message** + +Authentication service is busy. + +**Possible Causes** + +Another authentication is initiated when the current authentication has not been finished yet. + +**Solution** + +Initiate authentication again later. + +## 12500009 Authentication Locked + +**Error Message** + +Authentication is lockout. + +**Possible Causes** + +The number of authentication failures exceeds the limit. + +**Solution** + +Initiate authentication later. + +## 12500010 Credential Not Enrolled + +**Error Message** + +The type of credential has not been enrolled. + +**Possible Causes** + +The **authType** parameter set in **getAvailableStatus** of the **userAuth** module is **FACE**, but no facial credential is enrolled in the device. +**start()** is called to initiate facial authentication, but no facial credential is enrolled in the device. + +**Solution** + +Check that the related type of credential has been enrolled in the device. + +## 12700001 Failed to Enroll Faces + +**Error Message** + +The operation is failed. + +**Possible Causes** + +1. The facial authentication service is not started when **setSurfaceId()** of the **userAuth** module is called. +2. The proxy client fails to write data over IPC. +3. The stub server fails to parse data over IPC. +4. An error occurs when the facial authentication driver is invoked. + +**Solution** + +Call the API again later or restart the device. diff --git a/en/application-dev/reference/errorcodes/errorcode-utils.md b/en/application-dev/reference/errorcodes/errorcode-utils.md index 9bb6853ced81e314b8ad1622e0d39590145a31d7..0d0f1a22baca55308747aadea65cbe64ca61f4aa 100644 --- a/en/application-dev/reference/errorcodes/errorcode-utils.md +++ b/en/application-dev/reference/errorcodes/errorcode-utils.md @@ -219,3 +219,57 @@ The buffer is read-only. **Solution** Do not set the read-only attribute for the buffer. + +## 10200014 Non-Concurrent Function Error + +**Error Message** + +The function is not mark as concurrent. + +**Description** + +The function is not marked as **concurrent**. + +**Possible Causes** + +**@Concurrent** is not added to the function required by the task to be executed in the task pool. + +**Solution** + +Check the functions required by the tasks executed by the task pool and add the **@Concurrent** decorator. + +## 10200015 Failed to Cancel a Task That Does Not Exist + +**Error Message** + +The task is not exist when cancel it. + +**Description** + +This error code is reported when you attempt to cancel a task that does not exist. + +**Possible Causes** + +The task to cancel does not exist in the task pool. + +**Solution** + +Before canceling a task, ensure that the task is placed into the task pool by calling **taskpool.execute**. + +## 10200016 Failed to Cancel a Task Being Executed + +**Error Message** + +The task is running when cancel it. + +**Description** + +This error code is reported when you attempt to cancel a task that is being executed. + +**Possible Causes** + +The task to cancel is being executed. + +**Solution** + +Before canceling a task, ensure that the task finishes execution. diff --git a/en/application-dev/reference/errorcodes/errorcode-zlib.md b/en/application-dev/reference/errorcodes/errorcode-zlib.md index 1e5fbb46a15294207dd4c1e2c10e8de98bbdc93f..3fb887f1fbac58b02fb356a703240bf07258ca0c 100644 --- a/en/application-dev/reference/errorcodes/errorcode-zlib.md +++ b/en/application-dev/reference/errorcodes/errorcode-zlib.md @@ -8,11 +8,11 @@ The input source file is invalid. **Description** -This error code is reported when the source file passed in the **compress** or **decompress** API is invalid. +This error code is reported when the source file passed in the **compressFile()** or **decompressFile()** API is invalid. **Possible Causes** -When the **compress** API is called, the file to compress does not exist. When the **decompress** API is called, the file to decompress does not exist. +When the **compressFile()** API is called, the file to compress does not exist. When the **decompressFile()** API is called, the file to decompress does not exist. **Solution** @@ -27,12 +27,12 @@ The input destination file is invalid. **Description** -This error code is reported when the destination file passed in the **compress** or **decompress** API is invalid. +This error code is reported when the destination file passed in the **compressFile()** or **decompressFile()** API is invalid. **Possible Causes** -1. When the **compress** API is called, the passed destination file path is invalid, for example, a non-exist sandbox path. -2. When the **decompress** API is called, the destination folder does not exist. +1. When the **compressFile()** API is called, the passed destination file path is invalid, for example, a non-exist sandbox path. +2. When the **decompressFile()** API is called, the destination folder does not exist. **Solution** diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md index 6c8e02e6dfa0779fd378dc04b81f090f258338dd..a05bdaa4c6bb6c20f7a886dfe6b2495e1674c814 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-basic-calendar.md @@ -173,7 +173,7 @@ The following examples are not intended as copy-paste-ready. Further customizati "clickOneDay": { "action": "router", "bundleName": "com.example.calendar", - "abilityName": "com.example.calendar.MainAbility", + "abilityName": "EntryAbility", "params": { "action": "click_month_view_event", "day": "$event.day", diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md index cbf1f5fcb5aee5d2b80ff0ef22e9e38acbde16e9..31b25496a065cba484199dac044282cbd8d50b15 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md @@ -55,5 +55,5 @@ You can set universal styles for components in the **style** attribute or **.css | image-fill | <color> | - | Fill color for SVG images. The following components (and attributes) are supported: **button** (**icon** attribute) and **image** (**src** attribute).
The **fill** color value in the SVG image file is replaced with the value of **image-fill** during rendering, and is valid only for the fill attribute that is declared in the SVG image.| | clip-path | [ <geometry-box> \|<basic-shape> ] \| none | - | Clip area of the component. Only the content within this area is displayed.
**\**: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:
- **margin-box**: The width and height includes the margin.
- **border-box**: The width and height includes the border.
- **padding-box**: The width and height includes the padding.
- **content-box**: The width and height does not include any margin, border, or padding.
**\**: shape of the clip area. Available values include:
- **inset**, in the format of inset( <percentage>{1,4} [ round <'border-radius'> ]? )
- **circle**, in the format of circle( [ <percentage> ]? [ at <percentage> <percentage> ]? )
- **ellipse**, in the format of ellipse( [ <percentage>{2} ]? [ at <percentage> <percentage> ]? )
- **polygon**, in the format of polygon( [ <percentage> <percentage> ]\# )
- **path**, in the format of path( <string> )| | mask-image | - <linear-gradient>
- string | - | Image used for the mask of the component:
Gradient color mask, for example, **linear-gradient(to left, black, white)**.
Solid color mask, for example, **linear-gradient(to right, grey , grey)**.
Mask filled by a local SVG image, for example, **url(common/mask.svg)**| -| mask-size | - string
- <length><length>
- <percentage> <percentage> | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.
The **string** values are as follows:
- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: retains the original aspect ratio of the image.
The two **\** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
The two **** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.| +| mask-size | - string
- <length><length>
- <percentage> <percentage> | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.
The **string** values are as follows:
- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.
- **cover**: extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.
- **auto**: retains the original aspect ratio of the image.
The two **\** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.
The two **\** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default. | | mask-position | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | Display position of the mask image. The setting is valid only when **mask-image** is set to an image source. Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.
The **string** values are as follows:
- **left**: leftmost in the horizontal direction.
- **right**: rightmost in the horizontal direction.
- **top**: top in the vertical direction.
- **bottom**: bottom in the vertical direction.
- **center**: center position.
Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0 0 in px (**0px 0px**). If only one value is specified, the other one is **50%**.
Using **\**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0% 0%. For the lower right corner, the value is **100% 100%**. If only one value is specified, the other one is **50%**.
Using both **\** and **\**.| diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md index 9dbecd2d9174138b5df9d49da3caeecb07e5d76f..1622e3755d7670e70d3792c9cf2ac0c65f22cf08 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md @@ -24,7 +24,7 @@ Custom components are existing components encapsulated based on service requirem | Name| Type| Description| | -------- | -------- | -------- | | data | Object | Data model of the page. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).| -| props | Array/Object | Used for communication between components. This attribute can be transferred to components via ****. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.| +| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions. | ## Adding a Custom Event diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md index f355a8fc938732f1e08b31ef3932d23f363db913..20a8a497c4cd041709840826f689ea52fec4b121 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-file.md @@ -59,6 +59,6 @@ Application resources can be accessed via an absolute or relative path. In this ## Configuration Files -If you are developing a widget in the FA model, configure the **config.json** file. For details, see [FA Widget Development](../../ability/fa-formability.md#configuring-the-widget-configuration-file). +If you are developing a widget in the FA model, configure the **config.json** file. -If you are developing a widget in the stage model, configure **ExtensionAbility** under **extensionAbilities** in the **module.json5** file. For details, see [Stage Widget Development](../../ability/stage-formextension.md#configuring-the-widget-configuration-file). +If you are developing a widget in the stage model, configure **ExtensionAbility** under **extensionAbilities** in the **module.json5** file. diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md index 968ea8493c824313dc3828b99b098ba59031420f..403d80f0efc046048662a17f19ea7de51b5aa402 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md @@ -99,11 +99,11 @@ You can also implement redirection to the target application using a **want**, w | Selector | Type | Default Value | Description | | ------ | ------ | -------- | ---------------------------------------- | | action | string | "router" | Event type.
- **"router"**: redirection event.
- **"message"**: message event.| -| want | [Want](../apis/js-apis-application-Want.md) | - | Information about the target application. For details, see the **want** format. | +| want | [Want](../apis/js-apis-app-ability-want.md) | - | Information about the target application. For details, see the **want** format. | - ```json - { +```json + { "data": { "mainAbility": "xxx.xxx.xxx" }, @@ -112,7 +112,7 @@ You can also implement redirection to the target application using a **want**, w "action": "router", "want": { "bundleName": "com.example.myapplication", - "abilityName": "com.example.entry.MainAbility" + "abilityName": "EntryAbility" } }, "routerEventName2": { @@ -124,9 +124,9 @@ You can also implement redirection to the target application using a **want**, w } } } - ``` +``` - In API version 8, the [featureAbility.getWant](../apis/js-apis-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters. + In API version 8, the [featureAbility.getWant](../apis/js-apis-ability-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters. - Message event properties diff --git a/en/application-dev/reference/syscap.md b/en/application-dev/reference/syscap.md index 295ec50046c660282964f41679bd7a3377ca846b..c800e185a8bd87029a9c83d4ab63065edcc448ce 100644 --- a/en/application-dev/reference/syscap.md +++ b/en/application-dev/reference/syscap.md @@ -4,7 +4,7 @@ ### System Capabilities and APIs -SysCap is short for SystemCapability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association. +SystemCapability (SysCap in short) refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association. ![image-20220326064841782](figures/image-20220326064841782.png) diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index ce9f1dd695f62073424c5b967207ba316cd079b5..05d2d2864de5dc34947f43d1b54ab2480e039747 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -8,7 +8,7 @@ - User Authentication - [User Authentication Overview](userauth-overview.md) - [User Authentication Development](userauth-guidelines.md) -- Key Management +- HUKS - [HUKS Overview](huks-overview.md) - [HUKS Development](huks-guidelines.md) - Crypto Framework @@ -20,3 +20,4 @@ - hapsigner - [hapsigner Overview](hapsigntool-overview.md) - [hapsigner Guide](hapsigntool-guidelines.md) + - [HarmonyAppProvision Configuration File](app-provision-structure.md) \ No newline at end of file diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index c46c8fc8283271764986d20659276cf9f64aa555..1d52a333239bdb0b273b21b6a6dbe6bc6c49140f 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -2,58 +2,46 @@ ## When to Use -In this example, the app requires the **ohos.permission.PERMISSION1** and **ohos.permission.PERMISSION2** permissions to implement core functions. +The [Ability Privilege Level (APL)](accesstoken-overview.md#app-apls) of an application can be **normal**, **system_basic**, or **system_core**. The default APL is **normal**. The [permission types](accesstoken-overview.md#permission-types) include **system_grant** and **user_grant**. For details about the permissions for apps, see the [App Permission List](permission-list.md). -- The ability privilege level (APL) of the app is **normal**. -- The level of **ohos.permission.PERMISSION1** is **normal**, and the authorization mode is **system_grant**. -- The level of **ohos.permission.PERMISSION2** is **system_basic**, and the authorization mode is **user_grant**. +This document describes the following operations: -> **CAUTION** -> -> In this scenario, the required permissions include a **user_grant** permission. You can check whether the caller has the required permission through permission verification. -> -> If the permission verification result indicates that the app has not obtained that permission, dynamic user authorization is required. +- [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file) +- [Declaring Permissions in the ACL](#declaring-permissions-in-the-acl) +- [Requesting User Authorization](#requesting-user-authorization) +- [Pre-Authorizing user_grant Permissions](#pre-authorizing-user_grant-permissions) -## Available APIs +## Declaring Permissions in the Configuration File -The table below lists only the API used in this guide. For more information, see [Ability Access control](../reference/apis/js-apis-ability-context.md). +During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see [Application Models](../application-models/application-model-description.md). The application bundle and configuration file vary with the application model. -| API | Description | -| ------------------------------------------------------------ | --------------------------------------------------- | -| requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; | Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result.| +> **NOTE**
The default APL of an application is **normal**. When an application needs the **system_basic** or **system_core** APL, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-permissions-in-the-acl). -## Declaring Permissions +The following table describes the fields in the configuration file. -Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md). +| Field | Mandatory| Description | +| --------- | -------- | ------------------------------------------------------------ | +| name | Yes | Name of the permission. | +| reason | No | Reason for requesting the permission.
This field is mandatory when the requested permission needs user authorization (user_grant).| +| usedScene | No | Application scenario of the permission.
This field is mandatory when the requested permission needs user authorization (user_grant).| +| abilities | No | Abilities that require the permission. The value is an array.
**Applicable model**: stage| +| ability | No | Abilities that require the permission. The value is an array.
**Applicable model**: FA| +| when | No | Time when the permission is used.
Value:
- **inuse**: The permission applies only to a foreground application.
- **always**: The permission applies to both the foreground and background applications.| -Note that the app bundle structure and configuration file vary with the ability framework model. - -The following table describes the tags in the configuration file. - -| Field | Description | -| --------- | ------------------------------------------------------------ | -| name | Name of the permission. | -| reason | Reason for requesting the permission. This field is mandatory for a user_grant permission.| -| usedScene | Scenario of the permission. This field is mandatory for a user_grant permission.| -| ability | Abilities that use the permission. The value is an array.
**Applicable model**: FA | -| abilities | Abilities that use the permission. The value is an array.
**Applicable model**: stage | -| when | Time when the permission is used. The value can be **inuse** (the permission can be used only in the foreground) or **always** (the permission can be used in foreground and background).| - -### FA Model - -For the apps based on the FA model, declare the required permissions in the **config.json** file. +### Stage Model -**Example** +If the application is based on the stage model, declare the permissions in [**module.json5**](../quick-start/module-configuration-file.md). ```json { "module" : { - "reqPermissions":[ + // ... + "requestPermissions":[ { "name" : "ohos.permission.PERMISSION1", "reason": "$string:reason", "usedScene": { - "ability": [ + "abilities": [ "FormAbility" ], "when":"inuse" @@ -63,7 +51,7 @@ For the apps based on the FA model, declare the required permissions in the **co "name" : "ohos.permission.PERMISSION2", "reason": "$string:reason", "usedScene": { - "ability": [ + "abilities": [ "FormAbility" ], "when":"always" @@ -74,21 +62,20 @@ For the apps based on the FA model, declare the required permissions in the **co } ``` -### Stage Model - -For the apps based on the stage model, declare the required permissions in the **module.json5** file. +### FA Model -**Example** +If the application is based on the FA model, declare the required permissions in **config.json**. ```json { "module" : { - "requestPermissions":[ + // ... + "reqPermissions":[ { "name" : "ohos.permission.PERMISSION1", "reason": "$string:reason", "usedScene": { - "abilities": [ + "ability": [ "FormAbility" ], "when":"inuse" @@ -98,7 +85,7 @@ For the apps based on the stage model, declare the required permissions in the * "name" : "ohos.permission.PERMISSION2", "reason": "$string:reason", "usedScene": { - "abilities": [ + "ability": [ "FormAbility" ], "when":"always" @@ -109,60 +96,151 @@ For the apps based on the stage model, declare the required permissions in the * } ``` -## Declaring the ACL - -The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL. +## Declaring Permissions in the ACL -In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher that the app's APL in the app's profile. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). +If an application of the **normal** level requires permissions corresponding to the **system_basic** or **system_core** level, you need to declare the required permissions in the ACL. -For example, declare the required permission in the **acls** field: +For example, if an application needs to access audio files of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the related permissions to the **acl** field in the [HarmonyAppProvision configuration file](app-provision-structure.md). ```json { - "acls": { - "allowed-acls": [ - "ohos.permission.PERMISSION2" - ] - } + // ... + "acls":{ + "allowed-acls":[ + "ohos.permission.WRITE_AUDIO", + "ohos.permission.CAPTURE_SCREEN" + ] + } } ``` -## Applying for the user_grant Permission - -After the permissions are declared, the system grants the system_grant permission during the installation of the app. The user_grant permission must be authorized by the user. +## Requesting User Authorization -Therefore, before allowing the app to call the API protected by the **ohos.permission.PERMISSION2** permission, the system needs to verify whether the app has the permission to do so. +If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from users. A permission verification is performed first to determine whether the current invoker has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example. + -If the verification result indicates that the app has the permission, the app can access the target API. Otherwise, the app needs to request user authorization and then proceeds based on the authorization result. For details, see [Access Control Overview](accesstoken-overview.md). +> **NOTE**
Each time before an API protected by a permission is accessed, the [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) API will be called to request user authorization. After a permission is dynamically granted, the user may revoke the permission. Therefore, the previously granted authorization status cannot be persistent. -> **CAUTION** -> -> The permission authorized by a user is not permanent, because the user may revoke the authorization at any time. Each time before the API protected by the permission is called, call **requestPermissionsFromUser()** to request the permission. +### Stage Model -## Example +Example: Request the permission to read calendar information for an app. + +1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file). + +2. Call [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) indicates whether the app has the target permission. If yes, the target API can be called normally. + + Request user authorization in UIAbility. + + ```typescript + import UIAbility from '@ohos.app.ability.UIAbility'; + import window from '@ohos.window'; + import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + import { Permissions } from '@ohos.abilityAccessCtrl'; + + export default class EntryAbility extends UIAbility { + // ... + + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created, set main page for this ability + let context = this.context; + let AtManager = abilityAccessCtrl.createAtManager(); + // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization. + const permissions: Array = ['ohos.permission.READ_CALENDAR']; + AtManager.requestPermissionsFromUser(context, permissions).then((data) => { + console.info(`[requestPermissions] data: ${JSON.stringify(data)}`); + let grantStatus: Array = data.authResults; + if (grantStatus[0] === -1) { + // The authorization fails. + } else { + // The authorization is successful. + } + }).catch((err) => { + console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`); + }) + + // ... + } + } + ``` + + Request user authorization on the UI. + ```typescript + import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + import { Permissions } from '@ohos.abilityAccessCtrl'; + import common from '@ohos.app.ability.common'; + + @Entry + @Component + struct Index { + reqPermissions() { + let context = getContext(this) as common.UIAbilityContext; + let AtManager = abilityAccessCtrl.createAtManager(); + // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization. + const permissions: Array = ['ohos.permission.READ_CALENDAR']; + AtManager.requestPermissionsFromUser(context, permissions).then((data) => { + console.info(`[requestPermissions] data: ${JSON.stringify(data)}`); + let grantStatus: Array = data.authResults; + if (grantStatus[0] === -1) { + // The authorization fails. + } else { + // The authorization is successful. + } + }).catch((err) => { + console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`); + }) + } + + // Page display. + build() { + // ... + } + } + ``` -The procedure for requesting user authorization is as follows: +### FA Model -1. Obtain the ability context. -2. Call **requestPermissionsFromUser()** to request user authorization. The API determines whether to display a dialog box to request user authorization based on whether the app has the permission. -3. Check whether the app has the permission based on the return value. If the app has the permission, the API can be invoked. +Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization. ```js - // OnWindowStageCreate of the ability - onWindowStageCreate() { - var context = this.context +// onWindowStageCreate() of Ability +onWindowStageCreate() { + let context = this.context; let array:Array = ["ohos.permission.PERMISSION2"]; - // requestPermissionsFromUser determines whether to display a dialog box based on the permission authorization status. + // The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization. context.requestPermissionsFromUser(array).then(function(data) { - console.log("data type:" + typeof(data)); - console.log("data:" + data); - console.log("data permissions:" + data.permissions); - console.log("data result:" + data.authResults); + console.log("data:" + JSON.stringify(data)); + console.log("data permissions:" + JSON.stringify(data.permissions)); + console.log("data result:" + JSON.stringify(data.authResults)); }, (err) => { - console.error('Failed to start ability', err.code); + console.error('Failed to start ability', err.code); }); - } +} +``` +## Pre-Authorizing user_grant Permissions +By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed apps, you can pre-authroize the permissions, for example, the **ohos.permission.MICROPHONE** permission, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file to prevent the user authorization dialog box from being displayed. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the **user_grant** permissions in the file are granted. The **install_list_permissions.json** file contains the following fields: +- **bundleName**: bundle name of the application. +- `app_signature`: fingerprint information of the application. For details, see **Configuration in install_list_capability.json** in [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). +- **permissions**: **name** specifies the name of the **user_grant** permission to pre-authorize. **userCancellable** specifies whether the user can revoke the pre-authorization. The value **true** means the user can revoke the pre-authorization; the vaue **false** means the opposite. + +> **NOTE**
This file is available only for preinstalled applications. + +```json +[ + // ... + { + "bundleName": "com.example.myapplication", // Bundle Name. + "app_signature": ["****"], // Fingerprint information. + "permissions":[ + { + "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize. + "userCancellable": false // The user cannot revoke the authorization. + }, + { + "name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize. + "userCancellable": true // The user can revoke the authorization. + } + ] + } +] ``` -> **NOTE**
-> For details about the APIs, see [AbilityContext](../reference/apis/js-apis-ability-context.md). diff --git a/en/application-dev/security/accesstoken-overview.md b/en/application-dev/security/accesstoken-overview.md index 9e8aa2a655ecdfbd3ebc4133230f12fb9cf46d67..e42543a356fb71dee1c6eea6e84a2115ca1518be 100644 --- a/en/application-dev/security/accesstoken-overview.md +++ b/en/application-dev/security/accesstoken-overview.md @@ -2,14 +2,14 @@ OpenHarmony AccessTokenManager (ATM) implements unified app permission management based on access tokens. -By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also explicitly share their data or functions through APIs. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. +By default, apps can access limited system resources. However, to provide extended features, an app may need to access excess data (including personal data) and functions of the system or another app. The system or apps must also explicitly share their data or functions through APIs. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. App permissions are used to protect the following objects: - Data: personal data (such as photos, contacts, calendar, and location), device data (such as device ID, camera, and microphone), and app data. - Functions: device functions (such as making calls, sending SMS messages, and connecting to the Internet) and app functions (such as displaying windows and creating shortcuts). -Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions. +Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize app behavior and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions. Currently, ATM verifies app permissions based on the token identity (token ID). A token ID identifies an app. ATM manages app permissions based on the app's token ID. @@ -17,13 +17,13 @@ Currently, ATM verifies app permissions based on the token identity (token ID). Observe the following principles for permission management: -- Provide clear description about the app functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are required. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app. +- Provide clear description about the functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are needed. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app. - Use the principle of least authority for user permissions. Allow only necessary permissions for service functions. - When an app is started for the first time, avoid frequently displaying dialog boxes to request multiple permissions. Allow the app to apply for the permission only when it needs to use the corresponding service function. - If a user rejects to grant a permission, the user can still use functions irrelevant to this permission and can register and access the app. - Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to grant the permission in **Settings** if the user triggers this function again or needs to use this function. -- All the permissions granted to apps must come from the [App Permission List](permission-list.md). Custom permissions are not allowed for apps currently. +- All the permissions granted to apps must come from the [App Permission List](permission-list.md). Custom permissions are not allowed currently. ## Permission Workflows @@ -50,7 +50,9 @@ The figure below illustrates the process. 3. A low-APL app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl). ### Permission Verification -To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. The API can be called only after the permission verification is successful. +To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect an API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. + +The API can be called only after the permission verification is successful. The figure below shows the permission verification process. @@ -58,7 +60,7 @@ The figure below shows the permission verification process. 1: An app permission can be used to control the access to an API that has sensitive data involved or security threats on the core abilities. -2: Select the permission from the [App Permission List](permission-list.md). For example, if contact information is involved in an API provided by an app, you can use the contact-related permissions to protect the API. +2: The API can be protected by a permission in the [ACL](#acl). For example, if contact information is involved in an API provided by an app, you can use the contact-related permissions to protect the API. 3: Use **verifyAccessToken()** to check whether the caller has the required permission. For details, see [Permission Verification Guide](permission-verify-guidelines.md). @@ -88,7 +90,7 @@ Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificat The following is an example. -This example shows only the modification of the **apl** field. Set other fields based on your requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). +This example shows only the modification of the **apl** field. Set other fields based on your requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](app-provision-structure.md). ```json { @@ -123,7 +125,7 @@ The permissions open to apps vary with the permission level. The permission leve The system_core permission allows access to core resources of the OS. These resources are underlying core services of the system. If these resources are corrupted, the OS cannot run properly. - The system_core permissions are not open to third-party apps currently. + The system_core permissions are not open to third-party apps. ## Permission Types @@ -131,19 +133,19 @@ Permissions can be classified into the following types based on the authorizatio - **system_grant** - The app permissions are authorized by the system. This type of apps cannot access user or device sensitive information. The allowed operations have minor impact on the system or other apps. + The app permissions are authorized by the system. Apps granted with this type of permission cannot access user or device sensitive information, and the operations allowed for them have minor impact on the system or other apps. - For a system_grant app, the system automatically grants the required permissions to the app when the app is installed. The system_grant permission list must be presented to users on the details page of the app in the app store. + For a system_grant app, the system automatically grants the required permissions to the app when the app is installed. The system_grant permission list must be presented to users on the details page of the app in the app market. - **user_grant** - The app permissions must be authorized by users. This type of apps may access user or device sensitive information. The allowed operations may have a critical impact on the system or other apps. + The app permissions must be authorized by users. Apps granted with this type of permissions may access user or device sensitive information, and the operations allowed for them may have a critical impact on the system or other apps. This type of permissions must be declared in the app installation package and authorized by users dynamically during the running of the app. The app has the permission only after user authorization. - For example, in the [App Permission List](permission-list.md), the permissions for microphones and cameras are user_grant. The list provides reasons for using the permissions. + For example, as described in the [App Permission List](permission-list.md), the permissions for microphones and cameras are user_grant. The list provides reasons for using the permissions. - The user_grant permission list must also be presented on the details page of the app in the app store. + The user_grant permission list must also be presented on the details page of the app in the app market. ### Authorization Processes @@ -173,7 +175,7 @@ The procedure is as follows: **Precautions** - Check the app's permission each time before the operation requiring the permission is performed. -- To check whether a user has granted specific permissions to an app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). +- To check whether a user has granted specific permissions to an app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) API. This API returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). - Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call an API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the permission. The user will determine whether to grant the permission based on the running context of the app. - The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission. @@ -190,15 +192,15 @@ The APL of app A is **normal**. App A needs to have permission B (system_basic l In this case, you can use the ACL to grant permission B to app A. For details, see [Using the ACL](#using-the-acl). -For details about whether a permission can be enabled through the ACL, see the [App Permission List](permission-list.md). +For details about whether a permission can be enabled through the ACL, see [App Permission List](permission-list.md). ### Using the ACL -If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permission required. +If the permission required by an app has a higher level than the app's APL, you can use the ACL to grant the permission required. In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL. -That is, you need to declare the required permissions in the app's configuration file, and [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same. +That is, you need to declare the required permissions in the app's configuration file, and [declare the ACL](accesstoken-guidelines.md#declaring-permissions-in-the-acl) in the app's profile. The subsequent steps of authorization are the same. **NOTICE** @@ -216,4 +218,4 @@ When developing an app installation package, you must declare the ACL in the **a } ``` -For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). +For details about the fields in the profile, see [HarmonyAppProvision Configuration File](app-provision-structure.md). diff --git a/en/application-dev/quick-start/app-provision-structure.md b/en/application-dev/security/app-provision-structure.md similarity index 58% rename from en/application-dev/quick-start/app-provision-structure.md rename to en/application-dev/security/app-provision-structure.md index df74f5fc03327cfa876d0bc329b16ec1f26dc8cb..a772f024a4179af75e30dcf4f6bc0483ed0f86b0 100644 --- a/en/application-dev/quick-start/app-provision-structure.md +++ b/en/application-dev/security/app-provision-structure.md @@ -4,19 +4,19 @@ The **HarmonyAppProvision** configuration file (also called profile) is the file ## Configuration File Internal Structure The **HarmonyAppProvision** file consists of several parts, which are described in the table below. -**Table 1** Internal structure of the HarmonyAppProvision file -| Name | Description | Data Type| Mandatory| Initial Value Allowed| +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- | -| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes| No | -| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes| No| -| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes| No| -| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes| No| -| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes| No| +| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No | +| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No| +| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No| +| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes | No| +| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No| | validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No | -| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes| No | -| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No| No | -| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No| No | -| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No| No | +| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No | +| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | Yes | +| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | Yes | +| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | Yes | +| app-privilege-capabilities | Privilege information required by the application bundle. For details, see the [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). | String array| No | Yes | An example of the **HarmonyAppProvision** file is as follows: ```json @@ -47,6 +47,7 @@ An example of the **HarmonyAppProvision** file is as follows: "device-id-type": "udid", "device-ids": ["string"] }, + "app-privilege-capabilities":["AllowAppUsePrivilegeExtension"], "issuer": "OpenHarmony" } @@ -54,46 +55,57 @@ An example of the **HarmonyAppProvision** file is as follows: ### Internal Structure of the validity Object -| Name | Description | Data Type| Mandatory| Initial Value Allowed| + +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ---------- | ------------------------------- | ------- | ------- | --------- | -| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | -| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No | +| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | +| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | ### Internal Structure of the bundle-info Object -| Name | Description | Data Type| Mandatory| Initial Value Allowed| + +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | -------- | --------- | -| developer-id | Unique ID of the developer.| String | Yes| No | -| development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | -| distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | -| bundle-name | Bundle name of the application.| String | Yes| No | -| apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes| No | -| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes| No | +| developer-id | Unique ID of the developer.| String | Yes | No | +| development-certificate | Information about the [debug certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | +| distribution-certificate | Information about the [release certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No | +| bundle-name | Bundle name of the application.| String | Yes | No | +| apl | [Ability privilege level (APL)](accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No | +| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (normal application). Only system applications are allowed to call system APIs. If a normal application calls a system API, the call cannot be successful or the application may run abnormally.| String | Yes | No | ### Internal Structure of the acls Object -The **acls** object contains the [ACLs](../security/accesstoken-overview.md) configured for your application. It should be noted that you still need to fill the ACL information in the **reqPermissions** attribute in the [config.json](package-structure.md) file. - -**Table 4** Internal structure of the acls object +The **acls** object contains the [ACL](accesstoken-overview.md) configured for your application. It should be noted that you still need to add the ACL information to the [**requestPermissions**](../quick-start/module-configuration-file.md#requestpermissions) attribute in the application configuration file. -| Name | Description | Data Type| Mandatory| Initial Value Allowed| +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No| No | +| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No | ### Internal Structure of the permissions Object -The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to fill the permission information in the **reqPermissions** attribute in the [config.json](package-structure.md) file. +The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to add the ACL information to the [**requestPermissions**](../quick-start/module-configuration-file.md#requestpermissions) attribute in the application configuration file. -**Table 5** Internal structure of the permissions object - -| Name | Description | Data Type| Mandatory| Initial Value Allowed| +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No| No | +| restricted-permissions | [Restricted permissions](accesstoken-overview.md) required for your application.| String array | No | No | ### Internal Structure of the debug-info Object The **debug-info** object contains debugging information of your application, mainly device management and control information. -**Table 6** Internal structure of the debug-info object - -| Name | Description | Data Type| Mandatory| Initial Value Allowed| +| Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No| No | -| device-ids | IDs of devices on which your application can be debugged.| String array | No| No | +| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No | +| device-ids | IDs of devices on which your application can be debugged.| String array | No | No | + +## Modifying the HarmonyAppProvision Configuration File + +When a development project is created, the default application type is **hos_normal_app** and the default APL level is **normal**. + +To enable the application to use system APIs, you need to change the **app-feature** field to **hos_system_app** (system application). To apply for high-level permissions, you need to modify fields such as **apl** and **acl**. For details, see [Access Control Overview](accesstoken-overview.md). + + +To modify the HarmonyAppProvision configuration file, perform the following steps: + +1. Open the directory where the OpenHarmony SDK is located. (You can choose **File** > **Settings** > **OpenHarmony SDK** on the menu bar of DevEco Studio to query the directory.) +2. In the SDK directory, go to the **Toolchains** > {Version} > **lib** directory and open the **UnsgnedReleasedProfileTemplate.json** file. +3. Modify the related fields as required. + +After modifying the configuration file, [sign the application](hapsigntool-guidelines.md). diff --git a/en/application-dev/security/cert-guidelines.md b/en/application-dev/security/cert-guidelines.md index 9ba67b26752c374e35296dda9e428267f1195595..ed0e3e39a791b5c60055e9e200d764940ecfc12d 100644 --- a/en/application-dev/security/cert-guidelines.md +++ b/en/application-dev/security/cert-guidelines.md @@ -19,21 +19,20 @@ Typical operations involve the following: **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------- | -| cryptoCert | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback) : void | Parses certificate data to create an **X509Cert** instance. This API uses an asynchronous callback to return the result.| -| cryptoCert | createX509Cert(inStream : EncodingBlob) : Promise | Parses certificate data to create an **X509Cert** instance. This API uses a promise to return the result. | -| X509Cert | verify(key : cryptoFramework.PubKey, callback : AsyncCallback) : void | Verifies the certificate signature. This API uses an asynchronous callback to return the result. | -| X509Cert | verify(key : cryptoFramework.PubKey) : Promise | Verifies the certificate signature. This API uses a promise to return the result. | -| X509Cert | getEncoded(callback : AsyncCallback) : void | Obtains serialized certificate data. This API uses an asynchronous callback to return the result. | -| X509Cert | getEncoded() : Promise | Obtains serialized certificate data. This API uses a promise to return the result. | -| X509Cert | getPublicKey(callback : AsyncCallback) : void | Obtains the certificate public key. This API uses an asynchronous callback to return the result. | -| X509Cert | getPublicKey() : Promise | Obtains the certificate public key. This API uses a promise to return the result. | -| X509Cert | checkValidityWithDate(date: string, callback : AsyncCallback) : void | Verifies the certificate validity period. This API uses an asynchronous callback to return the result. | -| X509Cert | checkValidityWithDate(date: string) : Promise | Verifies the certificate validity period. This API uses a promise to return the result. | +| cryptoCert | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void | Parses certificate data to create an **X509Cert** instance. This API uses an asynchronous callback to return the result.| +| cryptoCert | createX509Cert(inStream : EncodingBlob) : Promise\ | Parses certificate data to create an **X509Cert** instance. This API uses a promise to return the result. | +| X509Cert | verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void | Verifies the certificate signature. This API uses an asynchronous callback to return the result. | +| X509Cert | verify(key : cryptoFramework.PubKey) : Promise\ | Verifies the certificate signature. This API uses a promise to return the result. | +| X509Cert | getEncoded(callback : AsyncCallback\) : void | Obtains serialized certificate data. This API uses an asynchronous callback to return the result. | +| X509Cert | getEncoded() : Promise\ | Obtains serialized certificate data. This API uses a promise to return the result. | +| X509Cert | getPublicKey() : cryptoFramework.PubKey | Obtains the certificate public key. | +| X509Cert | checkValidityWithDate(date: string) : void | Checks the certificate validity period. | | X509Cert | getVersion() : number | Obtains the certificate version. | | X509Cert | getSerialNumber() : number | Obtains the certificate serial number. | | X509Cert | getIssuerName() : DataBlob | Obtains the certificate issuer. | @@ -72,7 +71,7 @@ let certData = "-----BEGIN CERTIFICATE-----\n" + "I1Lwu6in1ruflZhzseWulXwcITf3bm/Y5X1g1XFWQUH\n" + "-----END CERTIFICATE-----\n"; -// Convert the string into a Uint8Array. +// Convert the certificate data form a string to a Uint8Array.. function stringToUint8Array(str) { var arr = []; for (var i = 0, j = str.length; i < j; i++) { @@ -94,11 +93,11 @@ function certSample() { cryptoCert.createX509Cert(encodingBlob, function (err, x509Cert) { if (err != null) { // Failed to create the X509Cert instance. - Console.log("createX509Cert failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("createX509Cert failed, errCode: " + err.code + ", errMsg: " + err.message); return; } // The X509Cert instance is successfully created. - Console.log("createX509Cert success"); + console.log("createX509Cert success"); // Obtain the certificate version. let version = x509Cert.getVersion(); @@ -107,51 +106,41 @@ function certSample() { x509Cert.getEncoded(function (err, data) { if (err != null) { // Failed to obtain the serialized data of the certificate. - Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); } else { // The serialized data of the certificate is successfully obtained. - Console.log("getEncoded success"); + console.log("getEncoded success"); } }); - - // Obtain the certificate public key. - x509Cert.getPublicKey(function (err, pubKey) { - if (err != null) { - // Failed to obtain the certificate public key. - Console.log("getPublicKey failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The certificate public key is successfully obtained. - Console.log("getPublicKey success"); - } - }); - + // Obtain the public key object using the getPublicKey() of the upper-level certificate object or this (self-signed) certificate object. let pubKey = null; - + try { + pubKey = x509Cert.getPublicKey(); + } catch (error) { + console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message); + } + // Verify the certificate signature. x509Cert.verify(pubKey, function (err, data) { if (err == null) { // The signature verification is successful. - Console.log("verify success"); + console.log("verify success"); } else { // The signature verification failed. - Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); } }); - + // Time represented in a string. let date = "150527000001Z"; // Verify the certificate validity period. - x509Cert.checkValidityWithDate(date, function (err, data) { - if (err != null) { - // Failed to verify the certificate validity period. - Console.log("checkValidityWithDate failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The certificate validity period is verified successfully. - Console.log("checkValidityWithDate success"); - } - }); + try { + x509Cert.checkValidityWithDate(date); + } catch (error) { + console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } }); } ``` @@ -171,36 +160,33 @@ Typical operations involve the following: **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. | Instance | API | Description | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| cryptoCert | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback) : void | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses an asynchronous callback to return the result.| -| cryptoCert | createX509Crl(inStream : EncodingBlob) : Promise | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses a promise to return the result. | -| X509Crl | isRevoked(cert : X509Cert, callback : AsyncCallback) : void | Checks whether the certificate is revoked. This API uses an asynchronous callback to return the result. | -| X509Crl | isRevoked(cert : X509Cert) : Promise | Checks whether the certificate is revoked. This API uses a promise to return the result. | -| X509Crl | getType() : string | Obtains the CRL type. | -| X509Crl | getEncoded(callback : AsyncCallback) : void | Obtains the serialized CRL data. This API uses an asynchronous callback to return the result. | -| X509Crl | getEncoded() : Promise | Obtains the serialized CRL data. This API uses a promise to return the result. | -| X509Crl | verify(key : cryptoFramework.PubKey, callback : AsyncCallback) : void | Verifies the CRL signature. This API uses an asynchronous callback to return the result. | -| X509Crl | verify(key : cryptoFramework.PubKey) : Promise | Verifies the CRL signature. This API uses a promise to return the result. | -| X509Crl | getVersion() : number | Obtains the CRL version. | +| cryptoCert | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses an asynchronous callback to return the result.| +| cryptoCert | createX509Crl(inStream : EncodingBlob) : Promise\ | Parses the X.509 CRL data to create an **X509Crl** instance. This API uses a promise to return the result. | +| X509Crl | isRevoked(cert : X509Cert) : boolean | Checks whether the certificate is revoked. | +| X509Crl | getType() : string | Obtains the CRL type. | +| X509Crl | getEncoded(callback : AsyncCallback\) : void | Obtains the serialized CRL data. This API uses an asynchronous callback to return the result. | +| X509Crl | getEncoded() : Promise\ | Obtains the serialized CRL data. This API uses a promise to return the result. | +| X509Crl | verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void | Verifies the CRL signature. This API uses an asynchronous callback to return the result. | +| X509Crl | verify(key : cryptoFramework.PubKey) : Promise\ | Verifies the CRL signature. This API uses a promise to return the result. | +| X509Crl | getVersion() : number | Obtains the CRL version. | | X509Crl | getIssuerName() : DataBlob | Obtains the CRL issuer. | | X509Crl | getLastUpdate() : string | Obtains the date when the CRL was last updated. | | X509Crl | getNextUpdate() : string | Obtains the next update date of the CRL. | -| X509Crl | getRevokedCert(serialNumber : number, callback : AsyncCallback) : void | Obtains the revoked certificate in the CRL based on the specified serial number. This API uses an asynchronous callback to return the result. | -| X509Crl | getRevokedCert(serialNumber : number) : Promise | Obtains the revoked certificate in the CRL based on the specified serial number. This API uses a promise to return the result. | -| X509Crl | getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback) : void | Obtains the specified X.509 certificate from the CRL. This API uses an asynchronous callback to return the result. | -| X509Crl | getRevokedCertWithCert(cert : X509Cert) : Promise | Obtains the specified X.509 certificate from the CRL. This API uses a promise to return the result. | -| X509Crl | getRevokedCerts(callback : AsyncCallback>) : void | Obtains all revoked certificates in the CRL. This API uses an asynchronous callback to return the result. | -| X509Crl | getRevokedCerts() : Promise> | Obtains all revoked certificates in the CRL. This API uses a promise to return the result. | -| X509Crl | getTbsInfo(callback : AsyncCallback) : void | Obtains the tbsCertList of the CRL. This API uses an asynchronous callback to return the result. | -| X509Crl | getTbsInfo() : Promise | Obtains the tbsCertList of the CRL. This API uses a promise to return the result. | +| X509Crl | getRevokedCert(serialNumber : number) : X509CrlEntry | Obtains the revoked certificate in the CRL based on the serial number. | +| X509Crl | getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry | Obtains the revoked certificate in the CRL based on the X.509 certificate. | +| X509Crl | getRevokedCerts(callback : AsyncCallback\>) : void | Obtains all revoked certificates in the CRL. This API uses an asynchronous callback to return the result. | +| X509Crl | getRevokedCerts() : Promise\> | Obtains all revoked certificates in the CRL. This API uses a promise to return the result. | +| X509Crl | getTbsInfo() : DataBlob | Obtains **tbsCertList** of the CRL. | | X509Crl | getSignature() : DataBlob | Obtains the CRL signature. | -| X509Crl | getSignatureAlgName() : string | Obtains the CRL signing algorithm. | -| X509Crl | getSignatureAlgOid() : string | Obtains the signing algorithm OID of the CRL. | -| X509Crl | getSignatureAlgParams() : DataBlob | Obtains the signing algorithm parameters of the CRL. | +| X509Crl | getSignatureAlgName() : string | Obtains the CRL signing algorithm. | +| X509Crl | getSignatureAlgOid() : string | Obtains the signing algorithm OID of the CRL. | +| X509Crl | getSignatureAlgParams() : DataBlob | Obtains the signing algorithm parameters of the CRL. | **How to Develop** @@ -223,7 +209,7 @@ let crlData = "-----BEGIN X509 CRL-----\n" + "DrAA7hErVgXhtURLbAI=\n" + "-----END X509 CRL-----\n"; -// Convert the string into a Uint8Array. +// Convert the certificate data form a string to a Uint8Array.. function stringToUint8Array(str) { var arr = []; for (var i = 0, j = str.length; i < j; i++) { @@ -245,11 +231,11 @@ function crlSample() { cryptoCert.createX509Crl(encodingBlob, function (err, x509Crl) { if (err != null) { // Failed to create the X509Crl instance. - Console.log("createX509Crl failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("createX509Crl failed, errCode: " + err.code + ", errMsg: " + err.message); return; } // The X509Crl instance is successfully created. - Console.log("createX509Crl success"); + console.log("createX509Crl success"); // Obtain the CRL version. let version = x509Crl.getVersion(); @@ -257,55 +243,46 @@ function crlSample() { // Obtain the serialized data of the CRL. x509Crl.getEncoded(function (err, data) { if (err != null) { - // Failed to obtain the serialized CRL data. - Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + // Failed to obtain the serialized data of the certificate. + console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); } else { - // The serialized CRL data is successfully obtained. - Console.log("getEncoded success"); + // The serialized data of the certificate is successfully obtained. + console.log("getEncoded success"); } }); - + // Create an X509Cert instance by using createX509Cert() of cryptoFramework. let x509Cert = null; - // Check whether the certificate is revoked. - x509Crl.isRevoked(x509Cert, function (err, isRevoked) { - if (err != null) { - // The operation fails. - Console.log("isRevoked failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The operation is successful. - Console.log("isRevoked success, isRevoked? " + isRevoked); - } - }); - + try { + let revokedFlag = x509Crl.isRevoked(x509Cert); + } catch (error) { + console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message); + } + // Obtain the PubKey instance by using generateKeyPair() or convertKey() of AsyKeyGenerator. The process is omitted here. let pubKey = null; // Verify the CRL signature. x509Crl.verify(pubKey, function (err, data) { if (err == null) { - // The operation is successful. - Console.log("verify success"); + // The signature verification is successful. + console.log("verify success"); } else { - // The operation fails. - Console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); + // The signature verification failed. + console.log("verify failed, errCode: " + err.code + ", errMsg: " + err.message); } }); - + // Certificate serial number, which must be set based on the service. let serialNumber = 1000; - + // Obtain the revoked certificate based on the serial number. - x509Crl.getRevokedCert(serialNumber, function (err, entry) { - if (err != null) { - // The operation fails. - Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The operation is successful. - Console.log("getRevokedCert success"); - } - }); + try { + let entry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } }); } ``` @@ -318,14 +295,15 @@ You need to use the certificate chain validator in certificate chain verificatio **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. | Instance | API | Description | | ------------------ | ------------------------------------------------------------ | -------------------------------- | | cryptoCert | createCertChainValidator(algorithm :string) : CertChainValidator | Creates a **CertChainValidator** instance.| -| CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback) : void | Verifies the certificate chain. This API uses an asynchronous callback to return the result. | -| CertChainValidator | validate(certChain : CertChainData) : Promise | Verifies the certificate chain. This API uses a promise to return the result. | +| CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback\) : void | Verifies the certificate chain. This API uses an asynchronous callback to return the result. | +| CertChainValidator | validate(certChain : CertChainData) : Promise\ | Verifies the certificate chain. This API uses a promise to return the result. | | CertChainValidator | algorithm : string | Obtains the certificate chain validator algorithm. | **How to Develop** @@ -349,7 +327,7 @@ let secondCaCertData = "-----BEGIN CERTIFICATE-----\n" + "...\n" + "-----END CERTIFICATE-----\n"; -// Convert the certificate data form a string to a Uint8Array. +// Convert the certificate data form a string to a Uint8Array.. function stringToUint8Array(str) { var arr = []; for (var i = 0, j = str.length; i < j; i++) { @@ -408,10 +386,10 @@ function certChainValidatorSample() { validator.validate(certChainData, function (err, data) { if (err != null) { // The operation fails. - Console.log("validate failed, errCode: " + err.code + ", errMsg: " + err.message); + console.log("validate failed, errCode: " + err.code + ", errMsg: " + err.message); } else { // The operation is successful. - Console.log("validate success"); + console.log("validate success"); } }); } @@ -429,18 +407,17 @@ Typical operations involve the following: **Available APIs** +For details about the APIs, see [Certificate](../reference/apis/js-apis-cert.md). The table below describes the APIs used in this guide. -| Instance | API | Description | -| ------------ | ----------------------------------------------------------- | ------------------------------------------ | -| X509CrlEntry | getEncoded(callback : AsyncCallback) : void; | Obtains the serialized data of the revoked certificate. This API uses an asynchronous callback to return the result.| -| X509CrlEntry | getEncoded() : Promise; | Obtains the serialized data of the revoked certificate. This API uses a promise to return the result. | -| X509CrlEntry | getSerialNumber() : number; | Obtains the serial number of the revoked certificate. | -| X509CrlEntry | getCertIssuer(callback : AsyncCallback) : void; | Obtains the issuer of the revoked certificate. This API uses an asynchronous callback to return the result. | -| X509CrlEntry | getCertIssuer() : Promise; | Obtains the issuer of the revoked certificate. This API uses a promise to return the result. | -| X509CrlEntry | getRevocationDate(callback : AsyncCallback) : void; | Obtains the revocation date of the certificate. This API uses an asynchronous callback to return the result. | -| X509CrlEntry | getRevocationDate() : Promise; | Obtains the issuer of the revoked certificate. This API uses a promise to return the result. | +| Instance | API | Description | +| ------------ | ----------------------------------------------------------- | ---------------------------------------- | +| X509CrlEntry | getEncoded(callback : AsyncCallback\) : void; | Obtains the serialized data of the revoked certificate. This API uses an asynchronous callback to return the result.| +| X509CrlEntry | getEncoded() : Promise\; | Obtains the serialized data of the revoked certificate. This API uses a promise to return the result. | +| X509CrlEntry | getSerialNumber() : number; | Obtains the serial number of the revoked certificate. | +| X509CrlEntry | getCertIssuer() : DataBlob; | Obtains the issuer of the revoked certificate. | +| X509CrlEntry | getRevocationDate() : string; | Obtains the revocation date of the revoked certificate. | **How to Develop** @@ -456,39 +433,32 @@ function crlEntrySample() { // Obtain a revoked certificate instance. In this example, the instance is obtained by using getRevokedCert(). let serialNumber = 1000; - x509Crl.getRevokedCert(serialNumber, function (err, crlEntry) { + let crlEntry = null; + try { + crlEntry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + + // Obtain the serial number of the revoked certificate. + let serialNumber = crlEntry.getSerialNumber(); + + // Obtain the revocation date of the revoked certificate. + try { + crlEntry.getRevocationDate(); + } catch (error) { + console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } + + // Obtain the serialized data of the revoked certificate instance. + crlEntry.getEncoded(function (err, data) { if (err != null) { - // Failed to obtain the revoked certificate instance. - Console.log("getRevokedCert failed, errCode: " + err.code + ", errMsg: " + err.message); - return; + // Failed to obtain the serialized data of the certificate. + console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); + } else { + // The serialized data of the certificate is successfully obtained. + console.log("getEncoded success"); } - // The revoked certificate instance is successfully obtained. - Console.log("getRevokedCert success"); - - // Obtain the serial number of the revoked certificate. - let serialNumber = crlEntry.getSerialNumber(); - - // Obtain the revocation date of the revoked certificate. - crlEntry.getRevocationDate(function (err, date) { - if (err != null) { - // Failed to obtain the revocation date. - Console.log("getRevocationDate failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The revocation date is successfully obtained. - Console.log("getRevocationDate success, date is: " + date); - } - }); - - // Obtain the serialized data of the revoked certificate instance. - crlEntry.getEncoded(function (err, data) { - if (err != null) { - // Failed to obtain the serialized data. - Console.log("getEncoded failed, errCode: " + err.code + ", errMsg: " + err.message); - } else { - // The serialized data is successfully obtained. - Console.log("getEncoded success"); - } - }); }); } ``` diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md index 35784280547f6f5064fc13f15d651801ea0d0b02..0ed590fbf850cfbbcac7e0c64ddcb0872d9d9353 100644 --- a/en/application-dev/security/cryptoFramework-guidelines.md +++ b/en/application-dev/security/cryptoFramework-guidelines.md @@ -32,10 +32,10 @@ The table below describes the APIs used in this guide. |AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.| |SymKeyGenerator|generateSymKey(callback : AsyncCallback\) : void|Generates a symmetric key randomly. This API uses an asynchronous callback to return the result.| |SymKeyGenerator|generateSymKey() : Promise\|Generates a symmetric key randomly. This API uses a promise to return the result.| -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) | -| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary public key and private key data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) | -| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts binary data into a symmetric key. This API uses an asynchronous callback to return the result.| -| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.| +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts the binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) | +| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) | +| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts the binary data into a symmetric key. This API uses an asynchronous callback to return the result. | +| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts the binary data into a symmetric key. This API uses a promise to return the result. | | Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)| **How to Develop** @@ -121,11 +121,11 @@ function convertAsyKey() { } ``` -**NOTE** - -The public key returned by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key must be in the DER format complying with PKCS #8 specifications. +> **NOTE** +> +> The public key returned by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key must be in the DER format complying with PKCS #8 specifications. -Example 4: Generate an asymmetric key pair from the binary ECC key data. + Example 4: Generate an asymmetric key pair from the binary ECC key data. 1. Obtain the ECC binary key data and encapsulate it into a **DataBlob** instance. 2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) passed in to a **KeyPair** instance. @@ -264,14 +264,14 @@ function stringToUint8Array(str) { return new Uint8Array(arr); } -// Convert byte streams into strings in plaintext. +// Output the byte streams in hexadecimal format. function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -// Output the byte streams in hexadecimal format. +// Convert byte streams into strings in plaintext. function uint8ArrayToString(array) { let arrayString = ''; for (let i = 0; i < array.length; i++) { @@ -383,14 +383,14 @@ function stringToUint8Array(str) { return new Uint8Array(arr); } -// Convert byte streams into strings in plaintext. +// Output the byte streams in hexadecimal format. function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -// Output the byte streams in hexadecimal format. +// Convert byte streams into strings in plaintext. function uint8ArrayToString(array) { let arrayString = ''; for (let i = 0; i < array.length; i++) { @@ -492,17 +492,9 @@ function test3DesEcb() { Example 2: Encrypt and decrypt data using an asymmetric key pair. -1. Generate an RSA key pair. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. - -2. Create a **Cipher** instance. - - Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. - -3. Perform encryption and decryption operations. - - Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. +3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -548,19 +540,19 @@ function encryptMessageCallback() { } ``` -**NOTE** - -- In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each of encryption and decryption. -- The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Crypto Framework Overview](cryptoFramework-overview.md). -- In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. +> **NOTE** +> +> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each of encryption and decryption. +> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Crypto Framework Overview](cryptoFramework-overview.md). +> - In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. ## Signing Data and Verifying Signatures **When to Use** A digital signature can be used to verify the authenticity of a message. Typical signing and signature verification operations involve the following: -1. Use RSA to sign data and verify the signature. -2. Use ECC to sign data and verify the signature. +- Use RSA to sign data and verify the signature. +- Use ECC to sign data and verify the signature. **Available APIs** @@ -573,38 +565,24 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry |Sign|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Sign** instance. This API uses a promise to return the result.| |Sign|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signing. This API uses an asynchronous callback to return the result.| |Sign|update(data : DataBlob) : Promise\|Updates the data for signing. This API uses a promise to return the result.| -|Sign|sign(data : DataBlob, callback : AsyncCallback) : void|Signs the data. This API uses an asynchronous callback to return the result.| -|Sign|sign(data : DataBlob) : Promise|Signs the data. This API uses a promise to return the result.| +|Sign|sign(data : DataBlob, callback : AsyncCallback\) : void|Signs the data. This API uses an asynchronous callback to return the result.| +|Sign|sign(data : DataBlob) : Promise\|Signs the data. This API uses a promise to return the result.| |cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.| |Verify|init(priKey : PriKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| |Verify|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| |Verify|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.| |Verify|update(data : DataBlob) : Promise\|Updates the data for signature verification. This API uses a promise to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise|Verifies the signature. This API uses a promise to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies the signature. This API uses a promise to return the result.| **How to Develop** Example 1: Use RSA to sign data and verify the signature. -1. Generate an RSA key pair. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. - -2. Create a **Sign** instance. - - Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. - -3. Generate a signature. - - Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. - -4. Create a **Verify** instance. - - Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. - -5. Verify the signature. - - Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -684,25 +662,11 @@ function verifyMessageCallback() { ``` Example 2: Using ECC to sign data and verify the signature. -1. Generate an ECC key. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. - -2. Create a **Sign** instance. - - Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. - -3. Generate a signature. - - Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. - -4. Create a **Verify** instance. - - Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. - -5. Verify the signature. - - Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -802,10 +766,10 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------------- | | cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. | -| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| -| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | -| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | -| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. | +| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| +| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | +| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | +| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. | | Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. | | Md | readonly algName : string; | Obtains the digest algorithm. | @@ -907,10 +871,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry **How to Develop** -1. Generate an ECC key. - - Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. - +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. 2. Generate a shared secret by using the private and public ECC keys. ```javascript @@ -966,15 +927,15 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | --------------------------------------------------- | -| cryptoFramework | function createMac(algName : string) : Md; | Creates a **Mac** instance. | -| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| -| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | -| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | -| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | -| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | -| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | +| cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. | +| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| +| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | +| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | +| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | +| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | +| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | | Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. | -| Mac | readonly algName : string; | Obtains the algorithm. | +| Mac | readonly algName : string; | Obtains the digest algorithm. | **How to Develop** @@ -1099,10 +1060,9 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Instance | API | Description | | --------------- | ------------------------------------------------------------ | ---------------------------------------------- | | cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | -| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | -| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | -| Random | setSeed(seed : DataBlob, callback : AsyncCallback\) : void; | Sets a seed. This API uses an asynchronous callback to return the result.| -| Random | setSeed(seed : DataBlob) : Promise\; | Sets a seed. This API uses a promise to return the result. | +| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | +| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | +| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | **How to Develop** @@ -1124,10 +1084,11 @@ function doRandByPromise(len) { var promiseGenerateRand = rand.generateRandom(len); promiseGenerateRand.then(randData => { console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; - }).then(() => { - console.error("[Promise]: setSeed success"); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -1146,13 +1107,11 @@ function doRandByCallback(len) { console.error("[Callback]: err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1,) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); } diff --git a/en/application-dev/security/cryptoFramework-overview.md b/en/application-dev/security/cryptoFramework-overview.md index afaa9658f3b9bd55754f3d830090ff3eece4e26a..9b0248563b33df85f26ff10b33432465ba6cf367 100644 --- a/en/application-dev/security/cryptoFramework-overview.md +++ b/en/application-dev/security/cryptoFramework-overview.md @@ -1,14 +1,14 @@ # Crypto Framework Overview -The crypto framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hash, and secure random number. You can use the APIs provided by this framework to implement cipher development quickly. +The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, message authentication code (MAC), hashes, and secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. ## Working Principles -The crypto framework provides components in the following layers: +The crypto framework provides components in the following layers: - Interface layer: provides unified JS interface externally. - Plugin layer: implements third-party algorithm libraries. -- Framework layer: flexibly loads the plugins in the plugin layer to adapt to third-party algorithm libraries and shields the implement differences between the third-party algorithm libraries. +- Framework layer: flexibly loads the plugins in the plugin layer to adapt to third-party algorithm libraries and shields the implementation differences between these libraries. ## Basic Concepts -### Symmetric Key +**Symmetric Key** A symmetric key is a key used both to encrypt and decrypt data. In symmetric encryption, the sender converts information in plaintext into ciphertext using a key and certain algorithm for security purposes. The receiver converts the ciphertext into plaintext using the same key and algorithm. @@ -19,7 +19,7 @@ A symmetric key is a key used both to encrypt and decrypt data. In symmetric enc Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but its processing speed is lower. The AES is faster and more secure than 3DES. -### Asymmetric Key +**Asymmetric Key** In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For signing and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data. @@ -27,7 +27,7 @@ In the asymmetric cryptography, a private and public key pair is required. The p The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows: - 1. Generate two large prime numbers **p** and **q**. + 1. Generate two large prime numbers **p** and **q**. 2. Compute **n** = **p** x **q**. @@ -41,44 +41,37 @@ In the asymmetric cryptography, a private and public key pair is required. The p The public key consists of the modulus **n** and the public exponent **e**. The private key consists of **n** and the private exponent **d**. - In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see **Constraints**. + In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see [**Constraints**](#constraints). - ECC key Elliptic-Curve Cryptography (ECC) is a public-key encryption based on the algebraic structure of elliptic curve over finite fields. The crypto framework provides a variety of ECC key generation capabilities. -### Encryption and Decryption +**Encryption and Decryption** - Symmetric AES encryption and decryption - The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. - - AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - + The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes. - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - > **NOTE** - > - > In ECB and CBC modes, the plaintext length is not an integer multiple of 128 bits and must be padded. - -- Symmetric 3DES encryption and decryption - - 3DES encryption and decryption apply the DES cipher three times to each data block obtain the ciphertext or plaintext. - The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. + > **NOTE** + > + > In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 128 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. + +- Symmetric 3DES encryption and decryption - DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: + 3DES encryption and decryption apply the DES cipher three times to each data block to obtain the ciphertext or plaintext. + The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: - **NoPadding**: no padding. - **PKCS5**: pads a block cipher with a block size of 8 bytes. - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - > **NOTE** + > **NOTE** > - > In ECB and CBC, the plaintext length is not an integer multiple of 64 bits and must be padded. + > In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 64 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. - Asymmetric RSA encryption and decryption @@ -90,21 +83,17 @@ In the asymmetric cryptography, a private and public key pair is required. The p Plaintext = Ciphertext ^ **d** mod **n** - The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. - - RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: + The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: - **NoPadding**: No padding is required. The length of the input or output data must be the same as that of the RSA key modulus. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. The length of the input data must be less than or equal to the RSA key modulus minus 11, and the length of the output data must be the same as that of the RSA key modulus. + - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus the **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - - **NOTE** - - Length of the RSA key modulus = (Number of RSA bits + 7)/8 + > **NOTE** + > + > Length of the RSA key modulus = (Number of RSA bits + 7)/8 -### Signing and Signature Verification +**Signing and Signature Verification** - RSA signing and signature verification @@ -116,41 +105,41 @@ In the asymmetric cryptography, a private and public key pair is required. The p Message = Signature ^ **d** mod **n** - The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest and then sign the message. The crypto framework provides the following padding modes for signing and signature verification: + The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest before signing the message. The crypto framework provides the following padding modes for signing and signature verification: - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. When this mode is used, the digest (**md**) must be set. - **PSS**: The PSS mode is a padding algorithm based on the RSA algorithm. When it is used, the digest (**md**) and mask function (**mgf1_md**) are required. - ECDSA - The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the unit bit strength of ECC is higher than that of other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms. + The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the ECC provides a higher unit bit strength than other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms. -### Key Agreement +**Key Agreement** -**ECDH** +- **ECDH** -Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library. + Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library. -### Digest +**Digest** -The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. The message digest algorithm is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. +The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. It is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. When the same digest algorithm is used, the generated digest (hash value) has the following features: - The same message always results in the same hash value. - The digest generated is of the fixed length no matter the length of messages. (The digest length is determined by the algorithm used). -- It is almost impossible to find two different messages with the same hash value (the probability still exists, depending on the length of the digest). +- It is almost impossible to find two different messages with the same hash value. (The probability still exists, depending on the length of the digest.) -There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section "**HMAC**". +There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section **HMAC**. MD algorithms include MD2, MD4, and MD5. Major SHA algorithms include SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. -### HMAC +**HMAC** -Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify both the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. +Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. Compared with MAC, HMAC introduces the shared secret, which ensures data correctness. -### Random Number +**Random Number** -Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. Random numbers can be generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, repeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness. +Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. They are generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, unrepeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness. - Internal state @@ -163,7 +152,7 @@ Random numbers are mainly used to generate temporary session keys or keys in asy ## Constraints -- The crypto framework does not support concurrent operations of multiple threads. +The crypto framework does not support concurrent operations of multiple threads. ### Key Generation Specifications @@ -171,19 +160,24 @@ Random numbers are mainly used to generate temporary session keys or keys in asy The following parameters are supported: -|Symmetric Key Algorithm|Key Length|String for Generating a Key| +|Symmetric Key Algorithm|Key Length (Bit)|String Parameter| |---|---|---| |3DES|192|3DES192| |AES|128|AES128| |AES|192|AES192| |AES|256|AES256| + > **NOTE** + > + > **String Parameter** is a combination of **Symmetric Key Algorithm** and **Key Length**. It specifies the key specifications when a symmetric key generator is created. + **Asymmetric Key Generation Specifications** + - **RSA key generation** The following parameters are supported: - |Asymmetric Key Algorithm|Key Length|Number of Primes|String for Generating a Key| + |Asymmetric Key Algorithm|Key Length (Bit)|Number of Primes|String Parameter| |---|---|---|---| |RSA|512|2|RSA512\|PRIMES_2| |RSA|768|2|RSA768\|PRIMES_2| @@ -203,7 +197,7 @@ The following parameters are supported: > **NOTE** > - > When the RSA asymmetric key is generated, the default number of primes is 2 and the **PRIMES_2** parameter can be omitted. + > When an RSA asymmetric key is generated, the default prime number is 2, and **PRIMES_2** is optional. - **ECC key generation** @@ -214,7 +208,7 @@ The following parameters are supported: |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| - |ECC|ECC512| + |ECC|ECC521| ### Encryption and Decryption Specifications @@ -222,7 +216,7 @@ The following parameters are supported: The following symmetric encryption algorithms are supported: -|Algorithm|Block Cipher Mode|Algorithm String| +|Algorithm|Block Cipher Mode| String Parameter | |---|---|---| |3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]| |3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]| @@ -237,56 +231,56 @@ The following symmetric encryption algorithms are supported: |AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| > **NOTE** -> -> The options included in the square brackets ([]) are mutually exclusive. +> - The options included in the square brackets ([]) are mutually exclusive. +> - **String Parameter** is a combination of **Algorithm** (including the key length), **Block Cipher Mode**, and padding mode. It specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. **Asymmetric RSA Encryption and Decryption** -The following padding modes are involved in RSA encryption and decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. -- When **NoPadding** is used, you can specify the following parameters: +The crypto framework provides three padding modes for RSA encryption/decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. +- If **NoPadding** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|NoPadding -- When **PKCS1** is used, you can specify the following parameters: +- If **PKCS1** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1 -- When **PKCS1_OAEP** is used, you can specify the following parameters: +- If **PKCS1_OAEP** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1_OAEP|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512] > **NOTE** > -> The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. +> The options included in the square brackets ([]) are mutually exclusive, and the options outside [] are fixed values. ### Signing and Signature Verification Specifications **RSA Signing and Signature Verification** -The following padding modes are involved in RSA encryption and decryption: **PKCS1** and **PSS**. -- When **PKCS1** is used, you can specify the following parameters: +The crypto framework provides two padding modes for RSA signing and signature verification: **PKCS1** and **PSS**. +- If **PKCS1** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PKCS1|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512] -- When **PSS** is used, you can specify the following parameters: +- If **PSS** is used, specify the parameter as follows: [RSA512|RSA768|RSA1024|RSA2048|RSA3072|RSA4096|RSA8192]|PSS|[MD5|SHA1|SHA224|SHA256|SHA384|SHA512]|[MGF1_MD5|MGF1_SHA1|MGF1_SHA224|MGF1_SHA256|MGF1_SHA384|MGF1_SHA512] > **NOTE** > -> The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. +> The options included in the square brackets ([]) are mutually exclusive, and the options outside [] are fixed values. **ECDSA Signing and Signature Verification** The following ECDSA parameters are supported: -|Asymmetric Key Algorithm|Supported Types| +|Asymmetric Key Algorithm|Supported Type| |---|---| |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| -|ECC|ECC512| +|ECC|ECC521| -|Digest Algorithm|Supported Types| +|Digest Algorithm|Supported Type| |---|---| |HASH|SHA-1| |HASH|SHA-224| @@ -300,12 +294,12 @@ The following ECDSA parameters are supported: The following ECDH parameters are supported: -|Asymmetric Key Algorithm|Supported Types| +|Asymmetric Key Algorithm|Supported Type| |---|---| |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| -|ECC|ECC512| +|ECC|ECC521| ### MD Algorithm Specifications The crypto framework supports only MD5. diff --git a/en/application-dev/security/figures/permission-read_calendar.png b/en/application-dev/security/figures/permission-read_calendar.png new file mode 100644 index 0000000000000000000000000000000000000000..8236bcf2f28531c88362f1210cf70101740394bf Binary files /dev/null and b/en/application-dev/security/figures/permission-read_calendar.png differ diff --git a/en/application-dev/security/hapsigntool-overview.md b/en/application-dev/security/hapsigntool-overview.md index bb91ed70b2cd9edeef18cc29348bb59d1908e559..24901bd3b2df1bcc9f0e14fc53a845171854c631 100644 --- a/en/application-dev/security/hapsigntool-overview.md +++ b/en/application-dev/security/hapsigntool-overview.md @@ -26,7 +26,7 @@ The hapsigner tool is implemented based on the Public Key Infrastructure (PKI). - Profile - [HarmonyAppProvision configuration file](../quick-start/app-provision-structure.md) provides information such as the authorized application permissions and device ID. + [HarmonyAppProvision configuration file](app-provision-structure.md) provides information such as the authorized application permissions and device ID. ## Constraints diff --git a/en/application-dev/security/huks-guidelines.md b/en/application-dev/security/huks-guidelines.md index cfeb93d8d766b4c8b791db43a7be18e95583c575..b72be28c24888642d1220779104477d28a170176 100644 --- a/en/application-dev/security/huks-guidelines.md +++ b/en/application-dev/security/huks-guidelines.md @@ -2,7 +2,7 @@ OpenHarmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys. -> **NOTE**
+> **NOTE** > > This document is based on API version 9 and applies only to ArkTS development. @@ -20,9 +20,9 @@ Generate a key for an application by specifying the alias and key parameters. > **NOTE** > -> 1. When a key is used if the parameters passed in does not comply with the parameters passed in during the key generation, the parameter verification will fail. +> - When a key is used if the parameters passed in does not comply with the parameters passed in during the key generation, the parameter verification will fail. > -> 2. If an optional parameter required by the algorithm is not passed in during the key generation process, it must be passed in when the key is used. +> - If an optional parameter required by the algorithm is not passed in during the key generation process, it must be passed in when the key is used. **Supported Key Types** diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 7f84d9cd058732ee490428034d90338bfaf7ea9c..073b31fc651ced76f80b95ed796ca452ca4c62d2 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1,165 +1,1605 @@ -# App Permission List - -Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine whether the app can apply for the target permissions based on the table below. - -For details about permission usage examples, see [Permission Application Guide](accesstoken-guidelines.md). - -| Permission | APL | Authorization Mode | Enable ACL| Description | -| -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------- | -| ohos.permission.USE_BLUETOOTH | normal | system_grant | TRUE | Allows an app to access to Bluetooth configuration. | -| ohos.permission.DISCOVER_BLUETOOTH | normal | system_grant | TRUE | Allows an app to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. | -| ohos.permission.MANAGE_BLUETOOTH | system_basic | system_grant | TRUE | Allows an app to pair with a Bluetooth device and access the contacts or messages of the device. | -| ohos.permission.INTERNET | normal | system_grant | TRUE | Allows an app to access the Internet. | -| ohos.permission.
MODIFY_AUDIO_SETTINGS | normal | system_grant | TRUE | Allows an app to modify audio settings. | -| ohos.permission.
ACCESS_NOTIFICATION_POLICY | normal | system_grant | FALSE | Allows an app to access the notification policy on the device. | -| ohos.permission.GET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to read telephony information. | -| ohos.permission.REQUIRE_FORM | system_basic | system_grant | TRUE | Allows an app to obtain the Ability Form. | -| ohos.permission.GET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to obtain network information. | -| ohos.permission.PLACE_CALL | system_basic | system_grant | TRUE | Allows an app to make calls without starting the dialer. | -| ohos.permission.SET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to set data network information. | -| ohos.permission.REMOVE_CACHE_FILES | system_basic | system_grant | TRUE | Allows the cache of the specified app to be cleared. | -| ohos.permission.REBOOT | system_basic | system_grant | TRUE | Allows an app to restart the device. | -| ohos.permission.RUNNING_LOCK | normal | system_grant | TRUE | Allows an app to obtain a running lock. | -| ohos.permission.SET_TIME | system_basic | system_grant | TRUE | Allows an app to set the system time. | -| ohos.permission.SET_TIME_ZONE | system_basic | system_grant | TRUE | Allows an app to set the system time zone. | -| ohos.permission.
DOWNLOAD_SESSION_MANAGER | system_core | system_grant | TRUE | Allows an app to manage the download sessions. | -| ohos.permission.COMMONEVENT_STICKY | normal | system_grant | TRUE | Allows an app to publish sticky common events. | -| ohos.permission.SYSTEM_FLOAT_WINDOW | system_basic | system_grant | TRUE | Allows an app to be displayed in a floating window on top of other apps. | -| ohos.permission.PRIVACY_WINDOW | system_basic | system_grant | TRUE | Allows an app to set screens that cannot be captured or recorded. | -| ohos.permission.POWER_MANAGER | system_core | system_grant | TRUE | Allows an app to hibernate or wake up the device by calling APIs. | -| ohos.permission.REFRESH_USER_ACTION | system_basic | system_grant | TRUE | Allows an app to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. | -| ohos.permission.POWER_OPTIMIZATION | system_basic | system_grant | TRUE | Allows an app to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes.| -| ohos.permission.REBOOT_RECOVERY | system_basic | system_grant | TRUE | Allows an app to restart the device and enter Recovery mode. | -| ohos.permission.
MANAGE_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows an app to manage local user accounts. | -| ohos.permission.
INTERACT_ACROSS_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows access between multiple OS accounts. | -| ohos.permission.VIBRATE | normal | system_grant | TRUE | Allows an app to control vibration. | -| ohos.permission.CONNECT_IME_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind to the **InputMethodAbility**. | -| ohos.permission.
CONNECT_SCREEN_SAVER_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind to the **ScreenSaverAbility**. | -| ohos.permission.
READ_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to read the screen saver information, such as the list of screen savers that have been installed and the activated one. | -| ohos.permission.
WRITE_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to modify the screen saver information, such as activating and previewing a screen saver. | -| ohos.permission.SET_WALLPAPER | normal | system_grant | TRUE | Allows an app to set a static wallpaper. | -| ohos.permission.GET_WALLPAPER | system_basic | system_grant | TRUE | Allows an app to read wallpaper files. | -| ohos.permission.
CHANGE_ABILITY_ENABLED_STATE | system_basic | system_grant | TRUE | Allows an app to enable or disable an app or component. | -| ohos.permission.ACCESS_MISSIONS | system_basic | system_grant | TRUE | Allows an app to obtain information about running processes and mission in a mission stack. | -| ohos.permission.
CLEAN_BACKGROUND_PROCESSES | normal | system_grant | TRUE | Allows an app to clear background processes based on their bundle names. | -| ohos.permission.
KEEP_BACKGROUND_RUNNING | normal | system_grant | TRUE | Allows a Service ability to keep running in the background. | -| ohos.permission.
UPDATE_CONFIGURATION | system_basic | system_grant | TRUE | Allows an app to modify system settings. | -| ohos.permission.UPDATE_SYSTEM | system_basic | system_grant | TRUE | Allows an app to call the update APIs. | -| ohos.permission.FACTORY_RESET | system_basic | system_grant | TRUE | Allows an app to call the APIs for restoring factory settings. | -| ohos.permission.
GRANT_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to grant sensitive permissions to other apps. | -| ohos.permission.
REVOKE_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to revoke sensitive permissions granted to other apps. | -| ohos.permission.
GET_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to obtain the sensitive permissions that have been granted to other apps. | -| ohos.permission.INTERACT_
ACROSS_LOCAL_ACCOUNTS_EXTENSION | system_core | system_grant | TRUE | Allows an app to set the attributes of apps of other users. | -| ohos.permission.LISTEN_BUNDLE_CHANGE | system_basic | system_grant | TRUE | Allows an app to listen for changes in other apps, when they are installed, updated, or uninstalled. | -| ohos.permission.GET_BUNDLE_INFO | normal | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | -| ohos.permission.ACCELEROMETER | normal | system_grant | TRUE | Allows an app to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. | -| ohos.permission.GYROSCOPE | normal | system_grant | TRUE | Allows an app to read data from a gyroscope sensor or uncalibrated gyroscope sensor. | -| ohos.permission.
GET_BUNDLE_INFO_PRIVILEGED | system_basic | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | -| ohos.permission.INSTALL_BUNDLE | system_core | system_grant | TRUE | Allows an app to install and uninstall other apps. | -| ohos.permission.MANAGE_SHORTCUTS | system_core | system_grant | TRUE | Allows an app to query and start shortcuts of other apps.| -| ohos.permission.radio.ACCESS_FM_AM | system_core | system_grant | TRUE | Allows an app to access radio services. | -| ohos.permission.SET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to change the telephone state. | -| ohos.permission.
START_ABILITIES_FROM_BACKGROUND | system_basic | system_grant | TRUE | Allows an app to start Feature abilities in the background. | -| ohos.permission.BUNDLE_ACTIVE_INFO | system_basic | system_grant | TRUE | Allows an app to obtain how long other apps have been running in the foreground or background. | -| ohos.permission.
START_INVISIBLE_ABILITY | system_core | system_grant | TRUE | Allows an app to start an invisible ability. | -| ohos.permission.sec.ACCESS_UDID | system_basic | system_grant | TRUE | Allows an app to obtain the Unified Device ID (UDID). | -| ohos.permission.
LAUNCH_DATA_PRIVACY_CENTER | system_basic | system_grant | TRUE | Allows an app to switch from its privacy statement page to the Data & privacy page. | -| ohos.permission.MANAGE_MEDIA_RESOURCES | system_basic | system_grant | TRUE | Allows an app to obtain and manage the media resources that are being played on the device.| -| ohos.permission.PUBLISH_AGENT_REMINDER | normal | system_grant | TRUE | Allows an app to use agent-powered reminders. | -| ohos.permission.
CONTROL_TASK_SYNC_ANIMATOR | system_core | system_grant | TRUE | Allows apps to use sync task animations. | -| ohos.permission.INPUT_MONITORING | system_core | system_grant | TRUE | Allows an app to listen for input events. Only the system signature apps can apply for this permission. | -| ohos.permission.MANAGE_MISSIONS | system_core | system_grant | TRUE | Allows an app to manage ability mission stacks. | -| ohos.permission.
NOTIFICATION_CONTROLLER | system_core | system_grant | TRUE | Allows an app to manage and subscribe to notifications. | -| ohos.permission.CONNECTIVITY_INTERNAL | system_basic | system_grant | TRUE | Allows an app to obtain network information or modify network settings. | -| ohos.permission.SET_ABILITY_CONTROLLER | system_basic | system_grant | TRUE | Allows an app to set the start and stop of an ability. | -| ohos.permission.USE_USER_IDM | system_basic | system_grant | FALSE | Allows an app to access the system identity credential information. | -| ohos.permission.MANAGE_USER_IDM | system_basic | system_grant | FALSE | Allows an app to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints.| -| ohos.permission.ACCESS_BIOMETRIC | normal | system_grant | TRUE | Allows an app to use biometric recognition for identity authentication. | -| ohos.permission.
ACCESS_USER_AUTH_INTERNAL | system_basic | system_grant | FALSE | Allows an app to use the system identity authentication capability to authenticate or identify users. | -| ohos.permission.ACCESS_PIN_AUTH | system_basic | system_grant | FALSE | Allows a system app to call the PIN input APIs to present a password input dialog box for users.| -| ohos.permission.GET_RUNNING_INFO | system_basic | system_grant | TRUE | Allows an app to obtain running status information. | -| ohos.permission.CLEAN_APPLICATION_DATA | system_basic | system_grant | TRUE | Allows an app to clear app data. | -| ohos.permission.RUNNING_STATE_OBSERVER | system_basic | system_grant | TRUE | Allows an app to observe the app status. | -| ohos.permission.CAPTURE_SCREEN | system_core | system_grant | TRUE | Allows an app to take screenshots. | -| ohos.permission.GET_WIFI_INFO | normal | system_grant | TRUE | Allows an app to obtain WLAN information. | -| ohos.permission.GET_WIFI_INFO_INTERNAL | system_core | system_grant | TRUE | Allows an app to obtain WLAN information. | -| ohos.permission.SET_WIFI_INFO | normal | system_grant | TRUE | Allows an app to set WLAN devices. | -| ohos.permission.GET_WIFI_PEERS_MAC | system_core | system_grant | TRUE | Allows an app to obtain the MAC address of the peer WLAN or Bluetooth device. | -| ohos.permission.GET_WIFI_LOCAL_MAC | system_basic | system_grant | TRUE | Allows an app to obtain the MAC address of the local WLAN or Bluetooth device. | -| ohos.permission.GET_WIFI_CONFIG | system_basic | system_grant | TRUE | Allows an app to obtain the WLAN configuration. | -| ohos.permission.SET_WIFI_CONFIG | system_basic | system_grant | TRUE | Allows an app to set WLAN information. | -| ohos.permission.
MANAGE_WIFI_CONNECTION | system_core | system_grant | TRUE | Allows an app to manage WLAN connections. | -| ohos.permission.MANAGE_WIFI_HOTSPOT | system_core | system_grant | TRUE | Allows an app to enable or disable Wi-Fi hotspots. | -| ohos.permission.GET_ALL_APP_ACCOUNTS | system_core | system_grant | FALSE | Allows an app to obtain all app account information. | -| ohos.permission.MANAGE_SECURE_SETTINGS | system_basic | system_grant | TRUE | Allows an app to modify security settings. | -| ohos.permission.READ_DFX_SYSEVENT | system_basic | system_grant | FALSE | Allows an app to obtain all app account information. | -| ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN | system_core | system_grant | TRUE | Allows an app to activate the device administrator app. | -| ohos.permission.SET_ENTERPRISE_INFO | system_basic | system_grant | TRUE | Allows the device administrator app to set enterprise information. | -| ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT | system_basic | system_grant | TRUE | Allows the device administrator app to subscribe to management events. | -| ohos.permission.ENTERPRISE_SET_DATETIME | system_basic | system_grant | TRUE | Allows the device administrator app to set the system time. | -| ohos.permission.ENTERPRISE_GET_DEVICE_INFO | system_basic | system_grant | TRUE | Allows the device administrator app to obtain device information. | -| ohos.permission.NFC_TAG | normal | system_grant | FALSE | Allows an app to read NFC tag information. | -| ohos.permission.NFC_CARD_EMULATION | normal | system_grant | FALSE | Allows an app to implement card emulation. | -| ohos.permission.PERMISSION_USED_STATS | system_basic | system_grant | TRUE | Allows a system application to access the permission usage records. | -| ohos.permission.
NOTIFICATION_AGENT_CONTROLLER | system_core | system_grant | TRUE | Allows an app to send agent-powered notifications. | -| ohos.permission.ANSWER_CALL | system_basic | user_grant | TRUE | Allows an app to answer incoming calls. | -| ohos.permission.READ_CALENDAR | normal | user_grant | TRUE | Allows an app to read calendar data. | -| ohos.permission.READ_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to read call logs. | -| ohos.permission.READ_CELL_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read cell broadcast messages received by the device. | -| ohos.permission.READ_CONTACTS | system_basic | user_grant | TRUE | Allows an app to read contacts. | -| ohos.permission.READ_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read messages. | -| ohos.permission.RECEIVE_MMS | system_basic | user_grant | TRUE | Allows an app to receive and process MMS messages. | -| ohos.permission.RECEIVE_SMS | system_basic | user_grant | TRUE | Allows an app to receive and process SMS messages. | -| ohos.permission.RECEIVE_WAP_MESSAGES | system_basic | user_grant | TRUE | Allows an app to receive and process WAP messages. | -| ohos.permission.MICROPHONE | normal | user_grant | TRUE | Allows an app to access the microphone. | -| ohos.permission.SEND_MESSAGES | system_basic | user_grant | TRUE | Allows an app to send messages. | -| ohos.permission.WRITE_CALENDAR | normal | user_grant | TRUE | Allows an app to add, remove, and modify calendar events. | -| ohos.permission.WRITE_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify call logs. | -| ohos.permission.WRITE_CONTACTS | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify contacts. | -| ohos.permission.DISTRIBUTED_DATASYNC | normal | user_grant | TRUE | Allows an app to exchange data with other devices. | -| ohos.permission.MANAGE_VOICEMAIL | system_basic | user_grant | TRUE | Allows an app to leave messages in the voice mailbox. | -| ohos.permission.
LOCATION_IN_BACKGROUND | normal | user_grant | FALSE | Allows an app running in the background to obtain the device location. | -| ohos.permission.LOCATION | normal | user_grant | TRUE | Allows an app to obtain the device location. | -| ohos.permission.APPROXIMATELY_LOCATION | normal | user_grant | FALSE | Allows an app to obtain the approximate location information of a device. | -| ohos.permission.MEDIA_LOCATION | normal | user_grant | TRUE | Allows an app to access geographical locations in the user's media file. | -| ohos.permission.CAMERA | normal | user_grant | TRUE | Allows an app to use the camera to take photos and record videos. | -| ohos.permission.READ_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from the user's external storage. | -| ohos.permission.WRITE_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from and write media files into the user's external storage. | -| ohos.permission.ACTIVITY_MOTION | normal | user_grant | TRUE | Allows an app to read the current workout status of the user. | -| ohos.permission.READ_HEALTH_DATA | normal | user_grant | TRUE | Allows an app to read the health data of the user. | -| ohos.permission.GET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to query default apps. | -| ohos.permission.SET_DEFAULT_APPLICATION | system_core | system_grant | TRUE | Allows an app to set and reset default apps. | -| ohos.permission.
MANAGE_DISPOSED_APP_STATUS | system_core | system_grant | TRUE | Allows an app to set and query the app handling state. | -| ohos.permission.ACCESS_IDS | system_core | system_grant | TRUE | Allows an app to query the unique identifier of a device. | -| ohos.permission.DUMP | system_core | system_grant | TRUE | Allows the basic system information and SA service information to be exported. | -| ohos.permission.
DISTRIBUTED_SOFTBUS_CENTER | system_basic | system_grant | FALSE | Allows networking between different devices. | -| ohos.permission.ACCESS_DLP_FILE | system_core | system_grant | TRUE | Allows configuration and management of the permissions on .dlp files. | -| ohos.permission.PROVISIONING_MESSAGE | system_core | system_grant | TRUE | Allows the Super Device Manager application to be activated. | -| ohos.permission.
ACCESS_SYSTEM_SETTINGS | system_basic | system_grant | TRUE | Allows an app to access or start system **Settings**. | -| ohos.permission.READ_IMAGEVIDEO | system_basic | user_grant | TRUE | Allows access to the images or video files in a user's directory. | -| ohos.permission.READ_AUDIO | system_basic | user_grant | TRUE | Allows access to the audio files in a user's directory. | -| ohos.permission.READ_DOCUMENT | system_basic | user_grant | TRUE | Allows access to the files in a user's directory. | -| ohos.permission.WRITE_IMAGEVIDEO | system_basic | user_grant | TRUE | Allows modification to the images or video files in a user's directory. | -| ohos.permission.WRITE_AUDIO | system_basic | user_grant | TRUE | Audio modification to the audio files in a user's directory. | -| ohos.permission.WRITE_DOCUMENT | system_basic | user_grant | TRUE | Allows modification to the files in a user's directory. | -| ohos.permission.
ABILITY_BACKGROUND_COMMUNICATION | system_basic | system_grant | TRUE | Allows an app to start the Ability component in the background and establish a connection with it. | -| ohos.permission.
securityguard.REPORT_SECURITY_INFO | system_basic | system_grant | FALSE | Allows an app to report risk data for security guard. | -| ohos.permission.
securityguard.REQUEST_SECURITY_MODEL_RESULT | system_basic | system_grant | TRUE | Allows an app to obtain the device risk status. | -| ohos.permission.
securityguard.REQUEST_SECURITY_EVENT_INFO | system_core | system_grant | FALSE | Allows an app to obtain detailed risk data. | -| ohos.permission.
READ_ACCESSIBILITY_CONFIG | system_basic | system_grant | FALSE | Allows an app to read the accessibility configuration. | -| ohos.permission.
WRITE_ACCESSIBILITY_CONFIG | system_basic | system_grant | FALSE | Allows an app to set the accessibility configuration. | -| ohos.permission.
ACCESS_CERT_MANAGER_INTERNAL | system_basic | system_grant | FALSE | Allows an app to install, uninstall, enable, and disable certificates and credentials. | -| ohos.permission.
ACCESS_CERT_MANAGER | normal | system_grant | FALSE | Allows an app to manage private credentials and query certificate status. | -| ohos.permission.
ACCESS_PUSH_SERVICE | system_basic | system_grant | TRUE | Allows an app to to access the Ability of the push service. | -| ohos.permission.
RECEIVER_STARTUP_COMPLETED | system_basic | system_grant | FALSE | Allows an app to subscribe to the startup broadcast. | -| ohos.permission.
MANAGE_CAMERA_CONFIG | system_basic | system_grant | FALSE | Allows an app to enable or disable cameras globally. | -| ohos.permission.READ_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | Allows an app to read all calendar information. | -| ohos.permission.WRITE_WHOLE_CALENDAR | system_basic | uesr_grant | TRUE | Allows an app to add, remove, or change all calendar events. | -| ohos.permission.ENFORCE_USER_IAM | system_core | system_grant | TRUE | Allows an SA to delete user information from the IAM subsystem without a token. | -| ohos.permission.ACCESS_AUTH_RESPOOL | system_core | system_grant | TRUE | Allows an SA to register the executor. | -| ohos.permission.MOUNT_UNMOUNT_MANAGER | system_basic | system_grant | FALSE | Allows an app to mount and unmount external cards. | -| ohos.permission.MOUNT_FORMAT_MANAGER | system_basic | system_grant | FALSE | Allows an app to format external cards. | -| ohos.permission.STORAGE_MANAGER | system_basic | system_grant | TRUE | Allows an app to call the interfaces of the Storage Manager service to query space statistics and volume information. | -| ohos.permission.BACKUP | system_basic | system_grant | TRUE | Allows an app to have backup and restore capabilities. | -| ohos.permission.FILE_ACCESS_MANAGER | system_basic | system_grant | TRUE | Allows a file management app to access user data files through the FAF. | -| ohos.permission.MANAGE_AUDIO_CONFIG | system_basic | system_grant | TRUE | Allows an app to to mute microphones globally. | +# Application Permission List + +Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine the permissions required for your application. + +For details about how to apply for required permissions, see [Permission Application Guide](accesstoken-guidelines.md). + +## ohos.permission.USE_BLUETOOTH + +Allows an application to access Bluetooth configurations. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISCOVER_BLUETOOTH + +Allows an application to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_BLUETOOTH + +Allows an application to pair with a Bluetooth device and access the contacts or messages of the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERNET + +Allows an application to access the Internet. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MODIFY_AUDIO_SETTINGS + +Allows an application to modify audio settings. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_NOTIFICATION_POLICY + +Allows an application to access the notification policy on the device. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.GET_TELEPHONY_STATE + +Allows an application to read telephony information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REQUIRE_FORM + +Allows an application to obtain widgets. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_NETWORK_INFO + +Allows an application to obtain network information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PLACE_CALL + +Allows an application to make calls without starting the dialer. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_NETWORK_INFO + +Allows an application to set data network information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REMOVE_CACHE_FILES + +Allows the cache of the specified application to be cleared. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REBOOT + +Allows an application to restart the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUNNING_LOCK + +Allows an application to obtain a running lock. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TIME + +Allows an application to set the system time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TIME_ZONE + +Allows an application to set the system time zone. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DOWNLOAD_SESSION_MANAGER + +Allows an application to manage download sessions. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.COMMONEVENT_STICKY + +Allows an application to publish sticky common events. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SYSTEM_FLOAT_WINDOW + +Allows an application to be displayed in a floating window on top of other applications. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PRIVACY_WINDOW + +Allows an application to set screens that cannot be captured or recorded. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.POWER_MANAGER + +Allows an application to hibernate or wake up the device by calling an API. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REFRESH_USER_ACTION + +Allows an application to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.POWER_OPTIMIZATION + +Allows an application to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REBOOT_RECOVERY + +Allows an application to restart the device and enter Recovery mode. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_LOCAL_ACCOUNTS + +Allows an application to manage local user accounts. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +Allows access between multiple OS accounts. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.VIBRATE + +Allows an application to control vibration. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECT_IME_ABILITY + +Allows an application to bind the InputMethodAbility. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECT_SCREEN_SAVER_ABILITY + +Allows an application to bind the ScreenSaverAbility. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_SCREEN_SAVER + +Allows an application to read the screen saver information, such as the list of screen savers that have been installed and the activated one. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_SCREEN_SAVER + +Allows an application to modify the screen saver information, such as activating and previewing a screen saver. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WALLPAPER + +Allows an application to set a static wallpaper. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WALLPAPER + +Allows an application to read wallpaper files. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +Allows an application to enable or disable an application or component. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_MISSIONS + +Allows an application to obtain information about running processes and mission in a mission stack. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CLEAN_BACKGROUND_PROCESSES + +Allows an application to clear background processes based on their bundle names. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.KEEP_BACKGROUND_RUNNING + +Allows a Service ability to keep running in the background. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.UPDATE_CONFIGURATION + +Allows an application to modify system settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.UPDATE_SYSTEM + +Allows an application to call the update APIs. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.FACTORY_RESET + +Allows an application to call the API for restoring factory settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GRANT_SENSITIVE_PERMISSIONS + +Allows an application to grant sensitive permissions to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.REVOKE_SENSITIVE_PERMISSIONS + +Allows an application to revoke sensitive permissions granted to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_SENSITIVE_PERMISSIONS + +Allows an application to obtain the sensitive permissions that have been granted to other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + +Allows an application to set the attributes of applications of other users. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.LISTEN_BUNDLE_CHANGE + +Allows an application to listen for changes in other applications, when they are installed, updated, or uninstalled. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_BUNDLE_INFO + +Allows an application to query information about another application. This permission applies only to third-party applications. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +Allows an application to query information about other applications at the same time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCELEROMETER + +Allows an application to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GYROSCOPE + +Allows an application to read data from a gyroscope sensor or uncalibrated gyroscope sensor. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INSTALL_BUNDLE + +Allows an application to install and uninstall other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_SHORTCUTS + +Allows an application to query and start shortcuts of other applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.radio.ACCESS_FM_AM + +Allows an application to access radio services. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_TELEPHONY_STATE + +Allows an application to change the telephone state. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.START_ABILIIES_FROM_BACKGROUND + +Allows an application to start Feature abilities in the background. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.BUNDLE_ACTIVE_INFO + +Allows an application to obtain how long other applications have been running in the foreground or background. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.START_INVISIBLE_ABILITY + +Allows an application to start an invisible ability. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.sec.ACCESS_UDID + +Allows an application to obtain the Unified Device ID (UDID). + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.LAUNCH_DATA_PRIVACY_CENTER + +Allows an application to switch from its privacy statement page to the Data & privacy page. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_MEDIA_RESOURCES + +Allows an application to obtain and manage the media resources that are being played on the device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PUBLISH_AGENT_REMINDER + +Allows an application to use agent-powered reminders. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR + +Allows applications to use sync task animations. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.INPUT_MONITORING + +Allows an application to listen for input events. Only the system signed applications can apply for this permission. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_MISSIONS + +Allows an application to manage ability mission stacks. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NOTIFICATION_CONTROLLER + +Allows an application to manage and subscribe to notifications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CONNECTIVITY_INTERNAL + +Allows an application to obtain network information or modify network settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_ABILITY_CONTROLLER + +Allows an application to set the start and stop of an ability. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.USE_USER_IDM + +Allows an application to access the system identity credential information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_USER_IDM + +Allows an application to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_BIOMETRIC + +Allows an application to use biometric recognition for identity authentication. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_USER_AUTH_INTERNAL + +Allows an application to use the system identity authentication capability to authenticate or identify users. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_PIN_AUTH + +Allows a system application to call the PIN input APIs to present a password input dialog box for users. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.GET_RUNNING_INFO + +Allows an application to obtain running status information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CLEAN_APPLICATION_DATA + +Allows an application to clear application data. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUNNING_STATE_OBSERVER + +Allows an application to observe the application status. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.CAPTURE_SCREEN + +Allows an application to take screenshots. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_INFO + +Allows an application to obtain WLAN information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_INFO_INTERNAL + +Allows an application to obtain WLAN information. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WIFI_INFO + +Allows an application to set WLAN devices. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_PEERS_MAC + +Allows an application to obtain the MAC address of the peer WLAN or Bluetooth device. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_LOCAL_MAC + +Allows an application to obtain the MAC address of the local WLAN or Bluetooth device. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_WIFI_CONFIG + +Allows an application to obtain the WLAN configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_WIFI_CONFIG + +Allows an application to set WLAN information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_WIFI_CONNECTION + +Allows an application to manage WLAN connections. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_WIFI_HOTSPOT + +Allows an application to enable or disable Wi-Fi hotspots. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_ALL_APP_ACCOUNTS + +Allows an application to obtain all application account information. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_SECURE_SETTINGS + +Allows an application to modify security settings. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_DFX_SYSEVENT + +Allows an application to access system event logging data. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +Allows an application to activate the device administrator app. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_ENTERPRISE_INFO + +Allows the device administrator application to set enterprise information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +Allows the device administrator application to subscribe to management events. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_SET_DATETIME + +Allows the device administrator application to set the system time. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENTERPRISE_GET_DEVICE_INFO + +Allows the device administrator application to obtain device information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NFC_TAG + +Allows an application to read NFC tag information. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.NFC_CARD_EMULATION + +Allows an application to implement card emulation. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.PERMISSION_USED_STATS + +Allows a system application to access the permission usage records. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +Allows an application to send agent-powered notifications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ANSWER_CALL + +Allows an application to answer incoming calls. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CALENDAR + +Allows an application to read calendar data. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CALL_LOG + +Allows an application to read call logs. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CELL_MESSAGES + +Allows an application to read cell broadcast messages received by the device. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_CONTACTS + +Allows an application to read contacts. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_MESSAGES + +Allows an application to read messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_MMS + +Allows an application to receive and process MMS messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_SMS + +Allows an application to receive and process SMS messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVE_WAP_MESSAGES + +Allows an application to receive and process WAP messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.MICROPHONE + +Allows an application to access the microphone. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.SEND_MESSAGES + +Allows an application to send messages. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CALENDAR + +Allows an application to add, remove, and modify calendar events. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CALL_LOG + +Allows an application to add, remove, and modify call logs. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_CONTACTS + +Allows an application to add, remove, and modify contacts. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISTRIBUTED_DATASYNC + +Allows an application to exchange data with other devices. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_VOICEMAIL + +Allows an application to leave messages in the voice mailbox. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.LOCATION_IN_BACKGROUND + +Allows an application running in the background to obtain the device location. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: FALSE + +## ohos.permission.LOCATION + +Allows an application to obtain the device location. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.APPROXIMATELY_LOCATION + +Allows an application to obtain the approximate location information of a device. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: FALSE + +## ohos.permission.MEDIA_LOCATION + +Allow an application to access geographical locations in the user's media file. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.CAMERA + +Allows an application to use the camera to take photos and record videos. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_MEDIA + +Allows an application to read media files from the user's external storage. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_MEDIA + +Allows an application to read media files from and write media files into the user's external storage. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACTIVITY_MOTION + +Allows an application to read the current workout status of the user. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_HEALTH_DATA + +Allows an application to read the health data of the user. + +**Permission level**: normal + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.GET_DEFAULT_APPLICATION + +Allows an application to query default applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.SET_DEFAULT_APPLICATION + +Allows an application to set and reset default applications. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_DISPOSED_APP_STATUS + +Allows an application to set and query the application handling state. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_IDS + +Allows an application to query the unique identifier of a device. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DUMP + +Allows the basic system information and SA service information to be exported. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.DISTRIBUTED_SOFTBUS_CENTER + +Allows networking between different devices. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_DLP_FILE + +Allows configuration and management of the permissions on .dlp files. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PROVISIONING_MESSAGE + +Allows the Super Device Manager application to be activated. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_SYSTEM_SETTINGS + +Allows an application to access or start system **Settings**. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_IMAGEVIDEO + +Allows access to the images or video files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_AUDIO + +Allows access to the audio files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.READ_DOCUMENT + +Allows access to the files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_IMAGEVIDEO + +Allows modification to the images or video files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_AUDIO + +Audio modification to the audio files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_DOCUMENT + +Allows modification to the files in a user's directory. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ABILITY_BACKGROUND_COMMUNICATION + +Allows an application to start the Ability component in the background and establish a connection with it. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.securityguard.REPORT_SECURITY_INFO + +Allows an application to report risk data for security guard. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.securityguard.REQUEST_SECURITY_MODEL_RESULT + +Allows an application to obtain the device risk status. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO + +Allows an application to obtain detailed risk data. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.READ_ACCESSIBILITY_CONFIG + +Allows an application to read the accessibility configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.WRITE_ACCESSIBILITY_CONFIG + +Allows an application to set the accessibility configuration. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_CERT_MANAGER_INTERNAL + +Allows an application to install, uninstall, enable, and disable certificates and credentials. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_CERT_MANAGER + +Allows an application to manage private credentials and query certificate status. + +**Permission level**: normal + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.ACCESS_PUSH_SERVICE + +Allows an application to to access the Ability of the push service. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RECEIVER_STARTUP_COMPLETED + +Allows an application to subscribe to the startup broadcast. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MANAGE_CAMERA_CONFIG + +Allows an application to enable or disable cameras globally. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.READ_WHOLE_CALENDAR + +Allows an application to read all calendar information. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.WRITE_WHOLE_CALENDAR + +Allows an application to add, remove, or change all calendar events. + +**Permission level**: system_basic + +**Authorization mode**: user_grant + +**Enable ACL**: TRUE + +## ohos.permission.ENFORCE_USER_IAM + +Allows an SA to delete user information from the IAM subsystem without a token. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_AUTH_RESPOOL + +Allows an SA to register the executor. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MOUNT_UNMOUNT_MANAGER + +Allows an application to mount and unmount external cards. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.MOUNT_FORMAT_MANAGER + +Allows an application to format external cards. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE + +## ohos.permission.STORAGE_MANAGER + +Allows an application to call the interfaces of the Storage Manager service to query space statistics and volume information. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.BACKUP + +Allows an application to have backup and restore capabilities. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.FILE_ACCESS_MANAGER + +Allows a file management application to access user data files through the FAF. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.MANAGE_AUDIO_CONFIG + +Allows an application to to mute microphones globally. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.ACCESS_SERVICE_DM + +Allows a system application to obtain the authentication and networking capability of distributed devices. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.RUN_ANY_CODE + +Allows an application to run unsigned code. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE + +## ohos.permission.PUBLISH_SYSTEM_COMMON_EVENT + +Allows an application to publish system common events. + +**Permission level**: system_basic + +**Authorization mode**: system_grant + +**Enable ACL**: TRUE diff --git a/en/application-dev/security/userauth-guidelines.md b/en/application-dev/security/userauth-guidelines.md index 85a82669d954947eea30a5e0cd82cc036f84b018..2902e73fe80c57942023674bb174cac384a218e2 100644 --- a/en/application-dev/security/userauth-guidelines.md +++ b/en/application-dev/security/userauth-guidelines.md @@ -1,113 +1,239 @@ # User Authentication Development > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
-> This development guide applies to the SDK of API Version 8 or later. +> This guide applies to the SDK for API version 9. ## When to Use -2D and 3D facial recognition used in identity authentication scenarios such as device unlocking, application login, and payment +User authentication supports facial recognition and fingerprint recognition and can be used in identity authentication scenarios such as device unlocking, application login, and payment. ## Available APIs -The userIAM_userAuth module provides methods for checking the support for user authentication, and performing and canceling authentication. You can perform authentication based on biometric features such as facial characteristics. For more details, see [API Reference](../reference/apis/js-apis-useriam-userauth.md). +The **userIAM_userAuth** module provides APIs for user authentication, including querying authentication capabilities, and initiating or canceling authentication. Users can use biometric feature information, such as facial and fingerprints, to perform authentications. For more details about the APIs, see [User Authentication](../reference/apis/js-apis-useriam-userauth.md). -Before performing authentication, check whether the device supports user authentication, including the authentication type and level. If user authentication is not supported, consider using another authentication type. The following table lists the APIs available for user authentication. +Before authentication, you must specify the [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8) and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to check whether the device supports the authentication capabilities. **Table 1** APIs of user authentication -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| getVersion() : number | Obtains the version information of an authentication object. | -| getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number | Checks whether the device supports the specified authentication type and level.| -| auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array | Performs user authentication. This method uses asynchronous callback to return the result. | -| cancelAuth(contextID : Uint8Array) : number | Cancels an authentication. | - -## How to Develop - -Before starting the development, make the following preparations: - -1. Add the ohos.permission.ACCESS_BIOMETRIC permission declaration to the application permission file. -2. Add **import userIAM_userAuth from '@ohos.userIAM.userAuth'** to the code file. - -The development procedure is as follows: - -1. Obtain an **Authenticator** singleton object. The sample code is as follows: - - ```js - let auth = new userIAM_userAuth.UserAuth(); - ``` - -2. (Optional) Obtain the version information of the authenticated object. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - let version = auth.getVersion(); - console.info("auth version = " + version); - ``` - -3. Check whether the device supports the authentication capabilities based on the specified authentication type and level. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - ``` - -4. Perform an authentication. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` - -5. Cancel the authentication. - - ```js - let auth = new userIAM_userAuth.UserAuth(); - // Obtain contextId using auth(). - let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - console.info("auth onResult result = " + result); - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - console.info("auth onAcquireInfo module = " + module); - } - }); - let cancelCode = auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` +| API | Description | +| ---------- | ----------------------- | +| getVersion() : number | Obtains the version information of an authentication object. | +| getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void | Checks whether the device supports the specified authentication type and level.| +| getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel : AuthTrustLevel): AuthInstance | Obtains an **AuthInstance** instance for user authentication.| +| on(name : AuthEventKey, callback : AuthEvent) : void | Subscribes to the user authentication events of the specified type.| +| off(name : AuthEventKey) : void | Unsubscribes from the user authentication events of the specific type.| +| start: void | Starts user authentication. | +| cancel: void | Cancel this user authentication. | + +## Obtaining Authentication Object Version Information + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Use [getVersion](../reference/apis/js-apis-useriam-userauth.md#useriam_userauthgetversion9) to obtain the version information. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + // Obtain version information. + try { + let version = userIAM_userAuth.getVersion(); + console.info("auth version = " + version); + } catch (error) { + console.info("get version failed, error = " + error); + } + ``` + +## Checking Authentication Capabilities Supported by a Device + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8) and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8), and call [getAvailableStatus](../reference/apis/js-apis-useriam-userauth.md#useriam_userauthgetavailablestatus9) to check whether the current device supports the authentication capabilities. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + // Check whether the authentication capabilities are supported. + try { + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info("current auth trust level is supported"); + } catch (error) { + console.info("current auth trust level is not supported, error = " + error); + } + ``` + +## Performing Authentication and Subscribing to the Authentication Result + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the challenge, [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8), and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to obtain an authentication object. + +3. Use [on](../reference/apis/js-apis-useriam-userauth.md#on9) to subscribe to the authentication result. + +4. Use [start](../reference/apis/js-apis-useriam-userauth.md#start9) to initiate an authentication and return the authentication result through [callback](../reference/apis/js-apis-useriam-userauth.md#callback9). + +5. Use [off](../reference/apis/js-apis-useriam-userauth.md#off9) to unsubscribe from the authentication result. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + let authType = userIAM_userAuth.UserAuthType.FACE; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Subscribe to the authentication result. + try { + auth.on("result", { + callback: (result: userIAM_userAuth.AuthResultInfo) => { + console.log("authV9 result " + result.result); + console.log("authV9 token " + result.token); + console.log("authV9 remainAttempts " + result.remainAttempts); + console.log("authV9 lockoutDuration " + result.lockoutDuration); + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + + // Unsubscribe from the authentication result. + try { + auth.off("result"); + console.info("cancel subscribe authentication event success"); + } catch (error) { + console.info("cancel subscribe authentication event failed, error = " + error); + } + ``` + +## Performing Authentication and Subscribing to Authentication Tip Information + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the challenge, [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8), and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to obtain an authentication object. + +3. Use [on](../reference/apis/js-apis-useriam-userauth.md#on9) to subscribe to the authentication tip information. + +4. Use [start](../reference/apis/js-apis-useriam-userauth.md#start9) to initiate an authentication and return the tip information through [callback](../reference/apis/js-apis-useriam-userauth.md#callback9). + +5. Use [off](../reference/apis/js-apis-useriam-userauth.md#off9) to unsubscribe from the authentication tip information. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + let authType = userIAM_userAuth.UserAuthType.FACE; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Subscribe to authentication tip information. + try { + auth.on("tip", { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // Do something. + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // Do something. + default: + // Do others. + } + } + }); + console.log("subscribe authentication event success"); + } catch (error) { + console.log("subscribe authentication event failed " + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + + // Unsubscribe from authentication tip information. + try { + auth.off("tip"); + console.info("cancel subscribe tip information success"); + } catch (error) { + console.info("cancel subscribe tip information failed, error = " + error); + } + ``` + +## Canceling User Authentication + +### How to Develop + +1. Apply for the permission.
Configure the **ohos.permission.ACCESS_BIOMETRIC** permission in **requestPermissions** in the **module.json5** file. For more information, see [module.json5](../quick-start/module-configuration-file.md). + +2. Specify the challenge, [authentication type](../reference/apis/js-apis-useriam-userauth.md#userauthtype8), and [authentication trust level](../reference/apis/js-apis-useriam-userauth.md#authtrustlevel8) to obtain an authentication object. + +3. Use [start](../reference/apis/js-apis-useriam-userauth.md#start9) to initiate an authentication. + +4. Use [cancel](../reference/apis/js-apis-useriam-userauth.md#cancel9) to cancel this authentication. + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); + let authType = userIAM_userAuth.UserAuthType.FACE; + let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); + } catch (error) { + console.log("get auth instance failed" + error); + } + + // Start user authentication. + try { + auth.start(); + console.info("authV9 start auth success"); + } catch (error) { + console.info("authV9 start auth failed, error = " + error); + } + + // Cancel the authentication. + try { + auth.cancel(); + console.info("cancel auth success"); + } catch (error) { + console.info("cancel auth failed, error = " + error); + } + ``` diff --git a/en/application-dev/security/userauth-overview.md b/en/application-dev/security/userauth-overview.md index f3e6a9a9042ad36f0111f3679f0084be4c6fc352..d7082741a06601e4b8009fd2f4388c4c64446643 100644 --- a/en/application-dev/security/userauth-overview.md +++ b/en/application-dev/security/userauth-overview.md @@ -16,7 +16,7 @@ Facial recognition establishes a secure channel between a camera and a trusted e Facial characteristics are stored in the TEE, which uses strong cryptographic algorithms to encrypt and protect the integrity of facial characteristics. The collected and stored facial characteristics will not be transferred out of the TEE without user authorization. This ensures that system or third-party applications cannot obtain facial characteristics, or send or back them up to any external storage medium. -## Limitations and Constraints +## Constraints - OpenHarmony only supports facial recognition and local authentication, and does not support an authentication UI. - To use biometric recognition, a device must have a camera with a face image pixel greater than 100x100. diff --git a/en/application-dev/task-management/Readme-EN.md b/en/application-dev/task-management/Readme-EN.md index efc153e1b229c56a83c630a98aee1cecf5c72cac..8f5c8d904521a8188079239092ffd5b88a58b955 100644 --- a/en/application-dev/task-management/Readme-EN.md +++ b/en/application-dev/task-management/Readme-EN.md @@ -5,9 +5,9 @@ - [Transient Task Development](transient-task-dev-guide.md) - [Continuous Task Development](continuous-task-dev-guide.md) - [Work Scheduler Development](work-scheduler-dev-guide.md) + - [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md) - [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md) - Agent-Powered Scheduled Reminder - - [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md) - - [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md) - + - [Agent-Powered Reminder Overview](reminder-agent-overview.md) + - [Agent-Powered Reminder Development](reminder-agent-development.md) \ No newline at end of file diff --git a/en/application-dev/task-management/background-agent-scheduled-reminder-guide.md b/en/application-dev/task-management/background-agent-scheduled-reminder-guide.md deleted file mode 100644 index ed220944dd102466ec190ca09d6066a8818acd3e..0000000000000000000000000000000000000000 --- a/en/application-dev/task-management/background-agent-scheduled-reminder-guide.md +++ /dev/null @@ -1,180 +0,0 @@ -# Agent-Powered Scheduled Reminder Development - -## When to Use - -You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits. - - -## Available APIs - -**reminderAgentManager** encapsulates the APIs for publishing and canceling reminders. - -For details about the APIs, see [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md). - -**Table 1** Major APIs in reminderAgentManager - -| Name| Description| -| -------- | -------- | -| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | -| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| -| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application.| -| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application.| -| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder.| -| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type.| - -## How to Develop - -> **NOTE** -> -> 1. To publish a reminder through the reminder agent, your application must apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. ->2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). -> 3. The reminder agent can be used only after being authorized by the user. - -1. Define a reminder agent. - -2. Publish the reminder agent. - -```ts -import reminderAgentManager from '@ohos.reminderAgentManager'; -import notification from '@ohos.notification'; - -// Sample code for defining a reminder agent for a countdown timer: -let timer : reminderAgentManager.ReminderRequestTimer = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 10, - actionButton: [ - { - title: "close", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - } - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} - -// Sample code for defining a reminder agent for a calendar event: -let calendar : reminderAgentManager.ReminderRequestCalendar = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, - dateTime: { - year: 2050, - month: 7, - day: 30, - hour: 11, - minute: 14, - second: 30 - }, - repeatMonths: [1], - repeatDays: [1], - actionButton: [ - { - title: "close", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} - -// Sample code for defining a reminder agent for an alarm: -let alarm : reminderAgentManager.ReminderRequestAlarm = { - reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, - hour: 11, - minute: 14, - daysOfWeek: [0], - actionButton: [ - { - title: "close", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} - -@Entry -@Component -struct Index { - @State message: string = 'test' - - publishReminder() { - try { - reminderAgentManager.publishReminder(timer).then(res => { - console.log("publishReminder promise reminderId:" + res); - }).catch(err => { - console.log("publishReminder err code:" + err.code + " message:" + err.message); - }) - } catch (error) { - console.log("publishReminder code:" + error.code + " message:" + error.message); - }; - } - - build() { - Row() { - Column() { - Text("Index") - .fontSize(50) - .fontWeight(FontWeight.Bold) - - Button() { Text('Countdown reminder agent').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40) - .onClick(() => { - // Sample code for publishing the reminder agent. - this.publishReminder(); - }) - - } - .width('100%') - } - .height('100%') - } -} -``` diff --git a/en/application-dev/task-management/background-agent-scheduled-reminder-overview.md b/en/application-dev/task-management/background-agent-scheduled-reminder-overview.md deleted file mode 100644 index 22c530571ad2770a279b9c94df998b6d773a5f1f..0000000000000000000000000000000000000000 --- a/en/application-dev/task-management/background-agent-scheduled-reminder-overview.md +++ /dev/null @@ -1,12 +0,0 @@ -# Agent-Powered Scheduled Reminder Overview - -According to the OpenHarmony background activity specifications, a third-party application will be suspended if it does not execute background tasks after switching to the background. In practice, an application may need to process certain work at specified moments, no matter what state it is in. For example, a shopping application needs to remind users of flash sale activities at some time points. Generally, a timer is used to achieve the preceding scenario. When the timer expires, the system starts the application to execute the task. However, some applications abuse the timer mechanism so they can be frequently waken up when running in the background. To avoid malicious background activities and meet service requirements of applications, OpenHarmony introduces the agent-powered scheduled reminder. -With the agent-powered scheduled reminder, the timing and pop-up notification functions of an application will be taken over by the reminder agent in the background, even when the application is suspended or exits. This prevents an application from being frequently woken up and helps reduce power consumption. - -## Notification Instance Types - -- **Countdown timers**: Applications can use this type to implement short-time timing notification services. - -- **Calendar events**: Applications can use this type to implement long-time notification services. - -- **Alarm clocks**: Applications can use this type to implement alarm-related services. diff --git a/en/application-dev/task-management/background-task-overview.md b/en/application-dev/task-management/background-task-overview.md index 201c666ad7cc65b1ab2ef865070562fa6b433bab..dc7e7e3eda37f3fe62e70114a1804cfa0bffdc65 100644 --- a/en/application-dev/task-management/background-task-overview.md +++ b/en/application-dev/task-management/background-task-overview.md @@ -1,26 +1,26 @@ # Background Task Management Overview Frequent activities of background applications cause user devices to consume power quickly and respond slowly. To meet performance and power consumption requirements, the system allows applications in the background to execute only activities within the specifications. Activities beyond the specifications are suspended by default, and resources allocated to them will be reclaimed when the available resources are insufficient. -If an application or a service module running in the background has a service to continue, it can request a [transient task](#transient-tasks) to delay the suspension or a [continuous task](#continuous-tasks) to prevent the suspension. If an application needs to execute a non-real-time task when running in the background, it can request a [Work Scheduler Task](#work-scheduler-tasks). A privileged application can also request [efficiency resources](#efficiency-resources) for more flexibility. +If an application or a service module running in the background has a service to continue, it can request a [transient task](#transient-tasks) to delay the suspension or a [continuous task](#continuous-tasks) to prevent the suspension. If an application needs to execute a non-real-time task when running in the background, it can request a [Work Scheduler task](#work-scheduler-tasks). A privileged application can also request [efficiency resources](#efficiency-resources) for more flexibility. ## Background Task Types For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode: -**No background task**: An application or service module does not need further processing when switched to the background. +- **No background task**: An application or service module does not need further processing when switched to the background. -**Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension. +- **Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension. -**Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP. +- **Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP. -**Work Scheduler task**: The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle. +- **Work Scheduler task**: The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle. -**Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including CPU, WORK_SCHEDULER, software, and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended. +- **Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including CPU, WORK_SCHEDULER, software, and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended. ## Selecting a Background Task -![Background Task Selection](public_sys-resources/bgtask_choice.png) +![Background Task Selection](figures/bgtask_choice.png) ## Transient Tasks @@ -51,17 +51,17 @@ OpenHarmony provides 9 background modes for services that require continuous tas **Table 1** Background modes for continuous tasks -| Background Mode| Description| Hint in Notification Panel| Remarks| -| -------- | -------- | -------- | -------- | -| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running.| - | -| audioPlayback | Audio output| An audio playback task is running.| - | -| audioRecording | Audio input| A recording task is running.| - | -| location | Positioning and navigation| A positioning task is running.| - | -| bluetoothInteraction | Bluetooth transmission| A Bluetooth-related task is running.| - | -| multiDeviceConnection | Distributed interconnection| A distributed task is running.| - | -| wifiInteraction | WLAN transmission| A WLAN-related task is running.| System API, which is available only to system applications| -| voip | Voice and video calls over VoIP| A call-related task is running.| System API, which is available only to system applications| -| taskKeeping | Computing task| A computing task is running| Effective only for specific devices| +| Background Mode | Description | Hint in Notification Panel | Remarks | +| --------------------- | ------------------------- | ------------ | ------------------------- | +| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running. | - | +| audioPlayback | Audio output | An audio playback task is running. | - | +| audioRecording | Audio input | A recording task is running. | - | +| location | Positioning and navigation | A positioning task is running. | - | +| bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - | +| multiDeviceConnection | Distributed interconnection | A distributed task is running. | - | +| wifiInteraction | WLAN transmission | A WLAN-related task is running.| System API, which is available only to system applications| +| voip | Voice and video calls over VoIP | A call-related task is running. | System API, which is available only to system applications| +| taskKeeping | Computing task | A computing task is running | Effective only for specific devices | ### Restrictions on Using Continuous Tasks - If a user triggers a perceivable task, such as broadcasting and navigation, the corresponding background mode is triggered. When the task is started, the system forcibly displays a notification to the user. @@ -80,15 +80,15 @@ The use of the Work Scheduler must comply with the following restrictions and ru - **Timeout**: The Work Scheduler callback can run only within the specified period of time. After the timeout, the callback automatically stops. The default timeout duration is 2 minutes. System applications can request [efficiency resources](efficiency-resources-apply-dev-guide.md) to obtain a longer duration (20 minutes in the charging state and 10 minutes in the non-charging state). - **Execution frequency**: The system controls the execution frequency of Work Scheduler tasks based on the activity level of their respective applications. If an application has applied for the WORK_SCHEDULER resources through the efficiency resource API, the execution frequency is not limited within the validity period of the resources. - | Application Group | Work Scheduler Task Execution Frequency | - | --------------------|------------------------- | - | Active| At a minimum interval of 2 hours| - | Used every day| At a minimum interval of 4 hours| - | Frequently used| At a minimum interval of 24 hours| - | Infrequently used| At a minimum interval of 48 hours| - | Restricted| Prohibited| - | Unused| Prohibited| - | [Exemption group for efficiency resources](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | Unlimited| + | Application Group | Work Scheduler Task Execution Frequency| + | ---------------------------------------- | ---------- | + | Active | At a minimum interval of 2 hours | + | Used every day | At a minimum interval of 4 hours | + | Frequently used | At a minimum interval of 24 hours | + | Infrequently used | At a minimum interval of 48 hours | + | Restricted | Prohibited | + | Unused | Prohibited | + | [Exemption group for efficiency resources](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#resourcetype)| Unlimited | - **WorkInfo setting** @@ -110,25 +110,21 @@ An application or process is assigned the privileges associated with the obtaine * With the TIMER resources, the application can use the timer to execute precise scheduled tasks. * With the hardware resources, the application can still be woken up by related services to execute tasks when it is suspended in the background. + **Table 2** Efficiency resource types -| Name | Value | Description | -| ----------------------- | ---- | --------------------- | -| CPU | 1 | CPU resources, which prevent the application from being suspended. | -| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. | -| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. | -| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | -| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | -| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | -| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| +| Name | Value | Description | +| -------------- | ---- | ------------------- | +| CPU | 1 | CPU resources, which prevent the application from being suspended. | +| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. | +| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. | +| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | +| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | +| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended.| +| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended. | ### Restrictions on Using Efficiency Resources - Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application. - - If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released. - - The WORK_SCHEDULER resources can be requested and released by applications, but not by processes. - - To use efficiency resources, an application must first submit a request to the application center to obtain corresponding privileges. - - diff --git a/en/application-dev/task-management/continuous-task-dev-guide.md b/en/application-dev/task-management/continuous-task-dev-guide.md index 5ec27a6e13200619e34ef88c0dd00e501b11cb20..b278a686e4267d7b62d123c2f6f2c338a9278ab7 100644 --- a/en/application-dev/task-management/continuous-task-dev-guide.md +++ b/en/application-dev/task-management/continuous-task-dev-guide.md @@ -3,7 +3,7 @@ ## When to Use If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP. -There is no time limit for a continuous task running in the background. To prevent abuse, the system limits the number of continuous tasks that can be requested. It also attaches a notification to the task so that the task is perceivable. In addition, the system verifies whether the application is actually executing the continuous task. +There is no time limit for a continuous task running in the background. To prevent abuse, the system limits the number of continuous tasks that can be requested. It also attaches a notification to each of the tasks so that the tasks are perceivable. In addition, the system verifies whether the application is actually executing a continuous task. ## Available APIs @@ -15,7 +15,7 @@ There is no time limit for a continuous task running in the background. To preve | stopBackgroundRunning(context: Context): Promise<void> | Cancels the continuous task. | -For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md). +For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). **Table 2** Background modes @@ -34,152 +34,9 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA ## How to Develop -### Development on the FA Model +### Development in the Stage Model -For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.md). - -If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources. - -If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks. - -1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**. - -``` -"module": { - "package": "com.example.myapplication", - "abilities": [ - { - "backgroundModes": [ - "dataTransfer", - "location" - ], // Background mode - "type": "service" // The ability type is service. - } - ], - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission - } - ] -} -``` - -2. Call the APIs for requesting and canceling a continuous task in the Service ability. - -```js -import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import featureAbility from '@ohos.ability.featureAbility'; -import wantAgent from '@ohos.wantAgent'; -import rpc from "@ohos.rpc"; - -function startContinuousTask() { - let wantAgentInfo = { - // List of operations to be executed after the notification is clicked. - wants: [ - { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" - } - ], - // Type of the operation to perform after the notification is clicked. - operationType: wantAgent.OperationType.START_ABILITY, - // Custom request code. - requestCode: 0, - // Execution attribute of the operation to perform after the notification is clicked. - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] - }; - - // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. - wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { - try { - backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { - console.info("Operation startBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation startBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } - }); -} - -function stopContinuousTask() { - try { - backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { - console.info("Operation stopBackgroundRunning succeeded"); - }).catch((err) => { - console.error("Operation stopBackgroundRunning failed Cause: " + err); - }); - } catch (error) { - console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); - } -} - -async function processAsyncJobs() { - // Execute the continuous task. - - // After the continuous task is complete, call the API to release resources. - stopContinuousTask(); -} - -let mMyStub; - -class MyStub extends rpc.RemoteObject { - constructor(des) { - if (typeof des === 'string') { - super(des); - } else { - return null; - } - } - onRemoteRequest(code, data, reply, option) { - console.log('ServiceAbility onRemoteRequest called'); - // The meaning of code is user-defined. - if (code === 1) { - // Receive the request code for requesting a continuous task. - startContinuousTask(); - // Execute the continuous task. - } else if (code === 2) { - // Receive the request code for canceling the continuous task. - stopContinuousTask(); - } else { - console.log('ServiceAbility unknown request code'); - } - return true; - } -} - -export default { - onStart(want) { - console.info('ServiceAbility onStart'); - mMyStub = new MyStub("ServiceAbility-test"); - // Call the API to start the task. - startContinuousTask(); - processAsyncJobs(); - }, - onStop() { - console.info('ServiceAbility onStop'); - }, - onConnect(want) { - console.info('ServiceAbility onConnect'); - return mMyStub; - }, - onReconnect(want) { - console.info('ServiceAbility onReconnect'); - }, - onDisconnect() { - console.info('ServiceAbility onDisconnect'); - }, - onCommand(want, restart, startId) { - console.info('ServiceAbility onCommand'); - } -}; -``` - -### Development on the Stage Model - -For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md). +For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md). 1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission (ohos.permission.KEEP_BACKGROUND_RUNNING) and background mode type in the **module.json5** file. @@ -201,10 +58,10 @@ For details about the stage model, see [Stage Model Overview](../ability/stage-b } ``` -2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details about how to use an ability in the stage model, see [Ability Development](../ability/stage-ability.md). +2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details, see [UIAbility Component Overview](../application-models/uiability-overview.md). ```ts -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; @Entry @@ -220,7 +77,7 @@ struct Index { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", } ], // Type of the operation to perform after the notification is clicked. @@ -290,14 +147,14 @@ struct Index { } ``` -3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Call Development](../ability/stage-call.md). +3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Using Ability Call (Intra-Device)](../application-models/uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-ability-call). ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -import wantAgent from '@ohos.wantAgent'; +import wantAgent from '@ohos.app.ability.wantAgent'; -const MSG_SEND_METHOD: string = 'CallSendMsg' +const MSG_SEND_METHOD: string = 'CallSendMsg'; let mContext = null; @@ -307,7 +164,7 @@ function startContinuousTask() { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + abilityName: "EntryAbility", } ], // Type of the operation to perform after the notification is clicked. @@ -381,7 +238,7 @@ function sendMsgCallback(data) { return new MySequenceable(10, "Callee test"); } -export default class BgTaskAbility extends Ability { +export default class BgTaskAbility extends UIAbility { onCreate(want, launchParam) { console.info("[Demo] BgTaskAbility onCreate") this.callee.on("test", sendMsgCallback); @@ -421,3 +278,146 @@ export default class BgTaskAbility extends Ability { } }; ``` + +### Development in the FA Model + +For details about how to use the ServiceAbility in the FA model, see [ServiceAbility Component Overview](../application-models/serviceability-overview.md). + +If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources. + +If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks. + +1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**. + +```json +"module": { + "package": "com.example.myapplication", + "abilities": [ + { + "backgroundModes": [ + "dataTransfer", + "location" + ], // Background mode + "type": "service" // The ability type is service. + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission + } + ] +} +``` + +2. Call the APIs for requesting and canceling a continuous task in the Service ability. + +```js +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.app.ability.wantAgent'; +import rpc from "@ohos.rpc"; + +function startContinuousTask() { + let wantAgentInfo = { + // List of operations to be executed after the notification is clicked. + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" + } + ], + // Type of the operation to perform after the notification is clicked. + operationType: wantAgent.OperationType.START_ABILITY, + // Custom request code. + requestCode: 0, + // Execution attribute of the operation to perform after the notification is clicked. + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + try { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } + }); +} + +function stopContinuousTask() { + try { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } catch (error) { + console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); + } +} + +async function processAsyncJobs() { + // Execute the continuous task. + + // After the continuous task is complete, call the API to release resources. + stopContinuousTask(); +} + +let mMyStub; + +class MyStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + onRemoteRequest(code, data, reply, option) { + console.log('ServiceAbility onRemoteRequest called'); + // The meaning of code is user-defined. + if (code === 1) { + // Receive the request code for requesting a continuous task. + startContinuousTask(); + // Execute the continuous task. + } else if (code === 2) { + // Receive the request code for canceling the continuous task. + stopContinuousTask(); + } else { + console.log('ServiceAbility unknown request code'); + } + return true; + } +} + +export default { + onStart(want) { + console.info('ServiceAbility onStart'); + mMyStub = new MyStub("ServiceAbility-test"); + // Call the API to start the task. + startContinuousTask(); + processAsyncJobs(); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return mMyStub; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, restart, startId) { + console.info('ServiceAbility onCommand'); + } +}; +``` diff --git a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md index 0b8ea31ca804f848d1e931b65a7e5f5812e656c2..61f1431ea4d26eb8579246b8ecec1f58fab56327 100644 --- a/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md +++ b/en/application-dev/task-management/efficiency-resources-apply-dev-guide.md @@ -1,22 +1,22 @@ -## Efficiency Resource Request Development +# Efficiency Resource Request Development -### When to Use +## When to Use To further balance power consumption overhead of the system, privileged system applications can be suspended in the background as other applications. To ensure normal provisioning of important functions, efficiency resource APIs are provided for these applications so that they can execute special tasks and use specific system resources in the background. For example, if they want to receive common events when suspended, they can use the APIs to request the common event resources. To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions. -### Available APIs +## Available APIs **Table 1** Main APIs for efficiency resources -| API | Description | -| ---------------------------------------- | ---------------------------------------- | -| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | Requests efficiency resources.| -| resetAllEfficiencyResources():void | Releases efficiency resources. | +| API | Description | +| ---------------------------------------- | ---------- | +| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#efficiencyresourcesrequest)): boolean | Requests efficiency resources. | +| resetAllEfficiencyResources():void | Releases efficiency resources.| -### How to Develop +## How to Develop 1. When a privileged application in the background needs to use special resources, request the target resources from the system. @@ -51,5 +51,3 @@ console.info("the result of request is: " + res); // Release all efficiency resources. backgroundTaskManager.resetAllEfficiencyResources(); ``` - - \ No newline at end of file diff --git a/en/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png b/en/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png new file mode 100644 index 0000000000000000000000000000000000000000..627a88f515e8a4ba1beb40e3242fd3521cb39494 Binary files /dev/null and b/en/application-dev/task-management/figures/WorkSchedulerExtensionAbility.png differ diff --git a/en/application-dev/task-management/public_sys-resources/bgtask_choice.png b/en/application-dev/task-management/figures/bgtask_choice.png similarity index 100% rename from en/application-dev/task-management/public_sys-resources/bgtask_choice.png rename to en/application-dev/task-management/figures/bgtask_choice.png diff --git a/en/application-dev/task-management/figures/en-us_image_0000001416585578.png b/en/application-dev/task-management/figures/en-us_image_0000001416585578.png new file mode 100644 index 0000000000000000000000000000000000000000..7603dfb263fe088c0a71a99be541838566b53268 Binary files /dev/null and b/en/application-dev/task-management/figures/en-us_image_0000001416585578.png differ diff --git a/en/application-dev/task-management/reminder-agent-development.md b/en/application-dev/task-management/reminder-agent-development.md new file mode 100644 index 0000000000000000000000000000000000000000..c9a23f6422aef7a2b2709b00d21b9c7e129496f4 --- /dev/null +++ b/en/application-dev/task-management/reminder-agent-development.md @@ -0,0 +1,177 @@ +# Agent-Powered Reminder Development + + +## Available APIs + +The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class. + + **Table 1** Major APIs in reminderAgentManager + +| API | Description | +| ---------------------------------------- | ---------------------------------------- | +| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application
and 2000 for the entire system.| +| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| +| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application. | +| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application. | +| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder. | +| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type. | + + +## How to Develop + +1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). + +2. [Enable the notification feature](../notification/notification-enable.md). + +3. Import the modules. + + ```js + import reminderAgentManager from '@ohos.reminderAgentManager'; + import notificationManager from '@ohos.notificationManager'; + ``` + +4. Define a reminder agent. You can define the following types of reminder agents based on project requirements. + - Countdown timer + + ```js + let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // The reminder type is countdown timer. + triggerTimeInSeconds: 10, + actionButton: [ // Set the button type and title displayed in the reminder notification. The Close and Snooze types are supported, and the Snooze type must be used together with the snoozeTimes and timeInterval parameters. + { + title: 'close', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + } + ], + wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + maxScreenWantAgent: {// Information about the target ability that is automatically started when the specified reminder time arrives is displayed in full screen. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + title: 'this is title', // Reminder title. + content: 'this is content', // Reminder content. + expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. + notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. + slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. + } + ``` + - Calendar event + + ```js + let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // The reminder type is calendar event. + dateTime: { // Reminder time. + year: 2023, + month: 7, + day: 30, + hour: 11, + minute: 14, + second: 30 + }, + repeatMonths: [1], // Month in which the reminder repeats. + repeatDays: [1], // Date on which the reminder repeats. + actionButton: [ // Set the button type and title displayed in the reminder notification. The Close and Snooze types are supported, and the Snooze type must be used together with the snoozeTimes and timeInterval parameters. + { + title: 'close', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: 'snooze', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + ringDuration: 5, // Ringing duration, in seconds. + snoozeTimes: 2, // Number of reminder snooze times. + timeInterval: 5, // Reminder snooze interval, in seconds. + title: 'this is title', // Reminder title. + content:'this is content', // Reminder content. + expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. + snoozeContent: 'remind later', // Content to be displayed when the reminder is snoozed. + notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. + slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. + } + ``` + - Alarm clock + + ```js + let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = { + reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // The reminder type is alarm clock. + hour: 23, // Hour portion of the reminder time. + minute: 9, // Minute portion of the reminder time. + daysOfWeek: [2], // Days of a week when the reminder repeats.. + actionButton: [ // Set the button type and title displayed in the reminder notification. The Close and Snooze types are supported, and the Snooze type must be used together with the snoozeTimes and timeInterval parameters. + { + title: 'close', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: 'snooze', + type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. + pkgName: 'com.example.myapplication', + abilityName: 'EntryAbility' + }, + ringDuration: 5, // Ringing duration, in seconds. + snoozeTimes: 2, // Number of reminder snooze times. + timeInterval: 5, // Reminder snooze interval, in seconds. + title: 'this is title', // Reminder title. + content: 'this is content', // Reminder content. + expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. + snoozeContent: 'remind later', // Content to be displayed when the reminder is snoozed. + notificationId: 99, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. + slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. + } + ``` + +5. Publish the reminder agent. After the agent is published, your application can use the agent-powered reminder feature. + + ```js + try { + reminderAgentManager.publishReminder(targetReminderAgent).then(res => { + console.info('publishReminder promise reminderId: ' + res); + let reminderId: number = res; + // ... + }).catch(err => { + console.info('publishReminder err code: ' + err.code + ' message:' + err.message); + }) + } catch (error) { + console.info('publishReminder code: ' + error.code + ' message:' + error.message); + } + ``` + + The following figure shows the running effect of an alarm clock. + + ![en-us_image_0000001416585578](figures/en-us_image_0000001416585578.png) + +6. To delete a reminder task, call [reminderAgentManager.cancelReminder()](../reference/apis/js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder). + + ```js + let reminderId = 0; // The reminderId is obtained from the callback after the agent is published. + + try { + reminderAgentManager.cancelReminder(reminderId).then(() => { + console.log("cancelReminder promise"); + }).catch(err => { + console.log("promise err code: " + err.code + ", message:" + err.message); + }); + } catch (error) { + console.log("cancelReminder code: " + error.code + ", message: " + error.message); + }; + ``` diff --git a/en/application-dev/task-management/reminder-agent-overview.md b/en/application-dev/task-management/reminder-agent-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6f0f4c5f99b60715e7c1a29841c9ca5aadf70cb8 --- /dev/null +++ b/en/application-dev/task-management/reminder-agent-overview.md @@ -0,0 +1,14 @@ +# Agent-Powered Reminder Overview + + +To deliver a better user experience, OpenHarmony manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. However, for some applications that are running in the background or have exited, notifications may need to be sent at a specified time. For example, a shopping application wants to remind users of flash sale activities at some time points. To meet these service requirements, OpenHarmony provides the agent-powered redminder feature. After an application switches to the background or exits, their timing and pop-up notification functions are taken over by the background agent. + + +OpenHarmony provides the following types of background agents: + + +- Countdown timers: Applications can use this type to implement short-time timing notification services. + +- Calendar events: Applications can use this type to implement long-time notification services. + +- Alarm clocks: Applications can use this type to implement alarm-related services. diff --git a/en/application-dev/task-management/transient-task-dev-guide.md b/en/application-dev/task-management/transient-task-dev-guide.md index b1e815fc68a485cb88f24b2c18b64f2658133196..a83ba2094138e2271f55758484f483a9a7ddbaed 100644 --- a/en/application-dev/task-management/transient-task-dev-guide.md +++ b/en/application-dev/task-management/transient-task-dev-guide.md @@ -2,12 +2,11 @@ ## When to Use -By default, an application can run for 6 to 12 seconds after it switches to the background but before being suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to delay the suspension. +By default, an application can run for a period of 6 to 12 seconds after it switches to the background. When this period expires, the application is suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to request a transient task to delay the suspension. -It is recommended that an application calls the **requestSuspendDelay** API before executing any time-consuming task, rather than when it is already running in the background. -The calling of the **requestSuspendDelay** API when the application is running in the foreground does not affect the transient task quota of the application. +You are advised not to call the [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) method to apply for delayed suspension after the application is running in the background. Instead, you need to call this interface to declare the execution time of the extended application to the system before performing any time-consuming operation. It is recommended that an application calls [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) when it is running in the foreground, so as not to affect the transient task quota of the application. -Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should cancel the transient task in a timely manner. +An application can obtain the remaining duration before being suspended by calling [getRemainingDelayTime()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagergetremainingdelaytimecallback). Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should call [cancelSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagercancelsuspenddelay) to cancel the transient task in a timely manner. Typical time-consuming tasks include saving status data to the local database, opening and processing a large file, and synchronizing data to the cloud server. @@ -19,67 +18,74 @@ Typical time-consuming tasks include saving status data to the local database, o | API | Description | | ---------------------------------------- | ---------------------------------------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.
The default duration value of delayed suspension is 3 minutes when the battery level is normal and 1 minute when the battery level is low.| +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo)| Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 3 minutes when the battery level is normal and 1 minute when the battery level is low.| | getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.
This API uses a promise to return the result. | | cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. | ## How to Develop -1. When an application needs to execute a time-consuming task, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task. +When an application needs to execute a time-consuming task in the background, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task. ```js -import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -let delayInfo; -let id; +let id; // ID of the suspension delay request. +let delayTime; // Remaining duration for the suspension delay request. // Request a suspension delay. function requestSuspendDelay() { - let myReason = 'test requestSuspendDelay'; - delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); - // The callback in invoked to notify the application that the suspension delay request is about to time out. The application needs to perform some cleanup and annotation operations. - }); - + let myReason = 'test requestSuspendDelay'; // Reason for the suspension delay request. + + try { + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + // The callback is invoked to notify the application that the suspension delay request is about to time out. The application needs to perform some cleanup and annotation operations and cancels the transient task. + console.info("[backgroundTaskManager] Request suspension delay will time out."); + backgroundTaskManager.cancelSuspendDelay(id); + }) id = delayInfo.requestId; - console.info("requestId is: " + id); + delayTime = delayInfo.actualDelayTime; + console.info("[backgroundTaskManager] The requestId is: " + id); + console.info("[backgroundTaskManager]The actualDelayTime is: " + delayTime); + } catch (error) { + console.error(`[backgroundTaskManager] requestSuspendDelay failed. code is ${error.code} message is ${error.message}`); + } } // Obtain the remaining duration before the application is suspended. -function getRemainingDelayTime() { - let delayTime = 0; - backgroundTaskManager.getRemainingDelayTime(id).then((res) => { - console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); - delayTime = res; - }).catch((err) => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); - }); - return delayTime; +async function getRemainingDelayTime() { + try { + await backgroundTaskManager.getRemainingDelayTime(id).then(res => { + console.log('[backgroundTaskManager] promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); + }).catch(error => { + console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); + }) + } catch (error) { + console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`); + } } // Cancel the suspension delay. function cancelSuspendDelay() { - backgroundTaskManager.cancelSuspendDelay(id); + backgroundTaskManager.cancelSuspendDelay(id); } -function performingLongRunningTask() { - // Before executing the time-consuming task, call the API to request a transient task to delay the suspension. - requestSuspendDelay(); - - // Obtain the available time quota through the getRemainingDelayTime() API. - let delayTime = getRemainingDelayTime(); +async function performingLongRunningTask() { + // Before executing a time-consuming task, call the API to request a transient task to delay the suspension. + requestSuspendDelay(); - if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming operation. - // Handle the scenario where the time quota is insufficient. + // If required, obtain the available time quota through the getRemainingDelayTime() API. + await getRemainingDelayTime(); - cancelSuspendDelay(); - return; - } + if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming task. + // Handle the scenario where the time quota is insufficient. + cancelSuspendDelay(); + return; + } - // Execute the time-consuming task. + // Execute the time-consuming task. - // After the time-consuming task is executed, call the API to cancel the transient task. - cancelSuspendDelay(); + // After the time-consuming task is executed, call the API to cancel the transient task. + cancelSuspendDelay(); } ``` diff --git a/en/application-dev/task-management/work-scheduler-dev-guide.md b/en/application-dev/task-management/work-scheduler-dev-guide.md index 6ab36ea5da66af894ddec3c21aba7eb7cc37e926..845423ee6fa93a39d5ac93cbd8856f0ec0e49c23 100644 --- a/en/application-dev/task-management/work-scheduler-dev-guide.md +++ b/en/application-dev/task-management/work-scheduler-dev-guide.md @@ -2,7 +2,7 @@ ## When to Use -If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler). +If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler). ## Available APIs @@ -14,21 +14,21 @@ startWork(work: WorkInfo): void; | Starts a Work Scheduler task. stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a Work Scheduler task. getWorkStatus(workId: number, callback: AsyncCallback\): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result. getWorkStatus(workId: number): Promise\; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result. -obtainAllWorks(callback: AsyncCallback\): Array\;| Obtains Work Scheduler tasks. This API uses an asynchronous callback to return the result. -obtainAllWorks(): Promise>;| Obtains Work Scheduler tasks. This API uses a promise to return the result. -stopAndClearWorks(): void;| Stops and clears Work Scheduler tasks. +obtainAllWorks(callback: AsyncCallback\): Array\;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result. +obtainAllWorks(): Promise>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result. +stopAndClearWorks(): void;| Stops and clears all the Work Scheduler tasks. isLastWorkTimeOut(workId: number, callback: AsyncCallback\): boolean;| Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks. isLastWorkTimeOut(workId: number): Promise\;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks. **Table 2** WorkInfo parameters -For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler). +For details about the restriction on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler). Name| Type|Description ---------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- -workId| number | Work ID. Mandatory. -bundleName| string | Name of the Work Scheduler task bundle. Mandatory. -abilityName| string | Name of the component to be notified by a Work Scheduler callback. Mandatory. +workId| number | ID of the Work Scheduler task. Mandatory. +bundleName| string | Bundle name of the Work Scheduler task. Mandatory. +abilityName| string | Name of the ability to be notified by a Work Scheduler callback. Mandatory. networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type. isCharging| boolean | Whether the device is charging. chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type. @@ -42,26 +42,27 @@ parameters | {[key: string]: any} |Carried parameters. **Table 3** Work Scheduler callbacks -Name | Description +API | Description ---------------------------------------------------------|----------------------------------------- -onWorkStart(work: WorkInfo): void | Triggered when the Work Scheduler task starts. -onWorkStop(work: WorkInfo): void | Triggered when the Work Scheduler task stops. +onWorkStart(work: WorkInfo): void | Called when the Work Scheduler task starts. +onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops. ### How to Develop 1. Import the modules. - Import the **workScheduler** package to implement registration: -```js -import workScheduler from '@ohos.resourceschedule.workScheduler'; -``` + Import the **workScheduler** module. + + ```js + import workScheduler from '@ohos.resourceschedule.workScheduler'; + ``` - Import the **WorkSchedulerExtensionAbility** package to implement callback: -```js -import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; -``` + Import the **WorkSchedulerExtensionAbility** module. + ```js + import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; + ``` -2. Develop an Extension ability to execute a Work Scheduler task. For details about the Extension ability, see [ExtensionAbility Mechanism](../ability/stage-brief.md#extensionability-mechanism). +2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md). ```ts import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; @@ -77,7 +78,7 @@ export default class MyExtension extends WorkSchedulerExtensionAbility { ``` -3. Register a Work Scheduler task. +3. Start a Work Scheduler task. ```ts import workScheduler from '@ohos.resourceschedule.workScheduler'; @@ -105,7 +106,7 @@ try{ ``` -4. Cancel the Work Scheduler task. +4. Stop the Work Scheduler task. ```ts import workScheduler from '@ohos.resourceschedule.workScheduler'; @@ -152,7 +153,7 @@ try{ ``` -6. Obtain all Work Scheduler tasks. +6. Obtain all the Work Scheduler tasks. ```ts try{ @@ -168,7 +169,7 @@ try{ } ``` -7. Stop and clear Work Scheduler tasks. +7. Stop and clear all the Work Scheduler tasks. ```ts try{ @@ -179,7 +180,7 @@ try{ } ``` -8. Check whether the last execution has timed out. +8. Check whether the last execution of a specified Work Scheduler task has timed out. ```ts try{ diff --git a/en/application-dev/task-management/workscheduler-extensionability.md b/en/application-dev/task-management/workscheduler-extensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..b2df1601a6608c6bb3c4dd10ce257a2c02284bc6 --- /dev/null +++ b/en/application-dev/task-management/workscheduler-extensionability.md @@ -0,0 +1,196 @@ +# WorkSchedulerExtensionAbility Development + +If your application needs to execute a non-real-time task or a persistent task, you can harness the Work Scheduler mechanism, which will schedule the task when the preset conditions (including the network type, charging type, storage status, battery status, and timing status) are met. + +**WorkSchedulerExtensionAbility** provides callbacks for Work Scheduler tasks. When a Work Scheduler task starts or stops, these callbacks are invoked to process your service logic. + +## Working Principles + +Figure 1 shows the working principle of Work Scheduler. + +**Figure 1** Work Scheduler working principle + +![WorkSchedulerExtensionAbility](figures/WorkSchedulerExtensionAbility.png) + +An application starts, stops, and obtains Work Scheduler tasks through the [workScheduler APIs](../reference/apis/js-apis-resourceschedule-workScheduler.md). + +The application service layer detects and determines the conditions. If the preset conditions are met, the application service layer calls back the **WorkSchedulerExtensionAbility** object to start the application and triggers the **onWorkStart** and **onWorkStop** callbacks. + +## Available APIs + +The **WorkSchedulerExtensionAbility** class has the following APIs. For details, see [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md). + +| Name| Description| +| -------- | -------- | +| onWorkStart(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task starts.| +| onWorkStop(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task stops.| + +## How to Develop + +To create a WorkScheduler project in DevEco Studio, perform the following steps: + +- [Implement callbacks for Work Scheduler](#implementing-callbacks-for-work-scheduler): Develop the callbacks provided by **WorkSchedulerExtensionAbility**. + +- [Implement Work Scheduler](#implementing-work-scheduler): Develop the [workScheduler APIs] to implement functions such as starting or stopping Work Scheduler tasks. + +- [Set the configuration file](#setting-the-configuration-file): Set the configuration file **module.json5**. + +### Implementing Callbacks for Work Scheduler + +1. Create a module named **library** in the root directory of the project, with the **Ohos Library** template selected. + +2. In the **./library/src/main/ets** directory under **library**, create an ArkTS file named **workAbility.ets** and implement the callbacks for Work Scheduler. + + Import the module. + + ```ts + import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' + ``` + + Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility. + + ```ts + export default class workAbility extends WorkSchedulerExtensionAbility { + // Callback invoked when the Work Scheduler task starts. + onWorkStart(workInfo) { + console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`) + // Publish an upgrade notification. + let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '') + notification.publish(notificationRequest, (err) => { + if (err) { + console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`) + } + console.log(`onWorkStart notification publish success`) + }) + } + + // Callback invoked when the Work Scheduler task stops. + onWorkStop(workInfo) { + // Publish an upgrade completion notification. + let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '') + notification.publish(notificationRequest, (err) => { + if (err) { + console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`) + } + console.log(`onWorkStop notification publish success`) + }) + } + } + ``` + +3. In the **./entry/src/main/ets** directory under the **entry** module of the project, create a directory named **workAbility**. In the **workAbility** directory, create an ArkTS file named **WorkTest.ets** and implement the callbacks for Work Scheduler. + +Import the module. + + ```ts + import { workAbility } from '@ohos/library' + ``` + +Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility. + + ```ts + export default class WorkTest extends workAbility { + onWorkStart(workInfo) { + console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`) + super.onWorkStart(workInfo) + } + + onWorkStopTest(workInfo) { + super.onWorkStop(workInfo) + console.log(`onWorkStop value`) + } + } + ``` + +### Implementing Work Scheduler + +1. In the **./library/src/main/ets** directory under **library**, create a TypeScript file named **DelayWork.ts**, and implement the Work Scheduler APIs. + + Import the module. + + ```ts + import workScheduler from '@ohos.resourceschedule.workScheduler' + ``` + + Encapsulate the APIs for starting and stopping Work Scheduler tasks. + + ```ts + export default class DelayWork { + private workInfo = { + workId: 1, + networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI, + bundleName: '', + abilityName: '' + } + // Start the Work Scheduler task. + startWork(bundleName: string, abilityName: string) { + this.workInfo.bundleName = bundleName + this.workInfo.abilityName = abilityName + try { + workScheduler.startWork(this.workInfo) + console.log(`startWork success`) + } catch (error) { + Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`) + prompt.showToast({ + message: `${error.message}` + }) + } + } + + // Stop the Work Scheduler task. + stopWork(bundleName: string, abilityName: string) { + this.workInfo.bundleName = bundleName + this.workInfo.abilityName = abilityName + workScheduler.stopWork(this.workInfo, false) + console.log(`stopWork`) + } + } + ``` + +2. In the **./entry/src/main/ets/pages/index.ets** directory under the **entry** module of the project, add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task. + + Import the module. + + ```ts + import { workAbility } from '@ohos/library' + ``` + + Add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task. In the API, **bundleName** and **abilityName** are passed in, where the value of **abilityName** is **WorkTest**. + + ```ts + Button($r('app.string.upgrade')) + .width('60%') + .height(40) + .fontSize(30) + .onClick(() => { + this.work.startWork('ohos.samples.workscheduler', 'WorkTest') + }) + ``` + + When the component is destructed, it calls the API to stop the Work Scheduler task. + + ```ts + aboutToDisappear() { + this.work.stopWork('ohos.samples.workscheduler', 'WorkTest') + } + ``` + +### Setting the Configuration File + +1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEntrance** to the code path of the WorkSchedulerExtensionAbility component. + + ```json + { + "module": { + "extensionAbilities": [ + { + "name": "WorkTest", + "srcEntrance": "./ets/workAbility/WorkTest.ets", + "label": "$string:WorkSchedulerExtensionAbility_label", + "description": "$string:WorkSchedulerExtensionAbility_desc", + "type": "workScheduler" + } + ] + } + } + ``` diff --git a/en/application-dev/tools/Readme-EN.md b/en/application-dev/tools/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..5dfe93a6a9584920a5da457ac61964dcb183a99c --- /dev/null +++ b/en/application-dev/tools/Readme-EN.md @@ -0,0 +1,9 @@ +# Debugging Tools + +- [Ability Assistant](aa-tool.md) +- [Bundle Manager](bm-tool.md) +- Packing and Unpacking Tools + - [Packaging Tool](packing-tool.md) + - [Unpacking Tool](unpacking-tool.md) +- [Common Event Manager](cem-tool.md) +- [Advanced Notification Manager](anm-tool.md) diff --git a/en/application-dev/tools/aa-tool.md b/en/application-dev/tools/aa-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..e03cdd52c6df142c13a06c918ae242c4115b323c --- /dev/null +++ b/en/application-dev/tools/aa-tool.md @@ -0,0 +1,119 @@ +# Ability Assistant + + +The Ability Assistant provides the application debugging and testing capabilities that enable you to start applications and test cases. With this tool, you can send commands (started with **aa**) in the hdc shell to perform various system operations, such as starting application components, forcibly stopping processes, and printing application component information. + + +- help + +Displays help information for the Ability Assistant. + +**Return value** + +Returns the help information. + +**Method** + + + ```bash + aa help + ``` + + +- start + +Starts an application component. The target component can be the PageAbility and ServiceAbility components of the FA model or the UIAbility and ServiceExtensionAbility components of the Stage model. The **visible** tag in the configuration file of the target component cannot be set to **false**. + + | Name| Description| + | -------- | -------- | + | -h/--help | Help information.| + | -d | Device ID. Optional.| + | -a | Ability name. Mandatory.| + | -b | Bundle name. Mandatory.| +| -D | Debugging mode. Optional.| + +**Return value** + +Returns "start ability successfully." if the ability is started; returns "error: failed to start ability." and the corresponding error information otherwise. + +**Method** + + + ```bash + aa start [-d ] -a -b [-D] +``` + +- stop-service + +Stops a ServiceAbility. + + | Name| Description| + | -------- | -------- | + | -h/--help | Help information.| + | -d | Device ID. Optional.| + | -a | Ability name. Mandatory.| +| -b | Bundle name. Mandatory.| + +**Return value** + +Returns "stop service ability successfully." if the ServiceAbility is stopped; returns "error: failed to stop service ability." otherwise. + +**Method** + + + ```bash + aa stop-service [-d ] -a -b +``` + +- dump + + Prints information about an application component. + + | Name| Level-2 Parameter| Description| + | -------- | -------- | -------- | + | -h/--help | - | Help information.| + | -a/--all | - | Application component information in all missions.| + | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Mission stack information.
The following values are available for **type**:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | + | -e/--extension | elementName | Extended component information.| + | -u/--userId | UserId | Mission stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: **aa dump -a -u 100** and **aa dump -d -u 100**.| + | -d/--data | - | DataAbility information.| +| -i/--ability | AbilityRecord ID | Detailed information about an application component.| + | -c/--client | - | Detailed information about an application component. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| + + **Method** + + + ```bash +aa dump -a + ``` + + ![aa-dump-a](figures/aa-dump-a.png) + + + ```bash +aa dump -l + ``` + + ![aa-dump-l](figures/aa-dump-l.png) + + + ```bash +aa dump -i 12 + ``` + + ![aa-dump-i](figures/aa-dump-i.png) + +- force-stop + +Forcibly stops a process based on the bundle name. + +**Return value** + +Returns "force stop process successfully." if the process is forcibly stopped; returns "error: failed to force stop process." otherwise. + +**Method** + + + ```bash + aa force-stop + ``` diff --git a/en/application-dev/tools/anm-tool.md b/en/application-dev/tools/anm-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..5a738bc22ff538676158bb3da32aacf9b507097c --- /dev/null +++ b/en/application-dev/tools/anm-tool.md @@ -0,0 +1,71 @@ +# Advanced Notification Manager + +The Advanced Notification Manager provides the notification debugging and testing capabilities that enable you to print notifications and set notification parameters. With this tool, you can send commands (started with **anm**) in the hdc shell to perform various system operations, such as printing notification details, setting the number of cached notifications, and enabling the notification capability. + +### help + +* **Function** + + Prints help information. + +* **Method** + + ```bash + anm help + ``` + +### dump + +* **Function** + + Prints information about notifications. + +* **Method** + + ```bash + anm dump [] + ``` + + The table below describes the available options. + + | Name | Description | + | ---------------- | ---------------------------------- | + | -A/--active | Information about all active notifications. | + | -R/--recent | Information about recent notifications. | + | -D/--distributed | Information about distributed notifications from other devices. | + | -b/--bundle | Bundle name. Optional.| + | -u/--user-id | User ID. Optional. | + | -h/--help | Help information. | + +* **Example**: Print information about active notifications. + + ```bash + anm dump -A + ``` + ![anm-dump-A](figures/anm-dump-A.png) + +### Setting + +* **Function** + + Sets notification parameters. + +* **Method** + + ```bash + anm setting [] + ``` + + The table below describes the available options. + + | Name | Description | + | ------------------------ | ------------------------------------ | + | -c/--recent-count | Maximum number of recent notifications stored in the memory.| + | -e/--enable-notification | Whether to enable the notification capability. | + | -h/--help | Help information. | + +* **Example**: Set the maximum number of recent notifications stored in the memory to 100. + + ```bash + anm setting -c 100 + ``` diff --git a/en/application-dev/tools/bm-tool.md b/en/application-dev/tools/bm-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..879a2f123b2e2ea9a1dc8ce30c38da81458dc2e3 --- /dev/null +++ b/en/application-dev/tools/bm-tool.md @@ -0,0 +1,275 @@ +# Bundle Manager + + +The Bundle Manager provides the bundle debugging and testing capabilities that enable you to install, uninstall, update, and query a bundle (application). With this tool, you can send commands (started with **bm**) in the hdc shell to perform various system operations, such as installing and uninstalling a bundle and querying bundle information. + +**Table 1** bm commands + +| Name| Description| +| -------- | -------- | +| help | Displays the commands supported by the Bundle Manager tool.| +| install | Installs a bundle.| +| uninstall | Uninstalls a bundle.| +| dump | Queries bundle information.| +| clean | Clears the cache and data of a bundle.| +| enable | Enables a bundle. A bundle can be used after being enabled.| +| disable | Disables a bundle. A bundle cannot be used after being disabled.| +| get | Obtains the UDID of a device.| +| quickfix | Performs patch-related operations, such as installing or querying a patch.| + + +## Help Command + +**Table 2** Help command + +| Name| Description| +| -------- | -------- | +| bm help | Displays the commands supported by the bm tool.| + +Example + + +```bash +# Display the help information. +bm help +``` + + +## Installation Command + +```bash +bm install [-h] [-p path] [-u userId] [-r] [-w waitting-time] +``` + +**Table 3** Installation command parameters + +| Name| Mandatory| Description| +| -------- | -------- | -------- | +| -h | No| Used to display the parameters supported by the **install** command. By default, the help information is displayed.| +| -p | Yes| Path of the HAP to install. You can specify a path to install one or more HAPs at the same time.| +| -u | No| User whose HAP is to be installed. By default, the current user's HAP is installed.| +| -r | No| Whether to install the HAP in overwrite mode. By default, the HAP is installed in overwrite mode.| +| -w | No| Time that the Bundle Manager tool waits before installing the HAP. The minimum waiting time is 5s, and the maximum waiting time is 600s. The default waiting time is 5s.| + + +Example + +```bash +bm install -p /data/app/ohosapp.hap -u 100 -w 5s -r +// The execution result is as follows: +install bundle successfully. +``` + + +## Uninstall Command + +```bash +bm uninstall [-h help] [-n bundleName] [-m moduleName] [-u userId] [-k] +``` + +**Table 4** Uninstall command parameters + +| Name| Mandatory| Description| +| -------- | -------- | -------- | +| -h | No| Used to display the parameters supported by the **uninstall** command. By default, the help information is displayed.| +| -n | Yes| Name of the bundle to uninstall.| +| -m | No| Module of the bundle to uninstall. By default, all modules are uninstalled.| +| -u | No| User whose bundle is to be uninstalled. By default, the current user's bundle is uninstalled.| +| -k | No| Whether the application data is retained when the bundle is uninstalled. By default, the application data is deleted along the uninstall.| + + +Example + +```bash +bm uninstall -n com.ohos.app -m com.ohos.app.EntryAbility -u 100 -k +// The execution result is as follows: +uninstall bundle successfully. +``` + + +## Dump Command + +```bash +bm dump [-h help] [-a] [-n bundleName] [-s shortcutInfo] [-u userId] [-d deviceId] +``` + + +If **-u** is not specified, the command applies to all users. + +**Table 5** Dump command parameters + +| Name| Mandatory| Description| +| -------- | -------- | -------- | +| -h | No| Used to display the parameters supported by the **dump** command. By default, the help information is displayed.| +| -a | Yes| Used to display all bundles installed in the system.| +| -n | Yes| Used to display the details of a bundle.| +| -s | Yes| Used to display the shortcut information of a bundle.| +| -d | No| Used to display the bundle information on a given device. By default, the bundle information on the current device is queried.| +| -u | No| Used to display the bundle information for a given user. By default, the bundle information of the current user is queried.| + + +Example + +```bash +# Display the names of all bundles installed in the system. +bm dump -a +# Display the details of a bundle. +bm dump -n com.ohos.app -u 100 +# Display the shortcut information of a bundle. +bm dump -s com.ohos.app -u 100 +# Display cross-device bundle information. +bm dump -n com.ohos.app -d xxxxx +``` + + +## Clean Command + +```bash +bm clean [-h] [-c] [-n bundleName] [-d] [-u userId] +``` + + +If **-u** is not specified, the command applies to all active users. + +**Table 6** Clean command parameters + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **clean** command.| +| -c -n | Used to clear the cache data of a bundle.| +| -d -n | Used to clear the data directory of a bundle.| +| -u | Used to clear the cache data of a bundle for a given user.| + + +Example + +```bash +# Clear the cache data of a bundle. +bm clean -c -n com.ohos.app -u 100 +// The execution result is as follows: +clean bundle cache files successfully. +# Clear the user data of a bundle. +bm clean -d -n com.ohos.app -u 100 +// The execution result is as follows: +clean bundle data files successfully. +``` + + +## Enable Command + +```bash +bm enable [-h] [-n bundleName] [-a abilityName] [-u userId] +``` + + +If **-u** is not specified, the command applies to all active users. + +**Table 7** Enable command parameters + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **enable** command.| +| -n | Used to enable a bundle.| +| -a | Used to enable an ability with a specified bundle name.| +| -u | Used to enable a bundle for a given user.| + + +Example + +```bash +# Enable a bundle. +bm enable -n com.ohos.app -a com.ohos.app.EntryAbility -u 100 +// The execution result is as follows: +enable bundle successfully. +``` + + +## Disable Command + +```bash +bm disable [-h] [-n bundleName] [-a abilityName] [-u userId] +``` + + +If **-u** is not specified, the command applies to all active users. + +**Table 8** Disabled command parameters + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **disable** command.| +| -n | Used to disable a bundle.| +| -a | Used to disable an ability with a specified bundle name.| +| -u | Used to disable a bundle for a given user.| + +Example + +```bash +# Disable a bundle. +bm disable -n com.ohos.app -a com.ohos.app.EntryAbility -u 100 +// The execution result is as follows: +disable bundle successfully. +``` + + +## Obtaining UDID + +```bash +bm get [-h] [-u] +``` + +**Table 9** Parameters used in the command for obtaining the UDID + +| Name| Description| +| -------- | -------- | +| -h | Used to display the parameters supported by the **get** command.| +| -u | Used to obtain the UDID of a device.| + + +Example + +```bash +# Obtain the UDID of a device. +bm get -u +// The execution result is as follows: +udid of current device is : +23CADE0C +``` + + +## Quick Fix + +```bash +bm quickfix [-h] [-a -f filePath] [-q -b bundleName] +``` + +**Table 10** Parameters used in the command for quick fix + +| Name| Description| +| -------- | -------- | +| -h | Used to display the commands supported by **quickfix**.| +| -a -f | Used to run the quick fix patch installation command. **file-path** corresponds to the hqf file. You can pass in one or more hqf files or the directory where the hqf file is located.| +| -q -b | Used to display the patch information based on the bundle name. **bundle-name** indicates the bundle name.| + + +Example + +```bash +# Display patch package information by the bundle name. +bm quickfix -q -b com.ohos.app +// The execution result is as follows: +// Information as follows: +// ApplicationQuickFixInfo: +// bundle name: com.ohos.app +// bundle version code: xxx +// bundle version name: xxx +// patch version code: x +// patch version name: +// cpu abi: +// native library path: +// type: +# Patch installation in the quick fix: +bm quickfix -a -f /data/app/ +// The execution result is as follows: +apply quickfix succeed. +``` diff --git a/en/application-dev/tools/cem-tool.md b/en/application-dev/tools/cem-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..beaf1a86e38b11508d5551a48e018cf98e7e7a6e --- /dev/null +++ b/en/application-dev/tools/cem-tool.md @@ -0,0 +1,85 @@ +# Common Event Manager + +The Common Event Manager provides the common event debugging and testing capabilities that enable you to print common event information and publish common events. With this tool, you can send commands (started with **cem**) in the hdc shell to perform various system operations, such as printing all common event subscribers, sent common events, and recipients, as well as publishing common events. + +## Commands + +### help + +* Function + + Prints help information. + +* Method + + ``` + cem help + ``` + +### publish + +* Function + + Publishes a common event. + +* Method + + ``` + cem publish [] + ``` + + The table below describes the available options. + + | Name | Description | + | ------------ | ------------------------------------------ | + | -e/--event | Name of the common event to publish. Mandatory. | + | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published.| + | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | + | -c/--code | Result code of the common event. Optional. | + | -d/--data | Data carried in the common event. Optional. | + | -h/--help | Help information. | + +* Example + + ```bash + # Publish a common event named testevent. + cem publish --event "testevent" + ``` + + ![cem-publish-event](figures/cem-publish-event.png) + + ```bash + # Publish a sticky, ordered common event named testevent. The result code of the event is 100 and the data carried is this is data. + cem publish -e "testevent" -s -o -c 100 -d "this is data" + ``` + + ![cem-publish-all](figures/cem-publish-all.png) + +### dump + +* Function + + Displays information about common events. + +* Method + + ``` + cem dump [] + ``` + + The table below describes the available options. + + | Name | Description | + | ---------- | -------------------------------------------- | + | -a/--all | Information about all common events that have been sent since system startup.| + | -e/--event | Information about a specific event. | + | -h/--help | Help information. | + +* Example + + ```bash + # Display details of a common event named testevent. + cem dump -e "testevent" + ``` + + ![cem-dump-e](figures/cem-dump-e.png) diff --git a/en/application-dev/tools/figures/aa-dump-a.png b/en/application-dev/tools/figures/aa-dump-a.png new file mode 100644 index 0000000000000000000000000000000000000000..ae8d41f65f68d73895be5bbbb539c0d220b2a9a5 Binary files /dev/null and b/en/application-dev/tools/figures/aa-dump-a.png differ diff --git a/en/application-dev/tools/figures/aa-dump-i.png b/en/application-dev/tools/figures/aa-dump-i.png new file mode 100644 index 0000000000000000000000000000000000000000..12998c5ba3e7d667d1147b6e825f8d110d5c5c5e Binary files /dev/null and b/en/application-dev/tools/figures/aa-dump-i.png differ diff --git a/en/application-dev/tools/figures/aa-dump-l.png b/en/application-dev/tools/figures/aa-dump-l.png new file mode 100644 index 0000000000000000000000000000000000000000..a6797eef284990e3fa25e71562ac8afbddf0821d Binary files /dev/null and b/en/application-dev/tools/figures/aa-dump-l.png differ diff --git a/en/application-dev/notification/figures/anm-dump-A.png b/en/application-dev/tools/figures/anm-dump-A.png similarity index 100% rename from en/application-dev/notification/figures/anm-dump-A.png rename to en/application-dev/tools/figures/anm-dump-A.png diff --git a/en/application-dev/notification/figures/cem-dump-e.png b/en/application-dev/tools/figures/cem-dump-e.png similarity index 100% rename from en/application-dev/notification/figures/cem-dump-e.png rename to en/application-dev/tools/figures/cem-dump-e.png diff --git a/en/application-dev/notification/figures/cem-publish-all.png b/en/application-dev/tools/figures/cem-publish-all.png similarity index 100% rename from en/application-dev/notification/figures/cem-publish-all.png rename to en/application-dev/tools/figures/cem-publish-all.png diff --git a/en/application-dev/notification/figures/cem-publish-event.png b/en/application-dev/tools/figures/cem-publish-event.png similarity index 100% rename from en/application-dev/notification/figures/cem-publish-event.png rename to en/application-dev/tools/figures/cem-publish-event.png diff --git a/en/application-dev/tools/packing-tool.md b/en/application-dev/tools/packing-tool.md new file mode 100644 index 0000000000000000000000000000000000000000..36b5c7fdc295604d7bc46db5e01300e517514ade --- /dev/null +++ b/en/application-dev/tools/packing-tool.md @@ -0,0 +1,90 @@ +# Packaging Tool + + +The packaging tool is a commissioning tool provided by OpenHarmony. It can generate HAP files in command line mode, pack multiple HAP files into an App Pack, or pack multiple HAP files and App Packs into an App Pack. App Pack is the application package format required for releasing an application on AppGallery. + + +The **app_packing_tool.jar** package can be found in the OpenHarmony SDK downloaded locally. + + +- Packing folders into an HAP file + +The command in the stage model is as follows: + + + ```bash + java -jar app_packing_tool.jar --mode