diff --git a/CODEOWNERS b/CODEOWNERS index 1e61b5d70d7ea0768b8683ea7956a4b34e212a5c..b795faf3a92d05a3975f5150e8f0f7789560b04f 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -426,7 +426,7 @@ zh-cn/application-dev/reference/apis/js-apis-socket.md @zhang-hai-feng @zengyawe zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw -zh-cn/application-dev/reference/apis/js-apis-system-app.md @shuaytao @RayShih @wangzhen107 @inter515 +zh-cn/application-dev/reference/apis/js-apis-system-app.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 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/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md index 0a5ba865f4b8c9894523666de1582b012f8f2237..ab116c430cb7b248b947ccbee46cf5ac932f9fc9 100644 --- a/en/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md @@ -78,6 +78,5 @@ The **module.json5** of a browser application is as follows: 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 \ No newline at end of file +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 index fa3aa07c60287688749c13035451d0b470e621ea..4e0a273f850b4919d0964580ebed89c053c273f7 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -55,4 +55,3 @@ When an application is switched to the background, it is cached in the backgroun } ``` - \ No newline at end of file diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index 2479ab317cfdff8bc642f3f307fb4d8423efe112..85dfb9523ca117e691480bcbd2321b5fb3b22304 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -2,6 +2,7 @@ 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** @@ -15,6 +16,7 @@ The [action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantactio 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** diff --git a/en/application-dev/application-models/api-switch-overview.md b/en/application-dev/application-models/api-switch-overview.md index 461e321d410a7f0036f5b4a1700c6176d7d451da..bf8223b5a6c047af46e960dad6713f20e251d02f 100644 --- a/en/application-dev/application-models/api-switch-overview.md +++ b/en/application-dev/application-models/api-switch-overview.md @@ -13,8 +13,8 @@ Due to the differences in the thread model and process model, certain APIs (mark import fa from '@ohos.ability.featureAbility'; let parameter = { "want": { - bundleName: "ohos.samples.demo", - abilityName: "ohos.samples.demo.MainAbility" + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.EntryAbility" } } fa.startAbility(parameter).then((data) => { @@ -30,8 +30,8 @@ Due to the differences in the thread model and process model, certain APIs (mark // 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: "ohos.samples.demo", - abilityName: "ohos.samples.demo.MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; this.context.startAbility(wantInfo).then((data) => { console.info('startAbility success.'); diff --git a/en/application-dev/application-models/app-deviceconfig-switch.md b/en/application-dev/application-models/app-deviceconfig-switch.md index 8630746cb46979d1a7e37c2c6e30787ad5fe91ec..1092c21081cd9a8d62c92a1a68ba434efee7c8c9 100644 --- a/en/application-dev/application-models/app-deviceconfig-switch.md +++ b/en/application-dev/application-models/app-deviceconfig-switch.md @@ -28,4 +28,3 @@ OpenHarmony has reconstructed the [deviceConfig](../quick-start/deviceconfig-str | 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.| - \ No newline at end of file diff --git a/en/application-dev/application-models/application-component-configuration-fa.md b/en/application-dev/application-models/application-component-configuration-fa.md index d460966545bc6e4901169779f0450308b44c8866..4cc1c9ad6831f0e54ae4c70f4f7229a7abc7c62f 100644 --- a/en/application-dev/application-models/application-component-configuration-fa.md +++ b/en/application-dev/application-models/application-component-configuration-fa.md @@ -38,4 +38,3 @@ When developing an application, you may need to configure certain tags to identi 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). - \ No newline at end of file diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md index 56a5ddac56d43e09609fa8e6e9669fab39681988..de9e29941b5ddcc9e29f62ddc039fb38b6bc54b6 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -3,8 +3,7 @@ When developing an application, you may need to configure certain tags to identify the application, such as the bundle name and application icon. This topic describes key tags that need to be configured during application development. Icons and labels are usually configured together. There is the application icon, application label, entry icon, and entry label, which correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). The application icon and label are used in **Settings**. For example, they are displayed in the application list in **Settings**. The entry icon is displayed on the device's home screen after the application is installed. The entry icon maps to a [UIAbility](uiability-overview.md) component. Therefore, an application can have multiple entry icons and labels. When you touch one of them, the corresponding UIAbility page is displayed. - - **Figure 1** Icons and labels +**Figure 1** Icons and labels ![application-component-configuration-stage](figures/application-component-configuration-stage.png) @@ -71,4 +70,3 @@ When developing an application, you may need to configure certain tags to identi 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. - \ No newline at end of file diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index af8f5d82a3f162381f4b970c82e0def06b91070b..8d49b7369bb93e26f4407313f2d9352acd7380e1 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -12,7 +12,7 @@ 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, request permissions from users, and more. + - [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'; @@ -65,15 +65,10 @@ 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) -- [Requesting Permissions from Users Through AbilityContext](#requesting-permissions-from-users-through-uiabilitycontext) - ### Obtaining the Application Development Path @@ -180,9 +175,9 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] > - 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'; @@ -194,8 +189,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] // ... } } - ``` - +``` + - Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module. > **NOTE** > @@ -204,7 +199,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] > - 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'; @@ -217,7 +212,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] } } ``` - + - Call **createModuleContext(moduleName:string)** to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module. ```ts @@ -242,7 +237,7 @@ When the ability lifecycle changes in a process, for example, being created or d ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; const TAG: string = "[Example].[Entry].[EntryAbility]"; @@ -298,14 +293,3 @@ export default class EntryAbility extends UIAbility { } } ``` - - -### Requesting Permissions from Users Through UIAbilityContext - -Each ability has the **Context** attribute. The ability is used to process the lifecycle. Methods use to operate the ability (such as **startAbility()**, **connectServiceExtensionAbility()**, and **terminateSelf()**) are implemented in the corresponding context. The context also provides methods for obtaining the ability configuration and requesting permissions from users. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). - - -When an application needs to obtain users' privacy information or use system capabilities, for example, to obtain location information, to access the calendar, or to use the camera to take photos or record videos, the application must request permissions from users, as shown below. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md). - -**Figure 2** Requesting the permission to access the calendar from users -application-context-stage \ No newline at end of file diff --git a/en/application-dev/application-models/application-model-description.md b/en/application-dev/application-models/application-model-description.md index 2c15a15ee2aa30c9e56a04fb21497af01969cd07..de7e3045d79eff2c681291f8d4de55129d361245 100644 --- a/en/application-dev/application-models/application-model-description.md +++ b/en/application-dev/application-models/application-model-description.md @@ -58,4 +58,3 @@ The table below describes their differences in detail. | **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).| - \ No newline at end of file diff --git a/en/application-dev/application-models/bind-serviceability-from-stage.md b/en/application-dev/application-models/bind-serviceability-from-stage.md index 0ee35195b8810efea9af4382c80d0c8e37e0fd70..2d99fddfe503db082cf7613f3875dcf490331dd9 100644 --- a/en/application-dev/application-models/bind-serviceability-from-stage.md +++ b/en/application-dev/application-models/bind-serviceability-from-stage.md @@ -12,15 +12,15 @@ A UIAbility accesses a ServiceAbility in the same way as it accesses a ServiceEx ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.info("MainAbility onCreate"); + console.info("EntryAbility onCreate"); } onDestroy() { - console.info("MainAbility onDestroy") + console.info("EntryAbility onDestroy") } onWindowStageCreate(windowStage) { - console.info("MainAbility onWindowStageCreate") + console.info("EntryAbility onWindowStageCreate") let want = { bundleName: "com.ohos.fa", abilityName: "ServiceAbility", @@ -40,13 +40,13 @@ export default class MainAbility extends UIAbility { let connectionId = this.context.connectServiceExtensionAbility(want, options); } onWindowStageDestroy() { - console.info("MainAbility onWindowStageDestroy") + console.info("EntryAbility onWindowStageDestroy") } onForeground() { - console.info("MainAbility onForeground") + console.info("EntryAbility onForeground") } onBackground() { - console.info("MainAbility onBackground") + console.info("EntryAbility onBackground") } } ``` diff --git a/en/application-dev/application-models/component-startup-rules-fa.md b/en/application-dev/application-models/component-startup-rules-fa.md index 15788e109c4406d740f403d3e21a27d7d0a451c6..db64e8c093df679a9e52d6bc753e4935a21c25be 100644 --- a/en/application-dev/application-models/component-startup-rules-fa.md +++ b/en/application-dev/application-models/component-startup-rules-fa.md @@ -25,7 +25,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol - **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-tag) + - 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. @@ -67,4 +67,3 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ![component-startup-rules](figures/component-startup-inter-fa.png) - \ No newline at end of file diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index a00d01780d9bf67b6b64ec90b4c3bd0635865c74..0e6c2ce33c68913221c7b09f02e96327b0ea1c30 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -24,7 +24,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol - **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-tag) + - 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. @@ -62,4 +62,3 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ![component-startup-rules](figures/component-startup-inter-stage.png) - \ No newline at end of file diff --git a/en/application-dev/application-models/config-file-fa.md b/en/application-dev/application-models/config-file-fa.md index f19104d0db5b36346ff3f868d0fb9e5773460ac1..3f550aa6192faeab625b9f65884fb0bbc7e79e15 100644 --- a/en/application-dev/application-models/config-file-fa.md +++ b/en/application-dev/application-models/config-file-fa.md @@ -4,4 +4,3 @@ The application configuration file contains information about the application co 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). - \ No newline at end of file diff --git a/en/application-dev/application-models/config-file-stage.md b/en/application-dev/application-models/config-file-stage.md index bf667dcb0d33228581cfbec3a7ab4750a3cb4b94..66cabf4a99fd4a3f5138c0a8ef1bbf2cefbe15c0 100644 --- a/en/application-dev/application-models/config-file-stage.md +++ b/en/application-dev/application-models/config-file-stage.md @@ -4,4 +4,3 @@ The application configuration file contains information about the application co 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). - \ No newline at end of file diff --git a/en/application-dev/application-models/configuration-file-diff.md b/en/application-dev/application-models/configuration-file-diff.md index 141eeab16f692b144c57488918e978217e61d08f..745f2702cab12b8ef99e174c924d49cf2217bf2b 100644 --- a/en/application-dev/application-models/configuration-file-diff.md +++ b/en/application-dev/application-models/configuration-file-diff.md @@ -9,4 +9,3 @@ The stage model uses the [app.json5](../quick-start/app-configuration-file.md) a **Figure 1** Configuration file differences ![comparison-of-configuration-file](figures/comparison-of-configuration-file.png) - \ No newline at end of file diff --git a/en/application-dev/application-models/create-pageability.md b/en/application-dev/application-models/create-pageability.md index 7a79770c309a165b8421974b28263bb20fa587ee..783646ff4cfd5fa2ab193005bfa9d182dc75b70c 100644 --- a/en/application-dev/application-models/create-pageability.md +++ b/en/application-dev/application-models/create-pageability.md @@ -30,7 +30,7 @@ export default { ``` -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 MainAbility: +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 { @@ -48,13 +48,13 @@ After the PageAbility is created, its abilities-related configuration items are ], "orientation": "unspecified", "visible": true, - "srcPath": "MainAbility", - "name": ".MainAbility", + "srcPath": "EntryAbility", + "name": ".EntryAbility", "srcLanguage": "ets", "icon": "$media:icon", - "description": "$string:MainAbility_desc", + "description": "$string:EntryAbility_desc", "formsEnabled": false, - "label": "$string:MainAbility_label", + "label": "$string:EntryAbility_label", "type": "page", "launchType": "singleton" } @@ -65,6 +65,7 @@ After the PageAbility is created, its abilities-related configuration items are 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| diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md index 63d7d26d47b64407e30fc03c2edb7ead210dc392..4ecdf35ead5482d4b4b2e0d0a2a4544e75686612 100644 --- a/en/application-dev/application-models/data-share-via-want.md +++ b/en/application-dev/application-models/data-share-via-want.md @@ -56,20 +56,20 @@ Users often need to share data (such as a text or an image) from one application } } } - ``` - - 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: - + ``` + + 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. - + - **"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 [Implicit Want Matching Rules](explicit-implicit-want-mappings.md#interpretation-of-implicit-want-matching-rules). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application. + 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: diff --git a/en/application-dev/application-models/dataability-configuration.md b/en/application-dev/application-models/dataability-configuration.md index d3618ea7a026311004524a9eb79ff3d1951d6a93..c8c69c8626cf9872e40931b2f97c431e105cb38f 100644 --- a/en/application-dev/application-models/dataability-configuration.md +++ b/en/application-dev/application-models/dataability-configuration.md @@ -59,4 +59,3 @@ The following is an example **config.json** file: For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md). - \ No newline at end of file diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md index 99aa45c9f8f387e5717a90478a0a24d2be60f463..ccf33e07d1b389eb1246a89a377febb1e7d24a78 100644 --- a/en/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md @@ -1,48 +1,48 @@ # 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. -- **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.| +| 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** - | 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.
For details, see [Interpretation of Implicit Want Matching Rules](#interpretation-of-implicit-want-matching-rules). | - | 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.| +## Matching Rules for Implicit Want -## Interpretation of Implicit Want Matching Rules +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-tag) in the [module.json5 file](../quick-start/module-configuration-file.md). +- 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. @@ -60,8 +60,7 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m - 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 - + **Figure 1** Matching rules of action in the want parameter want-action @@ -112,6 +111,7 @@ There are four combinations of **uri** and **type** settings. The matching rules 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 @@ -158,5 +158,3 @@ To simplify the description, **uri** in the passed **want** parameter is called - 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/`. - - \ No newline at end of file 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 index 8957b1b4a85a7bdc8d0d9ab422d7cf379ae6cf75..9ddf0c3892998aa5391de99775db5965f66bd4b1 100644 Binary files a/en/application-dev/application-models/figures/application-component-configuration-stage.png 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 index 9423fd5f99deb310315c13173422cb050d93fbb7..0d4c6cdfd040b4df9930d8bc639deff32f033824 100644 Binary files a/en/application-dev/application-models/figures/application-context-stage.png and b/en/application-dev/application-models/figures/application-context-stage.png differ diff --git a/en/application-dev/application-models/figures/stage-want1.png b/en/application-dev/application-models/figures/stage-want1.png index 09ebc69170dca547c7b965dbf62c1a4df978815f..558f0a8588d7785eaad1402e68d6ba60c3118f27 100644 Binary files a/en/application-dev/application-models/figures/stage-want1.png 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 index 3c5358cb3d98f8b519369f8ecce1964fd02c3d58..72829adade52ee11419d726f19e218ec4de15220 100644 Binary files a/en/application-dev/application-models/figures/stage-want2.png and b/en/application-dev/application-models/figures/stage-want2.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 index 59a0110cfc0b36780adb0a936af34588fcfdeb1a..92292f2c6ef4c9cbd06da2a523f27b571a957e2b 100644 Binary files a/en/application-dev/application-models/figures/uiability-intra-device-interaction.png and b/en/application-dev/application-models/figures/uiability-intra-device-interaction.png differ diff --git a/en/application-dev/application-models/hop-multi-device-collaboration.md b/en/application-dev/application-models/hop-multi-device-collaboration.md index 85d6403187331a40bb9ea6280a3129dfb0e84883..3a6fa2646a37785d41793407d4803d60743342dd 100644 --- a/en/application-dev/application-models/hop-multi-device-collaboration.md +++ b/en/application-dev/application-models/hop-multi-device-collaboration.md @@ -345,21 +345,19 @@ The following describes how to implement multi-device collaboration through cros 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. + 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: + 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", @@ -377,77 +375,75 @@ For the callee ability, implement the callback to receive data and the methods t ```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. - - + 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 = ""; + num: number = 0 + str: string = "" constructor(num, string) { - this.num = num; - this.str = string; + this.num = num + this.str = string } marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - return true; + messageParcel.writeInt(this.num) + messageParcel.writeString(this.str) + return true } unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - return true; + this.num = messageParcel.readInt() + this.str = messageParcel.readString() + return true } } ``` 4. Implement **Callee.on** and **Callee.off**. - In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. - - ```ts - const TAG: string = '[CalleeAbility]'; - const MSG_SEND_METHOD: string = 'CallSendMsg'; - - function sendMsgCallback(data) { - console.info('CalleeSortFunc called'); - - // Obtain the sequenceable data sent by the caller ability. - let receivedData = new MySequenceable(0, ''); - data.readSequenceable(receivedData); - console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); - - // Process the data. - // Return the sequenceable data result to the caller ability. - return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`); - } - - export default class CalleeAbility extends Ability { - onCreate(want, launchParam) { - try { - this.callee.on(MSG_SEND_METHOD, sendMsgCallback); - } catch (error) { - console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); - } - } - - onDestroy() { - try { - this.callee.off(MSG_SEND_METHOD); - } catch (error) { - console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`); - } - } - } - ``` - + In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. + + ```ts + const TAG: string = '[CalleeAbility]' + const MSG_SEND_METHOD: string = 'CallSendMsg' + + function sendMsgCallback(data) { + console.info('CalleeSortFunc called') + + // Obtain the sequenceable data sent by the caller ability. + let receivedData = new MySequenceable(0, '') + data.readSequenceable(receivedData) + console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`) + + // Process the data. + // Return the sequenceable data result to the caller ability. + return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) + } + + export default class CalleeAbility extends Ability { + onCreate(want, launchParam) { + try { + this.callee.on(MSG_SEND_METHOD, sendMsgCallback) + } catch (error) { + console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + } + } + + onDestroy() { + try { + this.callee.off(MSG_SEND_METHOD) + } catch (error) { + console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`) + } + } + } + ``` + 4. Obtain the caller object and access the callee ability. 1. Import the **UIAbility** module. @@ -457,14 +453,13 @@ For the callee ability, implement the callback to receive data and the methods t 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. + 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; + var caller = undefined + var context = this.context context.startAbilityByCall({ deviceId: getRemoteDeviceId(), @@ -472,23 +467,22 @@ For the callee ability, implement the callback to receive data and the methods t abilityName: 'CalleeAbility' }).then((data) => { if (data != null) { - caller = data; - console.info('get remote caller success'); + caller = data + console.info('get remote caller success') // Register the onRelease() listener of the caller ability. caller.onRelease((msg) => { - console.info(`remote caller onRelease is called ${msg}`); + console.info(`remote caller onRelease is called ${msg}`) }) - console.info('remote caller register OnRelease succeed'); + console.info('remote caller register OnRelease succeed') } }).catch((error) => { - console.error(`get remote caller failed with ${error}`); + console.error(`get remote caller failed with ${error}`) }) } - ``` - - 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). - ``` - + ``` + + 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. diff --git a/en/application-dev/application-models/mission-management-launch-type.md b/en/application-dev/application-models/mission-management-launch-type.md index 7dbb3b5c8fa5a8dfab3f03ab0eb3b02ba4cb98d2..72b6dbf80df2628119ebcc29339ed7e4b70e9a50 100644 --- a/en/application-dev/application-models/mission-management-launch-type.md +++ b/en/application-dev/application-models/mission-management-launch-type.md @@ -31,4 +31,3 @@ Every mission retains a snapshot of the UIAbility instance. After the UIAbility > > The **specified** mode is supported in the stage model only. - \ No newline at end of file diff --git a/en/application-dev/application-models/redirection-rules.md b/en/application-dev/application-models/redirection-rules.md index c5c9987c261364f87dadc0333b310744fe12f971..d7456653640942bca333a28f7f6d5262ec4d63f3 100644 --- a/en/application-dev/application-models/redirection-rules.md +++ b/en/application-dev/application-models/redirection-rules.md @@ -33,4 +33,4 @@ To enable an ability to be called by any application, configure the **config.jso ``` -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#interpretation-of-implicit-want-matching-rules) 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. +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/serviceability-configuration.md b/en/application-dev/application-models/serviceability-configuration.md index a0bf139c2ec08382b73e1bce7bb87882a2306def..2c8e009a10937140e013d030cf21a1167b1fd3e8 100644 --- a/en/application-dev/application-models/serviceability-configuration.md +++ b/en/application-dev/application-models/serviceability-configuration.md @@ -14,4 +14,3 @@ Similar to a PageAbility, a ServiceAbility is configured in **abilities** under For details about the configuration items, see [Internal Structure of module](../quick-start/module-structure.md). - \ No newline at end of file diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 6626bf66592f4fabb9abf890b163b9b392f04955..c4ffdbd980fff4ce568115f92af884da06739ad2 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -293,4 +293,3 @@ The ServiceExtensionAbility component returns an IRemoteObject in the **onConnec }) ``` - \ No newline at end of file diff --git a/en/application-dev/application-models/stage-model-development-overview.md b/en/application-dev/application-models/stage-model-development-overview.md index 139a27e2151cd3141bd7a0dd3a93c3c90929bf2a..6fbf06baa44d4c0f2196fa3c1b00a0761a71a161 100644 --- a/en/application-dev/application-models/stage-model-development-overview.md +++ b/en/application-dev/application-models/stage-model-development-overview.md @@ -17,7 +17,7 @@ The following figure shows the basic concepts used in the stage model. - 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 window through WindowStage, and this window provides an area for ArkUI to render. + 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) @@ -32,12 +32,12 @@ The following figure shows the basic concepts used in the stage model. During application development based on the stage model, the following tasks are involved in the application model. - **Table 1** Stage model development process +**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) | +| 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 MissionList](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) | +| 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-local-pageability.md b/en/application-dev/application-models/start-local-pageability.md index d8344820078bcdd52c2d92b1b406dfabf9253a35..425566ab88d66aecd4690c569dd84d94c46cd568 100644 --- a/en/application-dev/application-models/start-local-pageability.md +++ b/en/application-dev/application-models/start-local-pageability.md @@ -22,7 +22,7 @@ import featureAbility from '@ohos.ability.featureAbility' want: { bundleName: "com.example.myapplication", moduleName: "entry", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.EntryAbility" } } await featureAbility.startAbility(param) diff --git a/en/application-dev/application-models/start-page.md b/en/application-dev/application-models/start-page.md index adf814355974157f579b809be6583d9b7a713d70..58966d93cba037eaad141caaed0feaaaa672cde1 100644 --- a/en/application-dev/application-models/start-page.md +++ b/en/application-dev/application-models/start-page.md @@ -12,7 +12,7 @@ import featureAbility from '@ohos.ability.featureAbility'; async function restartAbility() { let wantInfo = { bundleName: "com.sample.MyApplication", - abilityName: "MainAbility", + abilityName: "EntryAbility", parameters: { page: "pages/second" } @@ -89,7 +89,7 @@ struct Index { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page1" } } }).then((data) => { @@ -104,7 +104,7 @@ struct Index { featureAbility.startAbility({ want: { bundleName: "com.exm.myapplication", - abilityName: "com.exm.myapplication.MainAbility", + abilityName: "com.exm.myapplication.EntryAbility", parameters: { page: "pages/page2" } } }).then((data) => { diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md index f3a09f4af4613e2ad963b8e0aba1596ba6903c67..9d1b7ed27f6780ce56d1e90b3be5d196cf3b1187 100644 --- a/en/application-dev/application-models/start-pageability-from-stage.md +++ b/en/application-dev/application-models/start-pageability-from-stage.md @@ -9,23 +9,23 @@ This topic describes how the two application components of the stage model start A UIAbility starts a PageAbility in the same way as it starts another UIAbility. ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.info("MainAbility onCreate") + console.info("EntryAbility onCreate") } onDestroy() { - console.info("MainAbility onDestroy") + console.info("EntryAbility onDestroy") } onWindowStageCreate(windowStage) { - console.info("MainAbility onWindowStageCreate") + console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { // ... }); let want = { bundleName: "com.ohos.fa", - abilityName: "MainAbility", + abilityName: "EntryAbility", }; this.context.startAbility(want).then(() => { console.info('Start Ability successfully.'); @@ -34,13 +34,13 @@ export default class MainAbility extends UIAbility { }); } onWindowStageDestroy() { - console.info("MainAbility onWindowStageDestroy") + console.info("EntryAbility onWindowStageDestroy") } onForeground() { - console.info("MainAbility onForeground") + console.info("EntryAbility onForeground") } onBackground() { - console.info("MainAbility onBackground") + console.info("EntryAbility onBackground") } } ``` @@ -54,23 +54,23 @@ A UIAbility starts a PageAbility through **startAbilityForResult()** in the same ```ts -import UIAbility from '@ohos.app.ability.UIAbility' +import UIAbility from '@ohos.app.ability.UIAbility'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.info("MainAbility onCreate") + console.info("EntryAbility onCreate") } onDestroy() { - console.info("MainAbility onDestroy") + console.info("EntryAbility onDestroy") } onWindowStageCreate(windowStage) { - console.info("MainAbility onWindowStageCreate") + console.info("EntryAbility onWindowStageCreate") windowStage.loadContent('pages/Index', (err, data) => { // ... }); let want = { bundleName: "com.ohos.fa", - abilityName: "MainAbility", + abilityName: "EntryAbility", }; this.context.startAbilityForResult(want).then((result) => { console.info('Ability verify result: ' + JSON.stringify(result)); @@ -79,13 +79,13 @@ export default class MainAbility extends UIAbility { }); } onWindowStageDestroy() { - console.info("MainAbility onWindowStageDestroy") + console.info("EntryAbility onWindowStageDestroy") } onForeground() { - console.info("MainAbility onForeground") + console.info("EntryAbility onForeground") } onBackground() { - console.info("MainAbility onBackground") + console.info("EntryAbility onBackground") } } ``` @@ -110,7 +110,7 @@ export default class ServiceExtension extends Extension { console.info("ServiceExtension onRequest") let wantFA = { bundleName: "com.ohos.fa", - abilityName: "MainAbility", + abilityName: "EntryAbility", }; this.context.startAbility(wantFA).then(() => { console.info('Start Ability successfully.'); diff --git a/en/application-dev/application-models/start-remote-pageability.md b/en/application-dev/application-models/start-remote-pageability.md index 54f370aa454019d3568c6048649d5fca4003d777..4e998a15d23d298bfdb402bd18ea0db2a9f819eb 100644 --- a/en/application-dev/application-models/start-remote-pageability.md +++ b/en/application-dev/application-models/start-remote-pageability.md @@ -97,13 +97,13 @@ function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { let list = dmClass.getTrustedDeviceListSync(); if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.info("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + console.info("EntryAbility onButtonClick getRemoteDeviceId err: list is null"); return; } - console.info("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + console.info("EntryAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); return list[0].deviceId; } else { - console.info("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.info("EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null"); } } ``` diff --git a/en/application-dev/application-models/start-uiability-from-fa.md b/en/application-dev/application-models/start-uiability-from-fa.md index fd2328f6471e045171312ea3909e652f68831c24..42d8e034cd6519643423bb289217d1aa140a18d4 100644 --- a/en/application-dev/application-models/start-uiability-from-fa.md +++ b/en/application-dev/application-models/start-uiability-from-fa.md @@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.MainAbility" + abilityName: "com.ohos.stage.EntryAbility" } }; featureAbility.startAbility(parameter).then((code) => { @@ -38,7 +38,7 @@ import featureAbility from '@ohos.ability.featureAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.MainAbility" + abilityName: "com.ohos.stage.EntryAbility" } }; featureAbility.startAbilityForResult(parameter).then((result) => { @@ -60,7 +60,7 @@ import particleAbility from '@ohos.ability.particleAbility'; let parameter = { "want": { bundleName: "com.ohos.stage", - abilityName: "com.ohos.stage.MainAbility" + abilityName: "com.ohos.stage.EntryAbility" } }; particleAbility.startAbility(parameter).then(() => { diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md index db85dfdffb0a7d9e60e78151d6654fcdd4a973aa..ea6b8bbecfa4a9a4f5434fb0aa5aad6184f38c9f 100644 --- a/en/application-dev/application-models/uiability-intra-device-interaction.md +++ b/en/application-dev/application-models/uiability-intra-device-interaction.md @@ -1,4 +1,4 @@ -# Interaction Intra-Device Between UIAbility Components +# 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). @@ -50,7 +50,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ```ts import UIAbility from '@ohos.app.ability.UIAbility'; - import Window from '@ohos.window'; + import window from '@ohos.window'; export default class FuncAbility extends UIAbility { onCreate(want, launchParam) { @@ -196,6 +196,7 @@ This section describes how to start the UIAbility of another application through ``` The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. + uiability-intra-device-interaction 3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**. @@ -442,7 +443,8 @@ Ability call is usually used in the following scenarios: The following figure shows the ability call process. -Figure 1 Ability call process +**Figure 1** Ability call process + call - The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. @@ -461,7 +463,7 @@ Figure 1 Ability call process 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 +**Table 2** Ability call APIs | API| Description| | -------- | -------- | @@ -486,8 +488,7 @@ For the callee ability, implement the callback to receive data and the methods t 1. Configure the ability launch type. - -Set **launchType** of the callee ability to **singleton** in the **module.json5** file. + Set **launchType** of the callee ability to **singleton** in the **module.json5** file. | JSON Field| Description| | -------- | -------- | @@ -595,9 +596,9 @@ An example of the ability configuration is as follows: 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) { diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md index c64d7fb3ffc0e3fa31741924439998118449068a..cda8307ddd3dae6f7cceac3fad134ef510d7383c 100644 --- a/en/application-dev/application-models/uiability-launch-type.md +++ b/en/application-dev/application-models/uiability-launch-type.md @@ -18,6 +18,7 @@ The launch type of the UIAbility component refers to the state of the UIAbility 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** @@ -47,6 +48,7 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration 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**. @@ -72,6 +74,7 @@ To use the standard mode, set **launchType** in the [module.json5 configuration 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. @@ -93,7 +96,7 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of ``` 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** parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to distinguish the UIAbility instances. + 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. @@ -146,7 +149,8 @@ For example, there are EntryAbility and SpecifiedAbility, and the launch type of 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. + +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. diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md index b530a7bda5c4f3c4fe0dd2eb96d53991083a5ff4..9ec701cbffd4da51098d5dc448addd88f26ee47e 100644 --- a/en/application-dev/application-models/uiability-lifecycle.md +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -7,7 +7,7 @@ When a user opens, switches, and returns to an application, the UIAbility instan The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below. - **Figure 1** UIAbility lifecycle states +**Figure 1** UIAbility lifecycle states Ability-Life-Cycle @@ -21,7 +21,7 @@ The **Create** state is triggered when the UIAbility instance is created during ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { @@ -36,14 +36,14 @@ export default class EntryAbility extends UIAbility { 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 +**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'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { // ... @@ -77,7 +77,7 @@ Before the UIAbility instance is destroyed, the **onWindowStageDestroy()** callb ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { // ... @@ -135,7 +135,7 @@ The UIAbility instance is destroyed when **terminateSelf()** is called or the us ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { // ... diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index ec26d2ca9b360259d7f7c00c37cba53bd5db8756..14cb5c4652749c97dd6e50c4232b6f65fb6feaab 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -37,4 +37,3 @@ To enable an application to properly use a UIAbility component, declare the UIAb > > 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). - \ No newline at end of file diff --git a/en/application-dev/application-models/uiability-usage.md b/en/application-dev/application-models/uiability-usage.md index ccd80625f460ea704f689f9b7dfa83f6b42fa47f..fa8badc6d48c7e550922cb60a15d02eab9cc80b6 100644 --- a/en/application-dev/application-models/uiability-usage.md +++ b/en/application-dev/application-models/uiability-usage.md @@ -11,10 +11,10 @@ If no startup page is specified, a white screen occurs after the application is ```ts import UIAbility from '@ohos.app.ability.UIAbility'; -import Window from '@ohos.window'; +import window from '@ohos.window'; export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: Window.WindowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created. Set a main page for this ability. windowStage.loadContent('pages/Index', (err, data) => { // ... diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md index 784f190ad6b23a85c60995c44babdc8dd34d576d..f8239c64cf43a0df0acca0bc1ec0e3be914eecfe 100644 --- a/en/application-dev/application-models/want-overview.md +++ b/en/application-dev/application-models/want-overview.md @@ -23,7 +23,7 @@ ``` - **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-tag)) provided by another application. For example, you can use implicit Want to describe a request for opening a link, since you do not care which application is used to open the link. The system matches all applications that support the request. + Implicit Want 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 @@ -47,5 +47,3 @@ > - 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. - - \ No newline at end of file diff --git a/en/application-dev/application-models/widget-development-fa.md b/en/application-dev/application-models/widget-development-fa.md index c170f134932af44c4e8b55888e216926ef51186e..17f9ee7234865b5d01e2a5f68e52cf7928739db7 100644 --- a/en/application-dev/application-models/widget-development-fa.md +++ b/en/application-dev/application-models/widget-development-fa.md @@ -184,7 +184,7 @@ The widget configuration file is named **config.json**. Find the **config.json** | 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)| - A configuration example is as follows: + Example configuration: ```json @@ -211,14 +211,14 @@ 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 attribute 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| - | metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute.| Object| 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)| | customizeData | Custom information about the widget.| Object array| Yes (initial value: left empty)| - A configuration example is as follows: + Example configuration: ```json @@ -232,11 +232,11 @@ The widget configuration file is named **config.json**. Find the **config.json** "type": "service", "srcLanguage": "ets", "formsEnabled": true, - "formConfigAbility": "ability://com.example.entry.MainAbility", + "formConfigAbility": "ability://com.example.entry.EntryAbility", "forms": [{ "colorMode": "auto", "defaultDimension": "2*2", - "description": "This is a service widget.", + "description": "This is a widget.", "formVisibleNotify": true, "isDefault": true, "jsComponentName": "widget", @@ -282,7 +282,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean 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 instance acquisition and update. + // Persistently store widget data for subsequent use, such as instance acquisition and update. // Implement this API based on project requirements. storeFormInfo(formId, formName, tempFlag); @@ -325,7 +325,7 @@ async function deleteFormInfo(formId: string) { For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -The **Want** object 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 @@ -434,7 +434,7 @@ You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. Thi "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "params": { "message": "add detail" } @@ -451,12 +451,12 @@ You can set router and message events for components on a widget. The router eve 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 MainAbility name of the FA model created by DevEco Studio is com.example.entry.MainAbility. - - **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 FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. + - **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. + - **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: @@ -529,7 +529,7 @@ The following is an example: "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.entry.MainAbility", + "abilityName": "com.example.entry.EntryAbility", "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 index 38f4e89d108d9d012c968b3d05de5b4e841ff482..3e542956072a31fbc8dbca097ae264dfe8ebfc5f 100644 --- a/en/application-dev/application-models/widget-development-stage.md +++ b/en/application-dev/application-models/widget-development-stage.md @@ -181,7 +181,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ### 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. - A configuration example is as follows: + Example configuration: ```json @@ -222,19 +222,19 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo | 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 attribute 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)| - | metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute.| Object| 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 { "forms": [ { "name": "widget", - "description": "This is a service widget.", + "description": "This is a widget.", "src": "./js/widget/pages/index/index", "window": { "designWidth": 720, @@ -288,7 +288,7 @@ export default class EntryFormAbility extends FormExtension { 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 instance acquisition and update. + // Persistently store widget data for subsequent use, such as instance acquisition and update. // Implement this API based on project requirements. storeFormInfo(formId, formName, tempFlag); @@ -334,7 +334,7 @@ export default class EntryFormAbility extends FormExtension { For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -The **Want** object 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 @@ -462,12 +462,12 @@ 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. + - **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. + - **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: @@ -597,4 +597,3 @@ The following is an example: }; ``` - \ No newline at end of file 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/application-test/arkxtest-guidelines.md b/en/application-dev/application-test/arkxtest-guidelines.md index ce7a28154635b724d127a50af801c74f84607402..334f69a8ca24eb8de3bb83cd1405fb14a25132bd 100644 --- a/en/application-dev/application-test/arkxtest-guidelines.md +++ b/en/application-dev/application-test/arkxtest-guidelines.md @@ -42,7 +42,7 @@ arkXtest is divided into two parts: unit test framework and UI test framework. - The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md). -## Environment preparations +## Preparing the Environment ### Environment Requirements @@ -72,7 +72,7 @@ export default function abilityTest() { it('testUiExample',0, async function (done) { console.info("uitest: TestUiExample begin"); //start tested ability - await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ + await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{ console.info('Uitest, start ability finished:' + result) }).catch(err => { console.info('Uitest, start ability failed: ' + err) @@ -81,7 +81,7 @@ export default function abilityTest() { //check top display ability await delegator.getCurrentTopAbility().then((Ability)=>{ console.info("get top ability"); - expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); + expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); }) done(); }) @@ -119,7 +119,7 @@ export default function abilityTest() { it('testUiExample',0, async function (done) { console.info("uitest: TestUiExample begin"); //start tested ability - await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ + await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{ console.info('Uitest, start ability finished:' + result) }).catch(err => { console.info('Uitest, start ability failed: ' + err) @@ -128,7 +128,7 @@ export default function abilityTest() { //check top display ability await delegator.getCurrentTopAbility().then((Ability)=>{ console.info("get top ability"); - expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); + expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility'); }) //ui test code //init uidriver @@ -154,20 +154,173 @@ export default function abilityTest() { ## Running the Test Script +### In DevEco Studio + You can run a test script in DevEco Studio in any of the following modes: -- Test package level: All test cases in the test package are executed. -- Test suite level: All test cases defined in the **describe** method are executed. -- Test method level: The specified **it** method, that is, a single test case, is executed. +1. Test package level: All test cases in the test package are executed. + +2. Test suite level: All test cases defined in the **describe** method are executed. + +3. Test method level: The specified **it** method, that is, a single test case, is executed. ![](figures/Execute.PNG) -## Viewing the Test Result +**Viewing the Test Result** After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure. ![](figures/TestResult.PNG) +### In the CLI + +To run a test script in the CLI, execute **aa** commands with different execution control keywords. + +Parameters in aa test commands + +| Keyword | Abbreviation| Description | Example | +| ------------- | ------------ | -------------------------------------- | ---------------------------------- | +| --bundleName | -b | Application bundle name. | - b com.test.example | +| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry | +| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry | +| NA | -s | \ pair.| - s unittest OpenHarmonyTestRunner | + +The framework supports multiple test case execution modes, which are triggered by the key-value pair following the **-s** keyword. The table below lists the available keys and values. + +| Key | Description | Value | Parameter | +| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- | +| unittest | OpenHarmonyTestRunner object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner | +| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt | +| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt | +| itName | Test case to be executed. | {itName} | -s itName testAttributeIt | +| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 | +| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true | +| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | +| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | +| size | Size of the test case to be executed. | small, medium, large | -s size small | + +**Running Commands** + +Configure hdc-related environment variables, and then perform the following: + +- Open the CLI. +- Run the **aa test** commands. + +Example 1: Execute all test cases. + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner +``` + +Example 2: Execute cases in the specified test suites, separated by commas (,). + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class s1,s2 +``` + +Example 3: Execute specified cases in the specified test suites, separated by commas (,). + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0 +``` + +Example 4: Execute all test cases except the specified ones, separated by commas (,). + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s notClass testStop +``` + +Example 5: Execute specified test cases, separated by commas (,). + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s itName stop_0 +``` + +Example 6: Set the timeout interval for executing a test case. + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s timeout 15000 +``` + +Example 7: Enable break-on-error mode. + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s breakOnError true +``` + +Example 8: Execute test cases of the specified type. + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s testType function +``` + +Example 9: Execute test cases at the specified level. + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s level 0 +``` + +Example 10: Execute test cases with the specified level. + +```shell + hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s size small +``` + +**Viewing the Test Result** + +- During test execution in the CLI, the log information similar to the following is displayed: + +``` +OHOS_REPORT_STATUS: class=testStop +OHOS_REPORT_STATUS: current=1 +OHOS_REPORT_STATUS: id=JS +OHOS_REPORT_STATUS: numtests=447 +OHOS_REPORT_STATUS: stream= +OHOS_REPORT_STATUS: test=stop_0 +OHOS_REPORT_STATUS_CODE: 1 + +OHOS_REPORT_STATUS: class=testStop +OHOS_REPORT_STATUS: current=1 +OHOS_REPORT_STATUS: id=JS +OHOS_REPORT_STATUS: numtests=447 +OHOS_REPORT_STATUS: stream= +OHOS_REPORT_STATUS: test=stop_0 +OHOS_REPORT_STATUS_CODE: 0 +OHOS_REPORT_STATUS: consuming=4 +``` + +| Log Field | Description | +| ------- | -------------------------| +| OHOS_REPORT_SUM | Total number of test cases in the current test suite.| +| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.| +| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. | +| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.| +| OHOS_REPORT_STATUS: stream | Error information of the current test case.| +| OHOS_REPORT_STATUS: test| Name of the current test case.| +| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. The options are as follows:
**0**: pass
**1**: error
**2**: fail| +| OHOS_REPORT_STATUS: consuming | Execution duration of the current test case.| + +- After the commands are executed, the log information similar to the following is displayed: + +``` +OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245 +OHOS_REPORT_CODE: 0 + +OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error +OHOS_REPORT_STATUS: taskconsuming=16029 + +``` +| Log Field | Description | +| ------------------| -------------------------| +| run | Total number of test cases in the current test package.| +| Failure | Number of failed test cases.| +| Error | Number of test cases whose execution encounters errors. | +| Pass | Number of passed test cases.| +| Ignore | Number of test cases not executed.| +| taskconsuming| Total time spent in executing the current test case.| + +> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information. + ## FAQs ### FAQs About Unit Test Cases @@ -182,7 +335,7 @@ The logs added to the test case are displayed after the test case execution, rat More than one asynchronous interface is called in the test case.
In principle, logs in the test case are printed before the test case execution is complete. - **Solution** +**Solution** If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode @@ -209,14 +362,18 @@ After the test case execution is complete, the console displays the error messag **Possible Causes** 1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. -2. The time taken for API invocation is longer than the timeout interval set for test case execution. + +2. The time taken for API invocation is longer than the timeout interval set for test case execution. + +3. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until the timeout expires. **Solution** 1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails. -2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. +2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. +3. Check the code logic and assertion result of the test case and make sure that the assertion is passed. ### FAQs About UI Test Cases #### The failure log contains "Get windows failed/GetRootByWindow failed" 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..654f099dad350ce1158c2bfd3f5b01b39d781d4b 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 details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md). **Table 2** APIs of the data consumer @@ -38,7 +38,47 @@ Examples are given below. ### Data Provider Application Development (Only for System Applications) -1. Import the dependencies. +[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override the APIs as required. + +- **onCreate** + + Called by the server to initialize service logic when the **DataShare** client connects to the **DataShareExtensionAbility** server. + +- **insert** + + Inserts data. This API is called when the client requests to insert data. + +- **update** + + Updates data. This API is called when the client requests to update data. + +- **delete** + + Deletes data. This API is called when the client requests to delete data. + +- **query** + + Queries data. This API is called when the client requests to query data. + +- **batchInsert** + + Batch inserts data. This API is called when the client requests to batch insert data. + +- **normalizeUri** + + Converts the URI provided by the client to the URI used by the server. This API can be overridden as required. + +- **denormalizeUri** + + Converts the URI used by the server to the initial URI passed by the client. This API can be overridden as required. + +Before implementing a **DataShare** service, create a **DataShareExtensionAbility** object in the DevEco Studio project as follows: + +1. In the **ets** directory of the **Module** project, right-click and choose **New > Directory** to create a directory named **DataShareAbility**. + +2. Right-click the **DataShareAbility** directory, and choose **New > TypeScript File** to create a file named **DataShareAbility.ts**. + +3. In the **DataShareAbility.ts** file, import the **DataShareExtensionAbility** and other dependencies. ```ts import Extension from '@ohos.application.DataShareExtensionAbility'; @@ -47,9 +87,9 @@ Examples are given below. import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API. +4. Override the **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. -3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. +5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. ```ts const DB_NAME = "DB00.db"; @@ -63,11 +103,11 @@ Examples are given below. export default class DataShareExtAbility extends Extension { private rdbStore_; - - // Override the onCreate() API. + + // Override onCreate(). onCreate(want, callback) { result = this.context.cacheDir + '/datashare.txt' - // Create an RDB. + // Create an RDB store. rdb.getRdbStore(this.context, { name: DB_NAME }, 1, function (err, data) { @@ -79,7 +119,7 @@ Examples are given below. }); } - // Override the query() API. + // Override query(). query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { console.info('invalid predicates'); @@ -102,14 +142,17 @@ Examples are given below. }; ``` -4. Define **DataShareExtensionAbility** in **module.json5**. + - | Field| Description | - | ------------ | ------------------------------------------------------------ | - | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | - | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| - | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | - | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| +6. Define **DataShareExtensionAbility** in **module.json5**. + + | Field | Description | + | --------- | ------------------------------------------------------------ | + | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | + | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | + | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | + | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | + | | | **module.json5 example** @@ -127,30 +170,32 @@ 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'; ``` - + 2. Define the URI string for communicating with the data provider. ```ts // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); ``` - + 3. Create a **DataShareHelper** instance. ```ts 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)=>{ @@ -159,7 +204,7 @@ Examples are given below. } } ``` - + 4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. ```ts @@ -182,7 +227,6 @@ Examples are given below. }); // Delete data. dsHelper.delete(dseUri, predicates, (err, data) => { - console.log("dsHelper delete result: " + data); + console.log("dsHelper delete result: " + data); }); ``` - diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md index 019adeb3fa6850ed5407e0107d5996054ef11de7..53fbd723922ea602e694e0844d2486b13f48538c 100644 --- a/en/application-dev/database/database-datashare-overview.md +++ b/en/application-dev/database/database-datashare-overview.md @@ -4,6 +4,8 @@ The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device. +**DataShare** must be used together with [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md). + Data needs to be shared in a wealth of scenarios. For example, contacts, short message service (SMS), and media gallery always needs to be shared. However, certain data, such as accounts and passwords, cannot be shared. Some data, such as SMS messages, can be queried but not modified by other applications. **DataShare** provides a secure data sharing mechanism for applications in a variety of scenarios. The data provider can directly use the **DataShare** framework to share data with other applications without complex encapsulation. The data consumer only needs to learn and use a set of interfaces because the data access mode does not vary with the data provisioning mode. This greatly reduces the learning time and development difficulty. @@ -16,22 +18,22 @@ Before you get started, familiarize yourself with the following concepts: - Data provider - An application that provides data and implements related services. It is also called a producer or server. + The **DataShareExtensionAbility** based on the stage model implements functions, such as selectively adding, deleting, modifying, and querying data, and opening files. It implements services related to cross-application data sharing. - Data consumer - An application that accesses the data or services provided by a data provider. It is also called a client. + The data consumer uses **DataShareHelper**, a utility class created by [createDataShareHelper()](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper), to access the data provided by the data provider. - **ValuesBucket** One or more data records stored in the form of key-value (KV) pairs. The keys are of the string type. The values can be of the number, string, Boolean, or Unit8Array type. - Result set - + A collection of query results. Flexible data access modes are provided for users to obtain data. - + - Predicate - + Conditions specified for updating, deleting, or querying data in the database. ## Working Principles @@ -41,7 +43,7 @@ Before you get started, familiarize yourself with the following concepts: ![](figures/en_DataShare.png) -- The **DataShareExtAbility** module, as the data provider, implements data sharing between applications. +- The **DataShareExtAbility** module, as the data provider, implements services related to data sharing between applications. - The **DataShareHelper** module, as the data consumer, provides interfaces for accessing data, including adding, deleting, modifying, and querying data. - The data consumer communicates with the data provider using inter-process communication (IPC). The data provider can be implemented through a database or other data storage. diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index ec77d5330b57751e36b3ba2d96b57028c340dd36..5d1bcb0e289ac4fde9c70fc6d0097fdeee287b5d 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -16,7 +16,8 @@ Call **createDistributedObject()** to create a distributed data object instance. **Table 1** API for creating a distributed data object instance -| Package| API| Description| + +| Bundle Name| API| Description| | -------- | -------- | -------- | | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the distributed data object to set.
- **DistributedObject**: returns the distributed data object created. | @@ -25,7 +26,8 @@ Call **createDistributedObject()** to create a distributed data object instance. Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object. **Table 2** API for generating a session ID randomly -| Package| API| Description| + +| Bundle Name| API| Description| | -------- | -------- | -------- | | ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.| @@ -34,9 +36,10 @@ Call **genSessionId()** to generate a session ID randomly. The generated session Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID. **Table 3** API for setting a session ID + | Class| API| Description| | -------- | -------- | -------- | -| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for a distributed data object.
**sessionId**: session ID of a distributed data object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty. | +| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for this distributed data object.
**sessionId**: ID of the distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| ### Observing Data Changes @@ -54,6 +57,7 @@ Call **on()** to subscribe to data changes of a distributed data object. When th Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes. **Table 5** APIs for observing status changes of a distributed data object + | Class| API| Description| | -------- | -------- | -------- | | DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.| @@ -90,86 +94,78 @@ The following example shows how to implement distributed data object synchroniza 2. Apply for the permission. - Add the permissions required (FA model) to the **config.json** file. The sample code is as follows: + Add the permissions required (FA model) to the **config.json** file. - ```json - { + ```json + { "module": { "reqPermissions": [ { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" + "name": "ohos.permission.DISTRIBUTED_DATASYNC" } ] } - } - ``` + } + ``` For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model). - This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: + This permission must also be granted by the user when the application is started for the first time. - ```js - import featureAbility from '@ohos.ability.featureAbility'; + ```js + import featureAbility from '@ohos.ability.featureAbility'; - function grantPermission() { - console.info('grantPermission'); - let context = featureAbility.getContext(); - context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { - console.info(`result.requestCode=${result.requestCode}`) + function grantPermission() { + console.info('grantPermission'); + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { + console.info(`result.requestCode=${result.requestCode}`) - }) - console.info('end grantPermission'); - } + }) + console.info('end grantPermission'); + } - grantPermission(); - ``` + grantPermission(); + ``` 3. Obtain a distributed data object instance. - The sample code is as follows: - ```js - var local_object = distributedObject.createDistributedObject({ - name: undefined, - age: undefined, - isVis: true, - parent: undefined, - list: undefined + let localObject = distributedObject.createDistributedObject({ + name: undefined, + age: undefined, + isVis: true, + parent: undefined, + list: undefined }); - var sessionId = distributedObject.genSessionId(); + let sessionId = distributedObject.genSessionId(); ``` - + 4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects. - The sample code is as follows: - - ```js +```js // Local object - var local_object = distributedObject.createDistributedObject({ - name: "jack", - age: 18, - isVis: true, - parent: { mother: "jack mom", father: "jack Dad" }, - list: [{ mother: "jack mom" }, { father: "jack Dad" }] + let localObject = distributedObject.createDistributedObject({ + name: "jack", + age: 18, + isVis: true, + parent: { mother: "jack mom", father: "jack Dad" }, + list: [{ mother: "jack mom" }, { father: "jack Dad" }] }); - local_object.setSessionId(sessionId); + localObject.setSessionId(sessionId); // Remote object - var remote_object = distributedObject.createDistributedObject({ - name: undefined, - age: undefined, - isVis: true, - parent: undefined, - list: undefined + let remoteObject = distributedObject.createDistributedObject({ + name: undefined, + age: undefined, + isVis: true, + parent: undefined, + list: undefined }); // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. - remote_object.setSessionId(sessionId); + remoteObject.setSessionId(sessionId); ``` -5. Observe the data changes of the distributed data object. - - You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes. - - The sample code is as follows: +5. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be invoked to return the data changes. ```js function changeCallback(sessionId, changeData) { @@ -177,89 +173,78 @@ The following example shows how to implement distributed data object synchroniza if (changeData != null && changeData != undefined) { changeData.forEach(element => { - console.info("changed !" + element + " " + local_object[element]); - }); - } + console.info("changed !" + element + " " + localObject[element]); + }); + } } // To refresh the page in changeCallback, correctly bind (this) to the changeCallback. - local_object.on("change", this.changeCallback.bind(this)); + localObject.on("change", this.changeCallback.bind(this)); ``` -6. Modify attributes of the distributed data object. - - The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). - - The sample code is as follows: +6. Modify attributes of the distributed data object. The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). ```js - local_object.name = "jack"; - local_object.age = 19; - local_object.isVis = false; - local_object.parent = { mother: "jack mom", father: "jack Dad" }; - local_object.list = [{ mother: "jack mom" }, { father: "jack Dad" }]; + localObject.name = "jack"; + localObject.age = 19; + localObject.isVis = false; + localObject.parent = { mother: "jack mom", father: "jack Dad" }; + localObject.list = [{ mother: "jack mom" }, { father: "jack Dad" }]; ``` > **NOTE**
- > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example: + > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. ```js // Supported modification. - local_object.parent = { mother: "mom", father: "dad" }; + localObject.parent = { mother: "mom", father: "dad" }; // Modification not supported. - local_object.parent.mother = "mom"; + localObject.parent.mother = "mom"; ``` 7. Access the distributed data object. Obtain the distributed data object attributes, which are the latest data on the network. - The sample code is as follows: - ```js - console.info("name " + local_object["name"]); +console.info("name " + localObject["name"]); ``` - -8. Unsubscribe from data changes. - - You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. - - The sample code is as follows: + +8. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. ```js - // Unregister the specified data change callback. - local_object.off("change", changeCallback); +// Unregister the specified data change callback. + localObject.off("change", changeCallback); // Unregister all data change callbacks. - local_object.off("change"); + localObject.off("change"); ``` - -9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. - The sample code is as follows: - - ```js - function statusCallback(sessionId, networkId, status) { - this.response += "status changed " + sessionId + " " + status + " " + networkId; - } - local_object.on("status", this.statusCallback); +9. Subscribe to status changes of this distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. + +```js + function statusCallback(sessionId, networkId, status) { + this.response += "status changed " + sessionId + " " + status + " " + networkId; + } + + localObject.on("status", this.statusCallback); ``` - + 10. Save a distributed data object and delete it. ```js // Save a distributed data object. - g_object.save("local").then((result) => { - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); + localObject.save("local").then((result) => { + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); }, (result) => { - console.info("save local failed."); + console.info("save local failed."); }); - // Delete a distributed data object.. - g_object.revokeSave().then((result) => { - console.info("revokeSave success."); + // Revoke the data saving operation. + localObject.revokeSave().then((result) => { + console.info("revokeSave success."); }, (result) => { - console.info("revokeSave failed."); + console.info("revokeSave failed."); }); ``` @@ -267,19 +252,15 @@ The following example shows how to implement distributed data object synchroniza You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered. - The sample code is as follows: - ```js - // Unregister the specified status change callback. - local_object.off("status", this.statusCallback); +// Unregister the specified status change callback. + localObject.off("status", this.statusCallback); // Unregister all status change callbacks. - local_object.off("status"); + localObject.off("status"); ``` - -12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. - - The sample code is as follows: + +12. Remove the distributed data object from the synchronization network. The data changes on the local object will not be synchronized to the removed distributed data object. ```js - local_object.setSessionId(""); +localObject.setSessionId(""); ``` diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index 73f785de4ddccaa1e10c6049066a5f3908d85fc6..b72874536b968593cbb7a3c8d5fd865eb1720b35 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -14,12 +14,12 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | | createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KvManager** object for database management. | -| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.| +| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.| | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. | | delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | -| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Queries data. | +| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Obtains data. | | on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | Subscribes to data changes in the KV store. | -| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | +| sync(deviceIdList: string[], mode: SyncMode, delayMs?: number): void | Triggers database synchronization in manual mode. | ## How to Develop @@ -61,32 +61,32 @@ The following uses a single KV store as an example to describe the development p context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => { console.info('success: ${data}'); }).catch((error) => { - console.info('failed: ${error}'); + console.error('failed: ${error}'); }) } grantPermission(); // Stage model - import Ability from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; let context = null; - - function grantPermission() { - class MainAbility extends Ability { - onWindowStageCreate(windowStage) { + + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage) { let context = this.context; - } + } } - - let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; - context.requestPermissionsFromUser(permissions).then((data) => { + + function grantPermission() { + let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC']; + context.requestPermissionsFromUser(permissions).then((data) => { console.log('success: ${data}'); - }).catch((error) => { - console.log('failed: ${error}'); - }); + }).catch((error) => { + console.error('failed: ${error}'); + }); } - + grantPermission(); ``` @@ -103,9 +103,9 @@ The following uses a single KV store as an example to describe the development p let context = featureAbility.getContext(); // Obtain the context of the stage model. - import AbilityStage from '@ohos.application.Ability'; + import UIAbility from '@ohos.app.ability.UIAbility'; let context = null; - class MainAbility extends AbilityStage{ + class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -119,7 +119,7 @@ The following uses a single KV store as an example to describe the development p } distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { if (err) { - console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`); return; } console.log('Created KVManager successfully'); diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index 897be371287a22f8efe7a8571feec93458d1ba5f..e5c9faa1477565541a94076e2fb568e69b2f5cf6 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -24,7 +24,7 @@ Obtain a **Preferences** instance for data operations. A **Preferences** instanc **Table 1** API for obtaining a **Preferences** instance -| Package | API | Description | +| Bundle Name | API | Description | | --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ohos.data.preferences | getPreferences(context: Context, name: string): Promise\ | Obtains a **Preferences** instance.| @@ -75,7 +75,7 @@ You can use the following APIs to delete a **Preferences** instance or data file **Table 6** APIs for deleting **Preferences** -| Package | API | Description | +| Bundle Name | API | Description | | --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\ | Deletes a **Preferences** instance from the memory and its files from the device.| | ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\ | Removes a **Preferences** instance from the memory to release memory. | @@ -113,10 +113,10 @@ You can use the following APIs to delete a **Preferences** instance or data file ```ts // Obtain the context. - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; let context = null; let preferences = null; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context; } @@ -159,7 +159,7 @@ You can use the following APIs to delete a **Preferences** instance or data file 5. Store data persistently. - Use **flush()** to flush data from the **Preferences** instance to its file. + Use **preferences.flush()** to flush data from the **Preferences** instance to its file. ```js preferences.flush(); @@ -186,7 +186,7 @@ You can use the following APIs to delete a **Preferences** instance or data file console.info("Failed to flush data. Cause: " + err); return; } - console.info("Flushed data successfully."); // The observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) }) ``` 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/database/database-relational-overview.md b/en/application-dev/database/database-relational-overview.md index c78034c76f63fe1f6e8bd338f9595206f8c5eea0..b02f2d646b9dc8e89b1b8a32f2743c8656c6d1f9 100644 --- a/en/application-dev/database/database-relational-overview.md +++ b/en/application-dev/database/database-relational-overview.md @@ -1,18 +1,18 @@ # RDB Overview -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. +A relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing data as in a local database. To satisfy different needs in complicated scenarios, the RDB store offers APIs for performing operations, such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. After an application is uninstalled, the related RDB store will be automatically deleted. You do not need to care about the implementation of the database locking mechanism. -## Basic concepts +## Basic Concepts -- **RDB** +- **RDB store** - A type of database created on the basis of relational models. The RDB stores data in rows and columns. A RDB is also called RDB store. + A type of database created on the basis of relational models. A RDB store holds data in rows and columns. - **Predicate** - A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. + A representation of the property or feature of a data entity, or the relationship between data entities. Predicates are used to define operation conditions. - **Result set** @@ -24,9 +24,9 @@ You do not need to care about the implementation of the database locking mechani ## Working Principles -The RDB provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. +The RDB store provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. -**Figure 1** How RDB works +**Figure 1** Working mechanism ![how-rdb-works](figures/how-rdb-works.png) @@ -38,6 +38,6 @@ The RDB provides common operation APIs for external systems. It uses the SQLite ## Constraints -- A maximum of four connection pools can be connected to an RDB to manage read and write operations. +- An RDB store can be connected to a maximum of four connection pools to manage read and write operations. -- To ensure data accuracy, the RDB supports only one write operation at a time. +- To ensure data accuracy, the RDB store supports only one write operation at a time. diff --git a/en/application-dev/database/figures/en_DataShare.png b/en/application-dev/database/figures/en_DataShare.png index e0243b935e8cc61d61c5f572a20c66aadc5edbd3..b56e96d3bb3ff338f082efd75959d9b15cea6a86 100644 Binary files a/en/application-dev/database/figures/en_DataShare.png and b/en/application-dev/database/figures/en_DataShare.png differ 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/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-file-management.md b/en/application-dev/faqs/faqs-file-management.md index adac2f5a6739a85c04005ef8068369776e90581c..6214cbc6b61aadc0e7501fbf3166d050b46500cb 100644 --- a/en/application-dev/faqs/faqs-file-management.md +++ b/en/application-dev/faqs/faqs-file-management.md @@ -59,7 +59,7 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md). 1. Configure the required permission in the **module.json5** file. - + ``` "requestPermissions": [ { @@ -69,13 +69,16 @@ The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In add ``` 2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded. - + ``` + import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; + private requestPermissions() { let permissionList: Array = [ "ohos.permission.READ_MEDIA" ]; - this.context.requestPermissionsFromUser(permissionList) + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(this.context, permissionList) .then(data => { console.info(`request permission data result = ${data.authResults}`) }) 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-album-guidelines.md b/en/application-dev/file-management/medialibrary-album-guidelines.md index fccb8446d5309dbbff0d0687aae8be5ceaf958c8..f03e11cf3cbc0e94737d3a66214f72dfb0a47ba3 100644 --- a/en/application-dev/file-management/medialibrary-album-guidelines.md +++ b/en/application-dev/file-management/medialibrary-album-guidelines.md @@ -42,8 +42,8 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); - const path = await media.getPublicDirectory(DIR_IMAGE) + let media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_IMAGE); // myAlbum is the path for storing the new file and the name of the new album. media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { if (fileAsset != undefined) { @@ -80,7 +80,7 @@ async function example() { selectionArgs: [], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let album = albumList[0]; album.albumName = 'newAlbum'; @@ -88,7 +88,7 @@ async function example() { album.commitModify().then(function() { console.info("albumRename successfully"); }).catch(function(err){ - console.info("albumRename failed with error:"+ err); + console.info("albumRename failed with error: " + err); }); } ``` diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md index fc9b327031cfee8ea6de601b3c3d268bbf161c53..7e4a1cdaff6cbd76995b295d5f4606f54c35913e 100644 --- a/en/application-dev/file-management/medialibrary-filepath-guidelines.md +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -17,7 +17,7 @@ Before using file paths for development, learn the file formats supported by eac | Directory | Directory Type | Media Type | Description | Supported File Format | | ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ | -| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv | +| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv | | Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv | | Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif | | Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg | @@ -38,7 +38,7 @@ The following describes how to obtain the public directory that stores camera fi ```ts async function example(){ const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; const dicResult = await media.getPublicDirectory(DIR_CAMERA); if (dicResult == 'Camera/') { @@ -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.filesDir](../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. @@ -81,11 +81,11 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o ```ts async function copyPublic2Sandbox() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let sandboxDirPath = globalThis.context.filesDir; - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selections: fileKeyObj.DISPLAY_NAME + '= ?', selectionArgs: ['testFile.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); @@ -108,7 +108,7 @@ async function copyPublic2Sandbox() { ```ts async function copySandbox2Public() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let sandboxDirPath = globalThis.context.filesDir; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; @@ -120,26 +120,26 @@ async function copySandbox2Public() { console.info('createFile failed, message = ' + err); } try { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selections: fileKeyObj.DISPLAY_NAME + '= ?', selectionArgs: ['testFile02.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); var fileAsset = await fetchResult.getFirstObject(); } catch (err) { - console.info('file asset get failed, message = ', err) + console.info('file asset get failed, message = ' + err); } - var fdPub = await fileAsset.open('rw'); - var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); + let fdPub = await fileAsset.open('rw'); + let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); await fileio.copyFile(fdSand, fdPub); await fileio.close(fdPub); await fileio.close(fdSand); let fdPubRead = await fileAsset.open('rw'); try { - var arrayBuffer = new ArrayBuffer(4096); + let arrayBuffer = new ArrayBuffer(4096); await fileio.read(fdPubRead, arrayBuffer); - var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer)); + var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); fileAsset.close(fdPubRead); } catch (err) { console.log('read text failed, message = ', err); @@ -167,12 +167,12 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe let mediaType = mediaLibrary.MediaType.FILE; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); media.createAsset(mediaType, "testFile.text", path).then (function (asset) { - console.info("createAsset successfully:"+ JSON.stringify(asset)); + console.info("createAsset successfully:" + JSON.stringify(asset)); }).catch(function(err){ - console.info("createAsset failed with error:"+ err); + console.info("createAsset failed with error: " + err); }); } ``` @@ -192,10 +192,10 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ```ts async function writeOnlyPromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { - selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selections: fileKeyObj.DISPLAY_NAME + '= ?', selectionArgs: ['testFile.txt'], }; let fetchResult = await media.getFileAssets(fileAssetFetchOp); @@ -218,8 +218,8 @@ async function writeOnlyPromise() { ```ts async function readOnlyPromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); - let fileKeyObj = mediaLibrary.FileKey + let media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; let fileAssetFetchOp = { selections: fileKeyObj.DISPLAY_NAME + '= ?' , selectionArgs: ['testFile.txt'], @@ -233,7 +233,7 @@ async function readOnlyPromise() { let arrayBuffer = new ArrayBuffer(4096); await fileio.read(fd, arrayBuffer); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); - globalThis.fileContent = fileContent + globalThis.fileContent = fileContent; globalThis.fileName = fileAsset.displayName; console.info('file content: ', fileContent); await fileAsset.close(fd); diff --git a/en/application-dev/file-management/medialibrary-overview.md b/en/application-dev/file-management/medialibrary-overview.md index 79f13fe066967607ab15f096fe3ce5478aaa9abe..481a87c8a103fafe4f496d76b3163e7a03f9d28c 100644 --- a/en/application-dev/file-management/medialibrary-overview.md +++ b/en/application-dev/file-management/medialibrary-overview.md @@ -22,7 +22,7 @@ The **mediaLibrary** module provides APIs for you to access and modify media fil > > This development guide applies only to the stage model (available from API version 9). -To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. +To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. Unless otherwise specified, the **MediaLibrary** APIs are used in **pages/index.ets** or custom .ets files of the project code. Before using the **MediaLibrary** APIs to develop features, you must learn how to: @@ -43,7 +43,7 @@ An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrar import mediaLibrary from '@ohos.multimedia.mediaLibrary'; const context = getContext(this); -var media = mediaLibrary.getMediaLibrary(context); +let media = mediaLibrary.getMediaLibrary(context); ``` ## Requesting Permissions @@ -56,7 +56,7 @@ To read and write a **MediaLibrary** instance, you must have the required permis | ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage.| user_grant | | ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant | -After configuring the permissions in the **module.json5** file, the application must call [Context.requestPermissionsFromUser](../reference/apis/js-apis-ability-context.md#abilitycontextrequestpermissionsfromuser) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. +After configuring the permissions in the **module.json5** file, the application must call [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. > **NOTE**
Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**. @@ -73,7 +73,7 @@ After configuring the permissions in the **module.json5** file, the application "reason": "$string:reason", "usedScene": { "abilities": [ - "MainAbility" + "EntryAbility" ], "when": "always" } @@ -83,7 +83,7 @@ After configuring the permissions in the **module.json5** file, the application "reason": "$string:reason", "usedScene": { "abilities": [ - "MainAbility" + "EntryAbility" ], "when": "always" } @@ -93,7 +93,7 @@ After configuring the permissions in the **module.json5** file, the application "reason": "$string:reason", "usedScene": { "abilities": [ - "MainAbility" + "EntryAbility" ], "when": "always" } @@ -103,19 +103,21 @@ After configuring the permissions in the **module.json5** file, the application } ``` -2. Call **requestPermissionsFromUser** to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. +2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. ```ts - import Ability from '@ohos.application.Ability' + import UIAbility from '@ohos.app.ability.UIAbility'; + import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { - var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] - var permissionRequestResult; - this.context.requestPermissionsFromUser(permissions,(err,result) => { - if(err){ + let list : Array = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; + let permissionRequestResult; + let atManager = abilityAccessCtrl.createAtManager(); + atManager.requestPermissionsFromUser(this.context, list, (err, result) => { + if (err) { console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); - }else{ + } else { permissionRequestResult=result; console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); } @@ -123,5 +125,3 @@ After configuring the permissions in the **module.json5** file, the application } } ``` - - diff --git a/en/application-dev/file-management/medialibrary-resource-guidelines.md b/en/application-dev/file-management/medialibrary-resource-guidelines.md index d3ca37dc5be9163a4de8c303aa81704d95056bc1..dea130ff3de563a904684d021a7d8f7f9b514c83 100644 --- a/en/application-dev/file-management/medialibrary-resource-guidelines.md +++ b/en/application-dev/file-management/medialibrary-resource-guidelines.md @@ -33,14 +33,14 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.IMAGE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -64,13 +64,13 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let option = { selections: fileKeyObj.DATE_ADDED + '= ?', selectionArgs: ['2022-8-5'], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -92,15 +92,15 @@ To sort files in descending order by the date when they are added, set **order** ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.IMAGE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], order: fileKeyObj.DATE_ADDED + " DESC", }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -124,14 +124,14 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.IMAGE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.IMAGE; let option = { selections: fileKeyObj.ALBUM_NAME + '= ?', selectionArgs: ['myAlbum'], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getNextObject((err, fileAsset) => { @@ -189,7 +189,7 @@ Complete sample code: ```ts async function getCameraImagePromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let imagesFetchOp = { @@ -236,7 +236,7 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ```ts async function getFirstThumbnailPromise() { const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let imagesFetchOp = { @@ -280,7 +280,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.FILE; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const path = await media.getPublicDirectory(DIR_DOCUMENTS); media.createAsset(mediaType, "testFile.text", path).then ((asset) => { console.info("createAsset successfully:"+ JSON.stringify(asset)); @@ -312,25 +312,25 @@ The following describes how to move the first file in the result set to the recy ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.FILE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); let asset = await fetchFileResult.getFirstObject(); if (asset == undefined) { - console.error('asset not exist') - return + console.error('asset not exist'); + return; } // Void callback. asset.trash(true).then(() => { console.info("trash successfully"); }).catch((err) => { - console.info("trash failed with error:"+ err); + console.info("trash failed with error: " + err); }); } ``` @@ -358,19 +358,19 @@ The following describes how to rename the first file in the result set as **newt ```ts async function example() { - let fileKeyObj = mediaLibrary.FileKey - let fileType = mediaLibrary.MediaType.FILE + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; let option = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], }; const context = getContext(this); - var media = mediaLibrary.getMediaLibrary(context); + let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option); let asset = await fetchFileResult.getFirstObject(); if (asset == undefined) { - console.error('asset not exist') - return + console.error('asset not exist'); + return; } asset.displayName = 'newImage.jpg'; // Void callback. @@ -380,6 +380,6 @@ async function example() { return; } console.log('fileRename successful.'); - }) + }); } ``` 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-capturer.md b/en/application-dev/media/audio-capturer.md index 539de6bb5c5a0723aa68a8994f7ee1970f393a3f..4202b8ea4d78e9c38f43fc77bf7ea503712340d8 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -21,7 +21,7 @@ This following figure shows the audio capturer state transitions. ## Constraints -Before developing the audio data collection feature, configure the **ohos.permission.MICROPHONE** permission for your application. For details about permission configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). +Before developing the audio data collection feature, configure the **ohos.permission.MICROPHONE** permission for your application. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). ## How to Develop @@ -178,16 +178,16 @@ For details about the APIs, see [AudioCapturer in Audio Management](../reference // Obtain the audio capturer information. let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); - + // Obtain the audio stream information. let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); - + // Obtain the audio stream ID. let audioStreamId : number = await audioCapturer.getAudioStreamId(); - + // Obtain the Unix timestamp, in nanoseconds. let audioTime : number = await audioCapturer.getAudioTime(); - + // Obtain a proper minimum buffer size. let bufferSize : number = await audioCapturer.getBuffersize(); ``` 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/media/audio-volume-manager.md b/en/application-dev/media/audio-volume-manager.md index 2063e831f886ae3e6e1fe0a5bd428da194d00227..28ed3dcbc8709609d092a96065a70996b4f487b5 100644 --- a/en/application-dev/media/audio-volume-manager.md +++ b/en/application-dev/media/audio-volume-manager.md @@ -16,7 +16,7 @@ The figure below shows the common APIs provided by the **AudioVolumeManager** mo ## Constraints -Before developing a microphone management application, configure the permission **ohos.permission.MICROPHONE** for the application. To set the microphone state, configure the permission **ohos.permission.MANAGE_AUDIO_CONFIG** (a system permission). For details about the permission configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). +Before developing a microphone management application, configure the permission **ohos.permission.MICROPHONE** for the application. To set the microphone state, configure the permission **ohos.permission.MANAGE_AUDIO_CONFIG** (a system permission). For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). ## How to Develop @@ -38,7 +38,7 @@ For details about the APIs, see [AudioVolumeManager in Audio Management](../refe 2. (Optional) Obtain the volume information and ringer mode. - To obtain the volume information (such as the ringtone, voice call, media, and voice assistant) of an audio stream or obtain the ringer mode (silent, vibration, or normal) of the current device, refer to the code below. For more details, see [Audio Management](../reference/apis/js-apis-audio.md). + To obtain the volume information of an audio stream (such as the ringtone, voice call, media, and voice assistant) or obtain the ringer mode (silent, vibration, or normal) of the current device, refer to the code below. For more details, see [Audio Management](../reference/apis/js-apis-audio.md). ```js import audio from '@ohos.multimedia.audio'; @@ -89,34 +89,34 @@ For details about the APIs, see [AudioVolumeManager in Audio Management](../refe var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); console.info('audioVolumeGroupManager create success.'); } - + async on() { // Subscribe to microphone state changes. await loadVolumeGroupManager(); await audioVolumeGroupManager.audioVolumeGroupManager.on('micStateChange', (micStateChange) => { console.info(`Current microphone status is: ${micStateChange.mute} `); }); } - + async isMicrophoneMute() { // Check whether the microphone is muted. await audioVolumeGroupManager.audioVolumeGroupManager.isMicrophoneMute().then((value) => { console.info(`isMicrophoneMute is: ${value}.`); }); } - + async setMicrophoneMuteTrue() { // Mute the microphone. await loadVolumeGroupManager(); await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(true).then(() => { console.info('setMicrophoneMute to mute.'); }); } - + async setMicrophoneMuteFalse() { // Unmute the microphone. await loadVolumeGroupManager(); await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(false).then(() => { console.info('setMicrophoneMute to not mute.'); }); } - async test(){ // Complete process: Subscribe to microphone state changes, obtain the microphone state, mute the microphone, obtain the microphone state, and unmute the microphone. + async test(){ // Complete process: Subscribe to microphone state changes, obtain the microphone state, mute the microphone, obtain the microphone state, and then unmute the microphone. await on(); await isMicrophoneMute(); await setMicrophoneMuteTrue(); 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-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-page-level.md b/en/application-dev/quick-start/arkts-state-mgmt-page-level.md index 504665688a8eada31cd51531c7cd8c485d795892..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 @@ -97,7 +97,7 @@ The **@Prop** decorated state variable has the following features: **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 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/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/full-sdk-switch-guide.md b/en/application-dev/quick-start/full-sdk-switch-guide.md index f9116ce7ead9c4dbcf15f9d7e6b88a1d8b274d6d..87289c7776cb3dc33b73abc25cb3ef2da06e6eca 100644 --- a/en/application-dev/quick-start/full-sdk-switch-guide.md +++ b/en/application-dev/quick-start/full-sdk-switch-guide.md @@ -4,7 +4,7 @@ Both the public SDK and full SDK are toolkits for application development.
T The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs. -The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **XComponent**, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps. +The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.app.ability.abilityManager.d.ts**, **@ohos.app.form.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps. > **NOTE** > @@ -34,7 +34,7 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo ![image-20220613220702504](figures/en-us_image_0000001655129232.png) - b. Verify that the SDK contains system APIs (such as APIs defined in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**). + b. Verify that the SDK contains system APIs, including the APIs in **@ohos.app.ability.abilityManager.d.ts**, **@ohos.app.form.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**. Note: The criteria for identifying system APIs are subject to the official API documentation. 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/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 13110f9784e44ab0d406917924394ef5b84fc470..3d225b8fd3e7c8941fddce20f678dd6797f6ae8b 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -108,7 +108,7 @@ - [MissionListener](js-apis-inner-application-missionListener.md) - [MissionParameter](js-apis-inner-application-missionParameter.md) - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) - - [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) + - [PermissionRequestResult](js-apis-permissionrequestresult.md) - [ProcessData](js-apis-inner-application-processData.md) - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) - [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.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.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) + - [@ohos.file.fileExtensionInfo (User File Extension Information)](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) @@ -235,22 +242,24 @@ - [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.request](js-apis-request.md) - Connectivity - - [@ohos.bluetooth](js-apis-bluetooth.md) - - [@ohos.connectedTag](js-apis-connectedTag.md) - - [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md) - - [@ohos.nfc.controller](js-apis-nfcController.md) - - [@ohos.nfc.tag](js-apis-nfcTag.md) - - [@ohos.rpc](js-apis-rpc.md) + - [@ohos.bluetooth (Bluetooth)](js-apis-bluetooth.md) + - [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md) + - [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](js-apis-cardEmulation.md) + - [@ohos.nfc.controller (Standard NFC)](js-apis-nfcController.md) + - [@ohos.nfc.tag (Standard NFC Tags)](js-apis-nfcTag.md) + - [@ohos.rpc (RPC)](js-apis-rpc.md) - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) - - [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md) - - [@ohos.wifi](js-apis-wifi.md) - - [@ohos.wifiext](js-apis-wifiext.md) + - [@ohos.wifiManagerExt (WLAN Extension)](js-apis-wifiManagerExt.md) + - [@ohos.wifi (To Be Deprecated)](js-apis-wifi.md) + - [@ohos.wifiext (To Be Deprecated)](js-apis-wifiext.md) - tag - - [nfctech](js-apis-nfctech.md) - - [tagSession](js-apis-tagSession.md) + - [nfctech (Standard NFC Technologies)](js-apis-nfctech.md) + - [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md) - 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,20 +307,25 @@ - [@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) - [@ohos.usb](js-apis-usb.md) - [@ohos.vibrator](js-apis-vibrator.md) - Account Management - - [@ohos.account.appAccount](js-apis-appAccount.md) - - [@ohos.account.distributedAccount](js-apis-distributed-account.md) - - [@ohos.account.osAccount](js-apis-osAccount.md) + - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) + - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) + - [@ohos.account.osAccount (OS Account Management)](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..ff89b62d12e370ccaa046c40576405e8cfe72c22 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 authorization status changes. 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 da7ec7d145779eb5044427fdee758a34f6b33fdc..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** > 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-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 0d2aef3e25aa21eb724c8f74f977d901ea12b290..6f933f9ca9997721df4377be310d6be1cb307e1e 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -1,4 +1,4 @@ -# @ohos.account.appAccount +# @ohos.account.appAccount (App Account Management) The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. @@ -4883,7 +4883,7 @@ Creates an app account implicitly based on the specified account owner. This API | options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | | callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| -### addAccountImplicitlydeprecated +### addAccountImplicitly(deprecated) addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void @@ -4922,7 +4922,7 @@ Authenticates an app account to obtain the authorization token. This API uses an | options | {[key: string]: Object} | Yes | Options for the authentication. | | callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| -### authenticatedeprecated +### authenticate(deprecated) authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void 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 index c6192ce1235b2c75607e92788b68fd635dddaffd..a98dc0e7c402469de49f9b1f4397fc4eecad000d 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 @@ -# @ohos.application.DataShareExtensionAbility +# @ohos.application.DataShareExtensionAbility (DataShare Extension Ability) -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,33 @@ 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| | -------- | -------- | -------- | -------- | -------- | -| context | [ExtensionContext](js-apis-inner-application-extensionContext.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 @@ -43,7 +63,7 @@ Called by the server to initialize service logic when the DataShare client conne **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -55,8 +75,9 @@ let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { onCreate(want, callback) { rdb.getRdbStore(this.context, { - name: DB_NAME - }, 1, function (err, data) { + name: DB_NAME, + securityLevel: rdb.SecurityLevel.S1 + }, function (err, data) { console.log('getRdbStore done, data : ' + data); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { @@ -89,7 +110,7 @@ Inserts data into the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -134,7 +155,7 @@ Updates data in the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -176,7 +197,7 @@ Deletes data from the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -219,7 +240,7 @@ Queries data from the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -264,7 +285,7 @@ Batch inserts data into the database. This API is called by the server and can b **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-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index aa9e1937cd66e83262211280f42f11f468e2d200..b1528f9e2fa160f1616ba9a86370d4a6d721546b 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,4 +1,4 @@ -# @ohos.bluetooth +# @ohos.bluetooth (Bluetooth) The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. 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 7c5bd52bd9ccbc5ee7ad99b8a1e7311ce8c5f8d5..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). 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-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index 329a2e6126de45fe401a748bd580a372cd1dc18e..cc57a0a73d463949911f3a8ff7c501a775ca300f 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,4 +1,4 @@ -# @ohos.nfc.cardEmulation +# @ohos.nfc.cardEmulation (Standard NFC Card Emulation) The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). @@ -16,21 +16,40 @@ import cardEmulation from '@ohos.nfc.cardEmulation'; Enumerates the NFC card emulation types. -**System capability**: SystemCapability.Communication.NFC.Core +> **NOTE** +> +> This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [hasHceCapability](#hashcecapability9). + +**System capability**: SystemCapability.Communication.NFC.CardEmulation | Name| Value| Description| | -------- | -------- | -------- | | HCE | 0 | HCE.| | UICC | 1 | Subscriber identity module (SIM) card emulation.| -| ESE | 2 | embedded Secure Element (eSE) emulation.| +| ESE | 2 | embedded Secure Element (eSE) emulation.| + +## CardType9+ + +Enumerates the types of services used by the card emulation application. -## cardEmulation.isSupported +**System capability**: SystemCapability.Communication.NFC.CardEmulation + +| Name| Value| Description| +| -------- | -------- | -------- | +| PAYMENT | "payment" | Payment type.| +| OTHER | "other" | Other types.| + +## isSupported isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. -**System capability**: SystemCapability.Communication.NFC.Core +> **NOTE** +> +> This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [hasHceCapability](#hashcecapability9). + +**System capability**: SystemCapability.Communication.NFC.CardEmulation **Parameters** @@ -44,68 +63,44 @@ Checks whether a certain type of card emulation is supported. | -------- | -------- | | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| -## HceService8+ - -Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE. +## hasHceCapability9+ -### startHCE8+ +hasHceCapability(): boolean -startHCE(aidList: string[]): boolean +Checks whether HCE is supported. -Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. +**System capability**: SystemCapability.Communication.NFC.CardEmulation **Required permissions**: ohos.permission.NFC_CARD_EMULATION -**System capability**: SystemCapability.Communication.NFC.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | -------- | ---- | ----------------------- | -| aidList | string[] | Yes | AID list to register.| - -### stopHCE8+ - -stopHCE(): boolean - -Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list. +**Return value** -**Required permissions**: ohos.permission.NFC_CARD_EMULATION +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if HCE is supported; returns **false** otherwise.| -**System capability**: SystemCapability.Communication.NFC.Core +## isDefaultService9+ -### on8+ +isDefaultService(elementName: ElementName, type: CardType): boolean -on(type: "hceCmd", callback: AsyncCallback): void; +Checks whether an application is the default application of the specified service type. -Registers a callback to receive APDUs from the peer card reader. +**System capability**: SystemCapability.Communication.NFC.CardEmulation **Required permissions**: ohos.permission.NFC_CARD_EMULATION -**System capability**: SystemCapability.Communication.NFC.Core - **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------------- | -| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | -| callback | AsyncCallback | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.| - -### sendResponse8+ - -sendResponse(responseApdu: number[]): void; - -Sends a response to the peer card reader. - -**Required permissions**: ohos.permission.NFC_CARD_EMULATION - -**System capability**: SystemCapability.Communication.NFC.Core +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md#elementname) | Yes| Application description, which consists of the bundle name and component name.| +| type | [CardType](#cardtype9) | Yes| Card emulation service type.| -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| ------------ | -------- | ---- | -------------------------------------------------- | -| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.| **Example** @@ -118,23 +113,16 @@ if (!isHceSupported) { return; } -// The device supports HCE and transimits APDUs with the remote NFC reader. -var hceService = new cardEmulation.HceService(); -hceService.startHCE([ - "F0010203040506", "A0000000041010" -]); - -hceService.on("hceCmd", (err, res) => { - if(err.data === 0) { - console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); - hceService.sendResponse([0x00,0xa4,0x04,0x00, - 0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44, - 0x46,0x30,0x31,0x00]); - } else { - console.log('callback => Operation hceCmd failed. Cause: ' + err.data); - } -}) - -// Stop HCE when the application exits the NFC card emulation. -hceService.stopHCE(); +var hasHceCap = cardEmulation.hasHceCapability(); +if (!hasHceCap) { + console.log('this device hasHceCapability false, ignore it.'); + return; +} + +var elementName = { + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", +}; +var isDefaultService = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT); +console.log('is the app is default service for this card type: ' + isDefaultService); ``` 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..08df60a00e536dbc715b2017f8301203cbbf9ffc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -0,0 +1,2107 @@ +# @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"); + // The service needs to call getPublicKey() of the upper-level X509Cert object to obtain the public key. + 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 | Public key of the X509 certificate obtained. This object is used only for **verify()** of **X509Cert**.| + +**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 in the YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ format. The date must end with **Z**, which indicates the UTC.| + +**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 X509 certificate validity period, in the YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ format. The value must end with **Z**, which indicates the UTC.| + +**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 X509 certificate validity period, in the YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ format. The value must end with **Z**, which indicates the UTC.| + +**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-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md index 1bfb1231c3c4584fe4d608891bdf2be54458e425..2764d1ee989e84e66ca6301e97c32a9ec2198c0c 100644 --- a/en/application-dev/reference/apis/js-apis-connectedTag.md +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -1,4 +1,4 @@ -# @ohos.connectedTag +# @ohos.connectedTag (Active Tags) The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags. @@ -129,7 +129,7 @@ Writes data to this active tag. This API uses a promise to return the result. ```js import connectedTag from '@ohos.connectedTag'; -var rawData = "010203"; // change it tobe correct. +var rawData = "010203"; // Set it as required. connectedTag.writeNdefTag(rawData).then(() => { console.log("connectedTag writeNdefTag Promise success."); }).catch((err)=> { @@ -159,7 +159,7 @@ Writes data to this active tag. This API uses an asynchronous callback to return ```js import connectedTag from '@ohos.connectedTag'; -var rawData = "010203"; // change it tobe correct. +var rawData = "010203"; // Set it as required. connectedTag.writeNdefTag(rawData, (err)=> { if (err) { console.log("connectedTag writeNdefTag AsyncCallback err: " + err); @@ -220,7 +220,7 @@ connectedTag.on("notify", (err, rfState)=> { var initStatus = connectedTag.init(); console.log("connectedTag init status: " + initStatus); -// Add nfc connecected tag business oprations here... +// Add NFC connected tag business operations here. // connectedTag.writeNdefTag(rawData) // connectedTag.readNdefTag() 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 2c90472a98a38d74e7211eb8dcef2061082f18c8..cf3067e37fd78e9c9d0f3d701b1fdf30cb79c88f 100644 --- a/en/application-dev/reference/apis/js-apis-curve.md +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -1,4 +1,4 @@ -# @ohos.curves +# @ohos.curves (Interpolation Calculation) The **Curves** module provides APIs for interpolation calculation to create step, cubic Bezier, and spring curves. 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 8df3ab1e84ff92e39f31566416a34c4ffb3afa9b..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,4 +1,4 @@ -# @ohos.data.storage +# @ohos.data.storage (Lightweight Data Storage) 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. 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-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 5a4a93c46fbe2492cecf4569f8e4e7db63469371..b1a3996627f88c46e0657102ad33bd6ed27855a6 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,4 +1,4 @@ -# @ohos.account.distributedAccount +# @ohos.account.distributedAccount (Distributed Account Management) The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states. @@ -252,7 +252,7 @@ Sets the distributed account information. This API uses a promise to return the updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void -Updates distributed account information. This API uses an asynchronous callback to return the result. +Updates the distributed account information. This API uses an asynchronous callback to return the result. > **NOTE** > 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..cf090461d612c336d1dbcdbd23de901b0fc239ee 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,22 +258,23 @@ 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** Stage model: ```js -import AbilityStage from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let kvManager; -export default class MyAbilityStage extends AbilityStage { +export default class EntryAbility extends UIAbility { onCreate() { console.log("MyAbilityStage onCreate") let context = this.context @@ -352,12 +283,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}`); } @@ -368,7 +295,7 @@ export default class MyAbilityStage extends AbilityStage { FA model: ```js -import featureAbility from '@ohos.ability.featureAbility' +import featureAbility from '@ohos.ability.featureAbility'; let kvManager; let context = featureAbility.getContext() const kvManagerConfig = { @@ -376,12 +303,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}`); } @@ -405,7 +328,7 @@ Creates and obtains a distributed KV store. This API uses an asynchronous callba | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | options | [Options](#options) | Yes | Configuration of the KV store to create. | -| callback | AsyncCallback<T> | Yes | Callback invoked to return the distributed single or device KV store created. | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the distributed KV store (**SingleKVStore** or **DeviceKVStore**) instance created.| **Error codes** @@ -462,7 +385,7 @@ Creates and obtains a distributed KV store. This API uses a promise to return th | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise<T> | Promise used to return the distributed single or device KV store created.| +| Promise<T> | Promise used to return the distributed KV store (**SingleKVStore** or **DeviceKVStore**) instance created.| **Error codes** @@ -617,7 +540,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 +604,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 +722,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 +2108,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 +2157,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 +2198,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 +2265,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 +2318,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 +2370,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 +2382,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 +2430,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 +2485,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 +2533,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 +2583,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 +2632,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 +2700,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 +2759,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 +2813,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 +2864,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 +2920,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 +2967,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 +3035,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 +3093,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 +3160,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 +3221,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 +3295,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 +3358,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 +3426,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 +3488,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 +3549,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 +3668,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 +3731,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 +3789,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 +3835,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 +3874,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 +3920,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 +4027,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 +4095,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 +4137,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 +4176,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 +4213,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 +4252,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 +4502,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 +4555,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 +4602,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 +4639,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 +4674,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 +4728,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 +4779,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 +4818,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 +4866,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 +4922,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 +4970,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 +5027,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 +5074,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 +5142,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 +5201,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 +5270,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 +5325,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 +5398,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 +5460,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 +5534,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 +5596,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 +5670,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 +5734,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 +5790,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 +5837,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 +5914,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 +5987,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 +6053,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 +6123,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 +6184,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 +6237,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 +6299,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 +6348,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 +6411,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 +6470,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 +6539,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..6f4b524d13bafded2ee0ed7086b1d00e81a43898 100644 --- a/en/application-dev/reference/apis/js-apis-fileAccess.md +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,16 +1,16 @@ -# User File Access and Management +# @ohos.file.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 ```js -import fileAccess from '@ohos.data.fileAccess'; +import fileAccess from '@ohos.file.fileAccess'; ``` ## fileAccess.getFileAccessAbilityInfo @@ -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** @@ -42,7 +38,41 @@ None wantInfos = await fileAccess.getFileAccessAbilityInfo(); console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos)); } catch (error) { - console.error("getFileAccessAbilityInfo failed, error " + error); + console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message); + } + } + ``` + +## fileAccess.getFileAccessAbilityInfo + +getFileAccessAbilityInfo(callback: AsyncCallback<Array<Want>>): void; + +Obtains information about all wants with **extension** set to **fileAcesss** in the system. A want is a basic communication component used to start services. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | callback | AsyncCallback<Array<Want>> | Yes| Promise used to return the **want** information obtained.| + +**Example** + + ```js + async getFileAccessAbilityInfo() { + try { + fileAccess.getFileAccessAbilityInfo(function (err, wantInfos) { + if (err) { + console.error("Failed to getFileAccessAbilityInfo in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos)); + }); + } catch (error) { + console.error("getFileAccessAbilityInfo failed, errCode:" + error.code + ", errMessage:" + error.message); } } ``` @@ -55,28 +85,28 @@ 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(). - // Create a Helper object to interact with the media library service only. + let fileAccessHelper = null; + / / Obtain wantInfos by using getFileAccessAbilityInfo(). + // Create a helper object to interact with the media library service only. let wantInfos = [ { "bundleName": "com.ohos.medialibrary.medialibrarydata", @@ -84,11 +114,12 @@ 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); + console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); } } ``` @@ -97,23 +128,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,11 +153,12 @@ 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"); } catch (error) { - console.error("createFileAccessHelper failed, error " + error); + console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); } } ``` @@ -135,22 +167,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 +188,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; @@ -173,7 +202,51 @@ None rootinfos.push(result.value); } } catch (error) { - console.error("getRoots failed, error " + error); + console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); + } + } + ``` + +## FileAccessHelper.getRoots + +getRoots(callback:AsyncCallback<RootIterator>) : void; + +Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result. +The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext). + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | callback | AsyncCallback<RootIterator> | Yes| Promise used to return the **RootIterator** object obtained.| + +**Example** + + ```js + async getRoots() { + let rootinfos = []; + let isDone = false; + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + fileAccessHelper.getRoots(function (err, rootIterator) { + if (err) { + console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + while (!isDone) { + let result = rootIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + rootinfos.push(result.value); + } + }); + } catch (error) { + console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); } } ``` @@ -182,7 +255,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 +263,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"); @@ -225,7 +298,7 @@ Synchronously obtains the **FileIterator** object of the first-level files (file fileInfos.push(result.value); } } catch (error) { - console.log("listFile failed, error " + error); + console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); } ``` @@ -233,7 +306,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,41 +314,41 @@ 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); + console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message); } ``` @@ -291,27 +364,27 @@ 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** ```js // fileInfoDir specifies the target directory. - // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; + // let filter = { suffix : [".txt", ".jpg", ".xlsx"] }; let fileInfoDir = fileInfos[0]; let subfileInfos = []; 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"); @@ -325,7 +398,7 @@ Synchronously obtains the **FileIterator** object of the next-level files (file subfileInfos.push(result.value); } } catch (error) { - console.error("listFile failed, error " + error); + console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message); } ``` @@ -341,16 +414,16 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -362,7 +435,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,13 +443,13 @@ 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); } } catch (error) { - console.error("scanFile-filter failed, error " + error); + console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message); } ``` @@ -392,33 +465,76 @@ 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. By default, the name of a local file must contain the file name extension.| **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"); return; } - console.log("File created successfully. fileUri: " + JSON.stringify(fileUri)); + console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri)); + } catch (error) { + console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.createFile + +createFile(uri: string, displayName: string, callback: AsyncCallback<string>) : void; + +Creates a file in a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the parent directory for the file to create.| + | displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file created.| + +**Example** + + ```js + // 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" + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + fileAccessHelper.createFile(sourceUri, displayName, function (err, fileUri) { + if (err) { + console.error("Failed to createFile in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("createFile sucess, fileUri: " + JSON.stringify(fileUri)); + }); } catch (error) { - console.error("createFile failed, error " + error); + console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` @@ -434,39 +550,82 @@ 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"); return; } - console.log("Folder created successfully. dirUri: " + JSON.stringify(dirUri)); + console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri)); } catch (error) { - console.error("mkDir failed, error " + error); + console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.mkDir + +mkDir(parentUri: string, displayName: string, callback: AsyncCallback<string>) : void; + +Creates a folder in a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | parentUri | string | Yes| URI of the parent directory for the folder to create.| + | displayName | string | Yes| Name of the folder to create.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the folder created.| + +**Example** + + ```js + // 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" + try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + fileAccessHelper.mkDir(sourceUri, dirName, function (err, dirUri) { + if (err) { + console.error("Failed to mkDir in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("mkDir sucess, dirUri: " + JSON.stringify(dirUri)); + }); + } catch (error) { + console.error("mkDir failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` ## 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,26 +635,68 @@ 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) { - console.error("openFile failed, error " + 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, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.openFile + +openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback<number>) : void; + +Opens a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file to open.| + | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| + | callback | AsyncCallback<number> | Yes| Promise used to return the handle to the file opened.| + +**Example** + + ```js + // 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. + fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ, function (err, fd) { + if (err) { + console.error("Failed to openFile in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("openFile sucess, fd: " + fd); + }); + } catch (error) { + console.error("openFile failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` @@ -511,9 +712,9 @@ Deletes a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to delete.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to delete.| **Return value** @@ -524,14 +725,55 @@ 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) { - console.error("delete failed, error " + error); + } catch (error) { + console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.delete + +delete(uri: string, callback: AsyncCallback<number>) : void; + +Deletes a file or folder. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to delete.| + | callback | AsyncCallback<number> | Yes| Promise used to return the result.| + +**Example** + + ```js + // 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. + fileAccessHelper.delete(targetUri, function (err, code) { + if (err) { + console.error("Failed to delete in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("delete sucess, code: " + code); + }); + } catch (error) { + console.error("delete failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` @@ -547,28 +789,71 @@ 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) { - console.error("move failed, error " + error); + console.log("move sucess, fileUri: " + JSON.stringify(fileUri)); + } catch (error) { + console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.move + +move(sourceFile: string, destFile: string, callback: AsyncCallback<string>) : void; + +Moves a file or folder. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFile | string | Yes| URI of the file or folder to move.| + | destFile | string | Yes| URI of the folder to which the file or folder will be moved.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the file or folder in the destination directory.| + +**Example** + + ```js + // The media library URI is used as an example. + //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the URI in fileInfo. + // 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. + fileAccessHelper.move(sourceFile, destFile, function (err, fileUri) { + if (err) { + console.error("Failed to move in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("move sucess, fileUri: " + JSON.stringify(fileUri)); + }); + } catch (error) { + console.error("move failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` @@ -584,27 +869,69 @@ 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) { - console.error("rename failed, error " + error); + console.log("rename sucess, DestDir: " + JSON.stringify(DestDir)); + } catch (error) { + console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## FileAccessHelper.rename + +rename(uri: string, displayName: string, callback: AsyncCallback<string>) : void; + +Renames a file or folder. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to rename.| + | displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| + | callback | AsyncCallback<string> | Yes| Promise used to return the URI of the renamed file or folder.| + +**Example** + + ```js + // 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. + fileAccessHelper.rename(sourceDir, "testDir", function (err, DestDir) { + if (err) { + console.error("Failed to rename in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + console.log("rename sucess, DestDir: " + JSON.stringify(DestDir)); + }); + } catch (error) { + console.error("rename failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` @@ -620,9 +947,9 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFileUri | string | Yes| URI of the file or folder.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFileUri | string | Yes| URI of the file or folder.| **Return value** @@ -633,24 +960,27 @@ 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) { - console.error("rename failed, error " + error); + } catch (error) { + console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message); }; ``` -## RootIterator.next +## FileAccessHelper.access -next( ) : { value: RootInfo, done: boolean } +access(sourceFileUri: string, callback: AsyncCallback<boolean>) : void; -Obtains the next-level device root directory. **RootIterator** is an iterator object of the device root directory. +Checks whether a file or folder exists. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileService @@ -658,7 +988,44 @@ Obtains the next-level device root directory. **RootIterator** is an iterator ob **Parameters** -None + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFileUri | string | Yes| URI of the file or folder.| + | callback | AsyncCallback<boolean> | Yes| Promise used to return the result.| + +**Example** + + ```js + // 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. + fileAccessHelper.access(sourceDir, function (err, existJudgment) { + if (err) { + console.error("Failed to access in async, errCode:" + err.code + ", errMessage:" + err.message); + return; + } + if (existJudgment) + console.log("sourceDir exists"); + else + console.log("sourceDir does not exist"); + }); + } catch (error) { + console.error("access failed, errCode:" + error.code + ", errMessage:" + error.message); + }; + ``` + +## RootIterator.next + +next( ) : { value: RootInfo, done: boolean } + +Obtains the next-level device root directory. **RootIterator** is an iterator object of the device root directory. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER **Return value** @@ -676,10 +1043,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 +1083,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..f91966f296e6e2e940cac09ba0598092a7653672 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.file.fileExtensionInfo (User File Extension Information) The **fileExtensionInfo** module defines attributes in **RootInfo** and **FileInfo** of the user file access and management module. @@ -10,7 +10,7 @@ The **fileExtensionInfo** module defines attributes in **RootInfo** and **FileIn ## Modules to Import ```js -import fileExtensionInfo from '@ohos.fileExtensionInfo'; +import fileExtensionInfo from '@ohos.file.fileExtensionInfo'; ``` ## fileExtensionInfo.DeviceType @@ -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 | The 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..82e2502f69e2bcba41e1db4bc2fc32ba748a062c 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -1,10 +1,11 @@ -# 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. - +> The APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.fs](./js-apis-file-fs.md). ## Modules to Import @@ -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,18 +3440,19 @@ 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. | | excludeMedia | Boolean | Whether to exclude the files already in Media. | + + \ No newline at end of file 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 36faaa094260d0d86f065040f3a99de323fa3d00..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 diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index f5eaa37329b675708a0f3068ba2d1d8d25202d20..1811193f0a4fee41e8f3ec23d0705ab24e0b43a1 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -1,4 +1,4 @@ -# HUKS +# @ohos.security.huks (HUKS) The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs. @@ -44,7 +44,7 @@ Defines the HUKS handle structure. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ---------------------------------------------------- | | handle | number | Yes | Value of the handle. | -| challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.| +| challenge | Uint8Array | No | Challenge obtained after the [initSession](#huksinitsession9) operation.| ## HuksReturnResult9+ @@ -74,7 +74,7 @@ Generates a key. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| | callback | AsyncCallback\ | Yes | Callback that returns no value.| **Example** @@ -130,7 +130,7 @@ Generates a key. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------ | | keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.| **Example** @@ -288,7 +288,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| | callback | AsyncCallback\ | Yes | Callback that returns no value.| **Example** @@ -356,7 +356,7 @@ Imports a key in plaintext. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ----------------------------------- | | keyAlias | string | Yes | Alias of the key. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.| **Example** @@ -426,7 +426,7 @@ Obtains the certificate used to verify a key. This API uses an asynchronous call | -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** @@ -553,7 +553,7 @@ Obtains the certificate used to verify a key. This API uses a promise to return | Type | Description | | ---------------------------------------------- | --------------------------------------------- | -| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| +| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| **Example** @@ -675,7 +675,7 @@ Imports a wrapped key. This API uses an asynchronous callback to return the resu | ---------------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the wrapped key to import. | | wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.| | callback | AsyncCallback\ | Yes | Callback that returns no value.| **Example** @@ -891,7 +891,7 @@ Imports a wrapped key. This API uses a promise to return the result. | ---------------- | --------------------------- | ---- | --------------------------------------------- | | keyAlias | string | Yes | Alias of the wrapped key to import. | | wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | -| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.| **Example** @@ -926,7 +926,7 @@ Exports a key. This API uses an asynchronous callback to return the result. | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.| **Example** @@ -968,7 +968,7 @@ Exports a key. This API uses a promise to return the result. | Type | Description | | ---------------------------------------------- | ------------------------------------------------------------ | -| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | +| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | **Example** @@ -1005,7 +1005,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| **Example** @@ -1047,7 +1047,7 @@ Obtains key properties. This API uses a promise to return the result. | Type | Description | | ----------------------------------------------- | ------------------------------------------------------------ | -| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | +| Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | **Example** @@ -1126,7 +1126,7 @@ Checks whether a key exists. This API uses a promise to return the result. | Type | Description | | ----------------- | --------------------------------------- | -| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.| **Example** @@ -1163,8 +1163,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback | -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | | keyAlias | string | Yes | Alias of the target key. | | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | -| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.| - +| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle9)> | Yes | Callback invoked to return the handle obtained through the initialization operation.| ## huks.initSession9+ @@ -1185,7 +1184,7 @@ Initializes the data for a key operation. This API uses a promise to return the | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.| +| Promise\<[HuksSessionHandle](#hukssessionhandle9)> | Promise used to return the handle obtained through the initialization operation.| ## huks.updateSession9+ @@ -1201,7 +1200,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to | -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | | handle | number | Yes | Handle of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.| ## huks.updateSession9+ @@ -1219,7 +1218,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to | handle | number | Yes | Handle of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | token | Uint8Array | Yes | Token of the **Update** operation. | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.| ## huks.updateSession9+ @@ -1241,7 +1240,7 @@ Updates the key operation data by segment. This API uses a promise to return the | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| +| Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.| ## huks.finishSession9+ @@ -1258,7 +1257,7 @@ Completes the key operation and releases resources. This API uses an asynchronou | handle | number | Yes | Handle of the **Finish** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | | token | Uint8Array | Yes | Token for the **Finish** operation. | -| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.| ## huks.finishSession9+ @@ -1275,8 +1274,7 @@ Completes the key operation and releases resources. This API uses an asynchronou | handle | number | Yes | Handle of the **Finish** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | | token | Uint8Array | Yes | Token for the **Finish** operation. | -| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| - +| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.| ## huks.finishSession9+ @@ -1298,8 +1296,7 @@ Completes the key operation and releases resources. This API uses a promise to r | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| - +| Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.| ## huks.abortSession9+ @@ -1605,26 +1602,26 @@ For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcod **System capability**: SystemCapability.Security.Huks -| Name | Description | Error Code | -| ---------------------------------------------- | --------------------------- | -------- | -| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 | -| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 | -| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 | -| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 | -| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 | -| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 | -| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 | -| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 | -| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 | -| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 | -| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 | -| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 | -| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 | -| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 | -| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 | -| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 | -| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 | -| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 | +| Name | Value| Description | +| ---------------------------------------------- | -------- |--------------------------- | +| HUKS_ERR_CODE_PERMISSION_FAIL | 201 | Permission verification failed. | +| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | 401 | Invalid parameters are detected. | +| HUKS_ERR_CODE_NOT_SUPPORTED_API | 801 | The API is not supported. | +| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | 12000001 | The feature is not supported. | +| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | 12000002 | Key algorithm parameters are missing. | +| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | 12000003 | Invalid key algorithm parameters are detected. | +| HUKS_ERR_CODE_FILE_OPERATION_FAIL | 12000004 | The file operation failed. | +| HUKS_ERR_CODE_COMMUNICATION_FAIL | 12000005 | The communication failed. | +| HUKS_ERR_CODE_CRYPTO_FAIL | 12000006 | Failed to operate the algorithm library. | +| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 12000007 | Failed to access the key because the key has expired.| +| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | 12000008 | Failed to access the key because the authentication has failed.| +| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | 12000009 | Key access timed out.| +| HUKS_ERR_CODE_SESSION_LIMIT | 12000010 | The number of key operation sessions has reached the limit. | +| HUKS_ERR_CODE_ITEM_NOT_EXIST | 12000011 | The target object does not exist. | +| HUKS_ERR_CODE_EXTERNAL_ERROR | 12000012 | An external error occurs. | +| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | 12000013 | The credential does not exist. | +| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 12000014 | The memory is insufficient. | +| HUKS_ERR_CODE_CALL_SERVICE_FAILED | 12000015 | Failed to call other system services. | ## HuksKeyPurpose @@ -1710,7 +1707,7 @@ Enumerates the key sizes. | HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | | HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | | HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | -| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | +| HUKS_AES_KEY_SIZE_192 | 192 | AES key of 192 bits | | HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | | HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | | HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| @@ -1983,7 +1980,7 @@ generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9). **System capability**: SystemCapability.Security.Huks @@ -1993,7 +1990,7 @@ Generates a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Alias of the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code defined in **HuksResult** is returned.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code defined in **HuksResult** is returned.| **Example** @@ -2035,7 +2032,7 @@ generateKey(keyAlias: string, options: HuksOptions) : Promise\ Generates a key. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem9+](#huksgeneratekeyitem9-1). **System capability**: SystemCapability.Security.Huks @@ -2050,7 +2047,7 @@ Generates a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| **Example** @@ -2082,14 +2079,13 @@ let options = { let result = huks.generateKey(keyAlias, options); ``` - ## huks.deleteKey(deprecated) deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Deletes a key. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9). **System capability**: SystemCapability.Security.Huks @@ -2099,7 +2095,7 @@ Deletes a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | -------------------------------------------------- | | keyAlias | string | Yes | Key alias passed in when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| **Example** @@ -2118,7 +2114,7 @@ deleteKey(keyAlias: string, options: HuksOptions) : Promise\ Deletes a key. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem9+](#huksdeletekeyitem9-1). **System capability**: SystemCapability.Security.Huks @@ -2133,7 +2129,7 @@ Deletes a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| **Example** @@ -2146,14 +2142,13 @@ let emptyOptions = { let result = huks.deleteKey(keyAlias, emptyOptions); ``` - ## huks.importKey(deprecated) importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Imports a key in plaintext. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9). **System capability**: SystemCapability.Security.Huks @@ -2163,7 +2158,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the | -------- | ------------------------ | ---- | ------------------------------------------------- | | keyAlias | string | Yes | Alias of the key.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| **Example** @@ -2213,7 +2208,7 @@ importKey(keyAlias: string, options: HuksOptions) : Promise\ Imports a key in plaintext. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.importKeyItem9+](#huksimportkeyitem9-1). **System capability**: SystemCapability.Security.Huks @@ -2228,7 +2223,7 @@ Imports a key in plaintext. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| **Example** @@ -2274,14 +2269,13 @@ let huksoptions = { let result = huks.importKey(keyAlias, huksoptions); ``` - ## huks.exportKey(deprecated) exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Exports a key. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9). **System capability**: SystemCapability.Security.Huks @@ -2291,7 +2285,7 @@ Exports a key. This API uses an asynchronous callback to return the result. | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.| **Example** @@ -2310,7 +2304,7 @@ exportKey(keyAlias: string, options: HuksOptions) : Promise\ Exports a key. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem9+](#huksexportkeyitem9-1). **System capability**: SystemCapability.Security.Huks @@ -2325,7 +2319,7 @@ Exports a key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | ------------------------------------------------------------ | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | **Example** @@ -2338,14 +2332,13 @@ let emptyOptions = { let result = huks.exportKey(keyAlias, emptyOptions); ``` - ## huks.getKeyProperties(deprecated) getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Obtains key properties. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9). **System capability**: SystemCapability.Security.Huks @@ -2355,7 +2348,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| **Example** @@ -2374,7 +2367,7 @@ getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ Obtains key properties. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties9+](#huksgetkeyitemproperties9-1). **System capability**: SystemCapability.Security.Huks @@ -2402,14 +2395,13 @@ let emptyOptions = { let result = huks.getKeyProperties(keyAlias, emptyOptions); ``` - ## huks.isKeyExist(deprecated) isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void Checks whether a key exists. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9). **System capability**: SystemCapability.Security.Huks @@ -2438,7 +2430,7 @@ isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ Checks whether a key exists. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist9+](#huksiskeyitemexist9-1). **System capability**: SystemCapability.Security.Huks @@ -2453,7 +2445,7 @@ Checks whether a key exists. This API uses a promise to return the result. | Type | Description | | ----------------- | --------------------------------------- | -| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| +| Promise\ | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.| **Example** @@ -2472,7 +2464,7 @@ init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\ **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -2482,8 +2474,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------- | | keyAlias | string | Yes | Alias of the target key.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| -| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.| - +| callback | AsyncCallback\<[HuksHandle](#hukshandledeprecated)> | Yes | Callback invoked to return the handle obtained through the initialization operation.| ## huks.init(deprecated) @@ -2491,7 +2482,7 @@ init(keyAlias: string, options: HuksOptions) : Promise\ Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.initSession9+](#huksinitsession9-1). **System capability**: SystemCapability.Security.Huks @@ -2506,34 +2497,15 @@ Initializes the data for a key operation. This API uses a promise to return the | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.| - +| Promise\<[HuksHandle](#hukshandledeprecated)> | Promise used to return the handle obtained through the initialization operation.| ## huks.update(deprecated) -update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void +update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9). - -**System capability**: SystemCapability.Security.Huks - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------- | -| handle | number | Yes | Handle of the **Update** operation. | -| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| - -## huks.update(deprecated) - -update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void - -Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. - -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-1). **System capability**: SystemCapability.Security.Huks @@ -2544,15 +2516,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to | handle | number | Yes | Handle of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result.| ## huks.update(deprecated) -update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ +update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\; Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.updateSession9+](#huksupdatesession9-2). **System capability**: SystemCapability.Security.Huks @@ -2568,8 +2540,7 @@ Updates the key operation by segment. This API uses a promise to return the resu | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| - +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.| ## huks.finish(deprecated) @@ -2577,7 +2548,7 @@ finish(handle: number, options: HuksOptions, callback: AsyncCallback\ **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9). **System capability**: SystemCapability.Security.Huks @@ -2587,8 +2558,7 @@ Completes the key operation and releases resources. This API uses an asynchronou | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| - +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the result.| ## huks.finish(deprecated) @@ -2596,7 +2566,7 @@ finish(handle: number, options: HuksOptions) : Promise\ Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.finishSession9+](#huksfinishsession9-1). **System capability**: SystemCapability.Security.Huks @@ -2611,8 +2581,7 @@ Completes the key operation and releases resources. This API uses a promise to r | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| - +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.| ## huks.abort(deprecated) @@ -2620,7 +2589,7 @@ abort(handle: number, options: HuksOptions, callback: AsyncCallback\ Aborts the use of the key. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9). **System capability**: SystemCapability.Security.Huks @@ -2630,7 +2599,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the | -------- | ---------------------- | ---- | ------------------------------------- | | handle | number | Yes | Handle of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| -| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| +| callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the result.| **Example** @@ -2731,7 +2700,7 @@ abort(handle: number, options: HuksOptions) : Promise\; Aborts the use of the key. This API uses a promise to return the result. -> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.abortSession9+](#huksabortsession9-1). **System capability**: SystemCapability.Security.Huks @@ -2746,7 +2715,7 @@ Aborts the use of the key. This API uses a promise to return the result. | Type | Description | | ----------------------------------- | -------------------------------------------------- | -| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| +| Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.| **Example** @@ -2847,7 +2816,6 @@ function huksAbort() { } ``` - ## HuksHandle(deprecated) Defines the HUKS handle structure. @@ -2858,8 +2826,7 @@ Defines the HUKS handle structure. | ---------- | ---------------- | ---- | -------- | | errorCode | number | Yes | Error code.| | handle | number | Yes| Value of the handle.| -| token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| - +| token | Uint8Array | No| Challenge obtained after the [init](#huksinitdeprecated) operation.| ## HuksResult(deprecated) @@ -2867,8 +2834,6 @@ Defines the **HuksResult** structure. **System capability**: SystemCapability.Security.Huks - - | Name | Type | Mandatory| Description | | ---------- | ------------------------------- | ---- | ---------------- | | errorCode | number | Yes | Error code. | 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 29a9d739a1cd77bfd030beee38380dc870440444..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'; ``` diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md index 862c39c608ba76b56c23b675c9ef1da19c43331f..d018dd4d9f09add2fe50458f982a99436327acf2 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. @@ -13,6 +13,8 @@ import InputEvent from '@ohos.multimodalInput.inputEvent'; ## InputEvent +Defines an input event. + **System capability**: SystemCapability.MultimodalInput.Input.Core **Parameters** 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..d6514f42799102b15c8e20a978fe71494c281dfd 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. @@ -204,9 +203,8 @@ try { inputMonitor.on("touch", touchEvent => { if (touchEvent.touches.length == 3) {// Three fingers are pressed. return true; - } else { - return false; } + return false; }); } catch (error) { console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); 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..77aa1fe74381a79a6edf3a787da788f1491dc644 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** > @@ -14,6 +14,8 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; ## KeyCode +Enumerates keycodes. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index 3cfb2440033aa8043801e986ade5b0bd28c475d3..75b857b9fb89599280c11008347145061509bbff 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 @@ -14,6 +13,8 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; ## Action +Defines a key action. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | @@ -24,6 +25,8 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; ## Key +Defines a key. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Type| Readable| Writable| Description | @@ -34,6 +37,8 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; ## KeyEvent +Defines a key event. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Type| Readable| Writable| Description | 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 f5b9b27f55ed9d363939bef6f55582423afe4a28..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. 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 f44a0801b9ae1d9d4fec2f4485bf848e8595caa5..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 @@ -# @ohos.mediaquery +# @ohos.mediaquery (Media Query) The **mediaquery** module provides different styles for different media types. diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md index d3d9e4c05e44c68bc7bc58caa5267ddb851cd9bb..6ed09f828cec12108e3833b258fe70eb1ab416ad 100644 --- a/en/application-dev/reference/apis/js-apis-mouseevent.md +++ b/en/application-dev/reference/apis/js-apis-mouseevent.md @@ -1,18 +1,20 @@ -# 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 +Defines a mouse action. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value| Description | @@ -28,6 +30,8 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou ## Button +Enumerates mouse actions. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | @@ -43,6 +47,8 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou ## Axis +Enumerates mouse axis types. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | @@ -54,6 +60,8 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou ## AxisValue +Defines a mouse axis type and value. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Type | Readable | Writable | Description | @@ -64,6 +72,8 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou ## MouseEvent +Defines a mouse event. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Type | Readable | Writable | Description | 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 bff6eb26654f551ab744bfdd7d988cb3b7a8f4f4..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 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 457fa931fd6550a7461d9a5c1f7bb40a41f7fe8b..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 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 9b0ceaead8faa59011bd2ec931e8fb5bd1477cbf..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 diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index 105af3cf95ca3a052faddbb6fe632940169fbcd1..9fede96b4b9bce626e63d715b34113ab8451bf61 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,14 +1,14 @@ -# Standard NFC +# @ohos.nfc.controller (Standard NFC) The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. -> **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** -``` +```js import controller from '@ohos.nfc.controller'; ``` @@ -18,7 +18,7 @@ Enumerates the NFC states. **System capability**: SystemCapability.Communication.NFC.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATE_OFF | 1 | NFC is closed (OFF).| | STATE_TURNING_ON | 2 | NFC is turning on.| @@ -31,6 +31,10 @@ isNfcAvailable(): boolean Checks whether the device supports NFC. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use canIUse("SystemCapability.Communication.NFC.Core"). + **System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -46,6 +50,10 @@ openNfc(): boolean Opens NFC. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [enableNfc](#controllerenablenfc9). + **Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Communication.NFC.Core @@ -56,12 +64,34 @@ Opens NFC. | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +## controller.enableNfc9+ + +enableNfc(): boolean + +Enables NFC. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Communication.NFC.Core + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100101 | NFC state is abnormal in service. | + ## controller.closeNfc closeNfc(): boolean Closes NFC. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [disableNfc](#controllerdisablenfc9). + **Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS **System capability**: SystemCapability.Communication.NFC.Core @@ -72,6 +102,24 @@ Closes NFC. | -------- | ------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +## controller.disableNfc9+ + +disableNfc(): boolean + +Disables NFC. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Communication.NFC.Core + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100101 | NFC state is abnormal in service. | + ## controller.isNfcOpen isNfcOpen(): boolean @@ -108,14 +156,12 @@ Subscribes to NFC state changes. A callback will be invoked to return the NFC st **System capability**: SystemCapability.Communication.NFC.Core -**Parameter** +**Parameters** - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| - | callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| - - +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| +| callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| ## controller.off('nfcStateChange') @@ -125,42 +171,55 @@ Unsubscribes from the NFC state changes. The subscriber will not receive NFC sta **System capability**: SystemCapability.Communication.NFC.Core -**Parameter** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| | callback | Callback<[NfcState](#nfcstate)> | No| Callback for the NFC state changes. This parameter can be left blank.| **Example** - ```js - import controller from '@ohos.nfc.controller'; - - // Define a callback key. - var NFC_STATE_CALLBACK_KEY = "nfcStateChange"; - - // Register the callback to receive NFC state change notifications. - controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> { - if (err) { - console.log("controller on callback err: " + err); - } else { - console.log("controller on callback nfcState: " + nfcState); - } - }); - - // Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. - if (!controller.isNfcOpen()) { - var ret = controller.openNfc(); - console.log("controller openNfc ret: " + ret); - } +```js +import controller from '@ohos.nfc.controller'; - // Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. - if (controller.isNfcOpen()) { - var ret = controller.closeNfc(); - console.log("controller closeNfc ret: " + ret); +// Register a callback to receive the NFC state change notification. +controller.on("nfcStateChange", (err, nfcState)=> { + if (err) { + console.log("controller on callback err: " + err); + } else { + console.log("controller on callback nfcState: " + nfcState); } - - // Unregister the callback. - controller.off(NFC_STATE_CALLBACK_KEY); - ``` +}); + + // Open NFC. The ohos.permission.MANAGE_SECURE_SETTINGS permission is required. +if (!controller.isNfcOpen()) { + var ret = controller.openNfc(); + console.log("controller openNfc ret: " + ret); +} + +// Use 'enableNfc' to enable NFC from API version 9. +try { + controller.enableNfc(); + console.log("controller enableNfc success"); +} catch (busiError) { + console.log("controller enableNfc busiError: " + busiError); +} + +// Close NFC. The ohos.permission.MANAGE_SECURE_SETTINGS permission is required. +if (controller.isNfcOpen()) { + var ret = controller.closeNfc(); + console.log("controller closeNfc ret: " + ret); +} + +// Use 'disableNfc' to disable NFC from API version 9. +try { + controller.disableNfc(); + console.log("controller disableNfc success"); +} catch (busiError) { + console.log("controller disableNfc busiError: " + busiError); +} + +// Unregister the callback. +controller.off("nfcStateChange"); +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 91ef73c07db34721d0cc0f964bb992ce37669ae3..f7f5b2b9362ed875d776c645be7d596de2755bfd 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,4 +1,4 @@ -# @ohos.nfc.tag +# @ohos.nfc.tag (Standard NFC Tags) The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. @@ -48,11 +48,11 @@ Before developing applications related to tag read and write, you must declare N } ``` > **CAUTION**
-1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. -2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed. -3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure. -4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. - +> +> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. +> - The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed. +> - The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure. +> - The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. ## **Modules to Import** ```js @@ -73,7 +73,7 @@ onCreate(want, launchParam) { try { tagInfo = tag.getTagInfo(want); } catch (error) { - console.log("tag.getTagInfo catched error: " + error); + console.log("tag.getTagInfo caught error: " + error); } if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); @@ -100,7 +100,7 @@ onCreate(want, launchParam) { try { nfcA = tag.getNfcATag(taginfo); } catch (error) { - console.log("tag.getNfcATag catched error: " + error); + console.log("tag.getNfcATag caught error: " + error); } // Other code to read or write this tag. } @@ -111,7 +111,7 @@ onCreate(want, launchParam) { try { isoDep = tag.getIsoDep(taginfo); } catch (error) { - console.log("tag.getIsoDep catched error: " + error); + console.log("tag.getIsoDep caught error: " + error); } // Other code to read or write this tag. } @@ -126,9 +126,16 @@ getNfcATag(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. -**Required permissions**: ohos.permission.NFC_TAG +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcA](#taggetnfca9). + +**System capability**: SystemCapability.Communication.NFC.Tag -**System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. **Return value** @@ -136,15 +143,70 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC- | -------- | -------- | | [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.| +## tag.getNfcA9+ + +getNfcA(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) + +Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getNfcBTag getNfcBTag(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. -**Required permissions**: ohos.permission.NFC_TAG +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcB](#taggetnfcb9). + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.| + +## tag.getNfcB9+ + +getNfcB(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) -**System capability**: SystemCapability.Communication.NFC.Core +Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. **Return value** @@ -152,15 +214,30 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getNfcFTag getNfcFTag(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. -**Required permissions**: ohos.permission.NFC_TAG +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcF](#taggetnfcf9). + +**System capability**: SystemCapability.Communication.NFC.Tag -**System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. **Return value** @@ -168,15 +245,70 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.| +## tag.getNfcF9+ + +getNfcF(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) + +Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getNfcVTag getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. -**Required permissions**: ohos.permission.NFC_TAG +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcV](#taggetnfcv9). -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| + +## tag.getNfcV9+ + +getNfcV(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) + +Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. **Return value** @@ -184,19 +316,27 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getIsoDep9+ getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | **Return value** @@ -218,13 +358,13 @@ getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | **Return value** @@ -246,7 +386,7 @@ getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfcte Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -274,12 +414,12 @@ getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------------------------------- | -| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | **Return value** @@ -301,7 +441,7 @@ getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfc Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -323,7 +463,7 @@ getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo) Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -344,7 +484,7 @@ makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); Creates an NDEF record based on the specified URI. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -373,7 +513,7 @@ try { console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); } } catch (busiError) { - console.log("ndefMessage makeUriRecord catched busiError: " + busiError); + console.log("ndefMessage makeUriRecord caught busiError: " + busiError); } ``` @@ -383,7 +523,7 @@ makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); Creates an NDEF record based on the specified text data and encoding type. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -414,7 +554,7 @@ try { console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); } } catch (busiError) { - console.log("ndefMessage makeTextRecord catched busiError: " + busiError); + console.log("ndefMessage makeTextRecord caught busiError: " + busiError); } ``` @@ -425,7 +565,7 @@ makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9) Creates an NDEF record based on the specified MIME data and type. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -456,7 +596,7 @@ try { console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); } } catch (busiError) { - console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); + console.log("ndefMessage makeMimeRecord caught busiError: " + busiError); } ``` ## tag.ndef.makeExternalRecord9+ @@ -465,7 +605,7 @@ makeExternalRecord(domainName: string, type: string, externalData: number[]): [N Creates an NDEF record based on application-specific data. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -498,7 +638,7 @@ try { console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); } } catch (busiError) { - console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); + console.log("ndefMessage makeExternalRecord caught busiError: " + busiError); } ``` @@ -508,7 +648,7 @@ messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): num Converts an NDEF message to bytes. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -540,7 +680,7 @@ try { let rawData2 = tag.ndef.messageToBytes(ndefMessage); console.log("ndefMessage messageToBytes rawData2: " + rawData2); } catch (busiError) { - console.log("ndefMessage messageToBytes catched busiError: " + busiError); + console.log("ndefMessage messageToBytes caught busiError: " + busiError); } ``` ## tag.ndef.createNdefMessage9+ @@ -549,7 +689,7 @@ createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9 Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -583,7 +723,7 @@ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#n Creates an NDEF message from the NDEF records list. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -618,7 +758,7 @@ try { Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Required permissions**: ohos.permission.NFC_TAG @@ -626,14 +766,15 @@ Defines the **TagInfo** object, which provides information about the tag technol | -------- | -------- | -------- | -------- | -------- | | uid9+ | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| | technology9+ | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| -| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#taginfo) instead.| +| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [technology](#taginfo).| | extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| | tagRfDiscId9+ | number | Yes| No| ID allocated when the tag is discovered.
**System API**: This is a system API.| | remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| + ## NdefRecord9+ Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Type**| **Readable**| **Writable**| **Description**| | -------- | -------- | -------- | -------- | -------- | @@ -645,7 +786,7 @@ Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. ## Technology Type Definition Enumerates the tag technology types. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | @@ -662,7 +803,7 @@ Enumerates the tag technology types. ## TnfType9+ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | @@ -677,7 +818,7 @@ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. ## NDEF Record RTD Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | @@ -687,7 +828,7 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ## NfcForumType9+ Enumerates the NFC Forum tag types. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | @@ -700,7 +841,7 @@ Enumerates the NFC Forum tag types. ## MifareClassicType9+ Enumerates the MIFARE Classic tag types. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | @@ -710,9 +851,9 @@ Enumerates the MIFARE Classic tag types. | TYPE_PRO | 3 | MIFARE Pro.| ## MifareClassicSize9+ -Enumerates the sizes of MIFARE Classic tags. +Enumerates the sizes of a MIFARE Classic tag. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | @@ -724,11 +865,11 @@ Enumerates the sizes of MIFARE Classic tags. ## MifareUltralightType9+ Enumerates the MIFARE Ultralight tag types. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | TYPE_UNKNOWN | 0 | Unknown type.| | TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| | TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| - + diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index e28864fc7bd2002838b7ae982bcb7b5269e2c086..b4f4905ccc0b3a6310f74ea700d16b3e6df519ea 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1,4 +1,4 @@ -# nfctech +# nfctech (Standard NFC Technologies) The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. @@ -26,9 +26,7 @@ getSak(): number Obtains the SAK value of this NFC-A tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -52,9 +50,7 @@ getAtqa(): number[] Obtains the ATQA value of this NFC-A tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -86,9 +82,7 @@ getRespAppData(): number[] Obtains the application data of this NFC-B tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -112,9 +106,7 @@ getRespProtocol(): number[] Obtains the protocol information of this NFC-B tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -146,9 +138,7 @@ getSystemCode(): number[] Obtains the system code from this NFC-F tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -172,9 +162,7 @@ getPmm(): number[] Obtains the PMm (consisting of the IC code and manufacturer parameters) information from this NFC-F tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -206,9 +194,7 @@ getResponseFlags(): number Obtains the response flags from this NFC-V tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -232,9 +218,7 @@ getDsfId(): number Obtains the data storage format identifier (DSFID) from this NFC-V tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -266,7 +250,7 @@ getHistoricalBytes(): number[] Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -290,7 +274,7 @@ getHiLayerResponse(): number[] Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -316,7 +300,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -367,7 +351,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -419,7 +403,7 @@ getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] Obtains all NDEF records. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -454,7 +438,7 @@ getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) Obtains the NDEF tag type. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -478,7 +462,7 @@ getNdefMessage(): [NdefMessage](#ndefmessage9) Obtains the NDEF message from this NDEF tag. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -501,7 +485,7 @@ isNdefWritable(): boolean; Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -527,7 +511,7 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -577,7 +561,7 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -629,7 +613,7 @@ Writes an NDEF message to this tag. This API uses a promise to return the result **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -682,7 +666,7 @@ Writes an NDEF message to this tag. This API uses an asynchronous callback to re **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -738,7 +722,7 @@ Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -772,7 +756,7 @@ Sets this NDEF tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Error codes** @@ -816,7 +800,7 @@ Sets this NDEF tag to read-only. This API uses an asynchronous callback to retur **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -866,7 +850,7 @@ getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): Converts an NFC Forum Type tag to a string defined in the NFC Forum. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -911,7 +895,7 @@ Authenticates a sector using a key. The sector can be accessed only after the au **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -965,7 +949,7 @@ Authenticates a sector using a key. The sector can be accessed only after the au **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1021,7 +1005,7 @@ Reads a block (16 bytes) on this tag. This API uses a promise to return the resu **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1078,14 +1062,14 @@ Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read.| **Error codes** @@ -1132,7 +1116,7 @@ Writes data to a block on this tag. This API uses a promise to return the result **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1186,7 +1170,7 @@ Writes data to a block on this tag. This API uses an asynchronous callback to re **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1243,7 +1227,7 @@ Increments a block with data. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1296,7 +1280,7 @@ Increments a block with data. This API uses an asynchronous callback to return t **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1352,7 +1336,7 @@ Decrements a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1405,7 +1389,7 @@ Decrements a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1461,7 +1445,7 @@ Transfers data from the temporary register to a block. This API uses a promise t **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1512,7 +1496,7 @@ Transfers data from the temporary register to a block. This API uses an asynchro **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1566,7 +1550,7 @@ Restores data in the temporary register from a block. This API uses a promise to **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1617,7 +1601,7 @@ Restores data in the temporary register from a block. This API uses an asynchron **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1669,7 +1653,7 @@ getSectorCount(): number Obtains the number of sectors in this MIFARE Classic tag. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -1693,7 +1677,7 @@ getBlockCountInSector(sectorIndex: number): number Obtains the number of blocks in a sector. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1729,7 +1713,7 @@ getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -1753,7 +1737,7 @@ getTagSize(): number Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -1777,7 +1761,7 @@ isEmulatedTag(): boolean Checks whether it is an emulated tag. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -1801,7 +1785,7 @@ getBlockIndex(sectorIndex: number): number Obtains the index of the first block in a sector. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1835,9 +1819,9 @@ try { getSectorIndex(blockIndex: number): number -Obtains the index of a sector that holds the specified block. +Obtains the index of the sector that holds the specified block. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1883,7 +1867,7 @@ Reads four pages (4 bytes per page) from this tag. This API uses a promise to re **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1941,7 +1925,7 @@ Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -1995,7 +1979,7 @@ Writes one page (4 bytes) of data to this tag. This API uses a promise to return **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -2048,7 +2032,7 @@ Writes one page (4 bytes) of data to this tag. This API uses an asynchronous cal **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -2102,7 +2086,7 @@ getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) Obtains the type of this MIFARE Ultralight tag. -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -2136,7 +2120,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -2190,7 +2174,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -2245,7 +2229,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -2299,7 +2283,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 9fdf5e1f345b68fcd99e6e027cfb0c44d5da29d8..06bd296eab73896a8034d3d8245bf05e09d9548c 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,4 +1,4 @@ -# @ohos.notification +# @ohos.notification (Notification) The **Notification** module provides notification management capabilities, covering notifications, notification slots, notification subscription, notification enabled status, and notification badge status. @@ -41,7 +41,7 @@ function publishCallback(err) { } } // NotificationRequest object -var notificationRequest = { +let notificationRequest = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -51,8 +51,8 @@ var notificationRequest = { additionalText: "test_additionalText" } } -} -Notification.publish(notificationRequest, publishCallback) +}; +Notification.publish(notificationRequest, publishCallback); ``` @@ -75,7 +75,7 @@ Publishes a notification. This API uses a promise to return the result. ```js // NotificationRequest object -var notificationRequest = { +let notificationRequest = { notificationId: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -85,7 +85,7 @@ var notificationRequest = { additionalText: "test_additionalText" } } -} +}; Notification.publish(notificationRequest).then(() => { console.info("publish success"); }); @@ -124,9 +124,9 @@ function publishCallback(err) { } } // User ID -var userId = 1 +let userId = 1; // NotificationRequest object -var notificationRequest = { +let notificationRequest = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -136,7 +136,7 @@ var notificationRequest = { additionalText: "test_additionalText" } } -} +}; Notification.publish(notificationRequest, userId, publishCallback); ``` @@ -162,7 +162,7 @@ Publishes a notification to a specified user. This API uses a promise to return **Example** ```js -var notificationRequest = { +let notificationRequest = { notificationId: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -172,9 +172,9 @@ var notificationRequest = { additionalText: "test_additionalText" } } -} +}; -var userId = 1 +let userId = 1; Notification.publish(notificationRequest, userId).then(() => { console.info("publish success"); @@ -209,7 +209,7 @@ function cancelCallback(err) { console.info("cancel success"); } } -Notification.cancel(0, "label", cancelCallback) +Notification.cancel(0, "label", cancelCallback); ``` @@ -265,7 +265,7 @@ function cancelCallback(err) { console.info("cancel success"); } } -Notification.cancel(0, cancelCallback) +Notification.cancel(0, cancelCallback); ``` @@ -295,7 +295,7 @@ function cancelAllCallback(err) { console.info("cancelAll success"); } } -Notification.cancelAll(cancelAllCallback) +Notification.cancelAll(cancelAllCallback); ``` @@ -349,10 +349,10 @@ function addSlotCallBack(err) { } } // NotificationSlot object -var notificationSlot = { +let notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION -} -Notification.addSlot(notificationSlot, addSlotCallBack) +}; +Notification.addSlot(notificationSlot, addSlotCallBack); ``` @@ -379,9 +379,9 @@ Adds a notification slot. This API uses a promise to return the result. ```js // NotificationSlot object -var notificationSlot = { +let notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION -} +}; Notification.addSlot(notificationSlot).then(() => { console.info("addSlot success"); }); @@ -415,7 +415,7 @@ function addSlotCallBack(err) { console.info("addSlot success"); } } -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack); ``` @@ -475,14 +475,14 @@ function addSlotsCallBack(err) { } } // NotificationSlot object -var notificationSlot = { +let notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION -} +}; // NotificationSlotArray object -var notificationSlotArray = new Array(); +let notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray, addSlotsCallBack) +Notification.addSlots(notificationSlotArray, addSlotsCallBack); ``` @@ -509,11 +509,11 @@ Adds an array of notification slots. This API uses a promise to return the resul ```js // NotificationSlot object -var notificationSlot = { +let notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION -} +}; // NotificationSlotArray object -var notificationSlotArray = new Array(); +let notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { @@ -549,8 +549,8 @@ function getSlotCallback(err, data) { console.info("getSlot success"); } } -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.getSlot(slotType, getSlotCallback) +let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.getSlot(slotType, getSlotCallback); ``` @@ -578,7 +578,7 @@ Obtains a notification slot of a specified type. This API uses a promise to retu **Example** ```js -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { console.info("getSlot success, data: " + JSON.stringify(data)); }); @@ -611,7 +611,7 @@ function getSlotsCallback(err, data) { console.info("getSlots success"); } } -Notification.getSlots(getSlotsCallback) +Notification.getSlots(getSlotsCallback); ``` @@ -666,8 +666,8 @@ function removeSlotCallback(err) { console.info("removeSlot success"); } } -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType,removeSlotCallback) +let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.removeSlot(slotType,removeSlotCallback); ``` @@ -689,7 +689,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu **Example** ```js -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +let slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { console.info("removeSlot success"); }); @@ -721,7 +721,7 @@ function removeAllCallBack(err) { console.info("removeAllSlots success"); } } -Notification.removeAllSlots(removeAllCallBack) +Notification.removeAllSlots(removeAllCallBack); ``` @@ -778,12 +778,12 @@ function subscribeCallback(err) { function onConsumeCallback(data) { console.info("Consume callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onConsume: onConsumeCallback -} -var info = { +}; +let info = { bundleNames: ["bundleName1", "bundleName2"] -} +}; Notification.subscribe(subscriber, info, subscribeCallback); ``` @@ -821,9 +821,9 @@ function subscribeCallback(err) { function onConsumeCallback(data) { console.info("Consume callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onConsume: onConsumeCallback -} +}; Notification.subscribe(subscriber, subscribeCallback); ``` @@ -854,7 +854,7 @@ Subscribes to a notification with the subscription information specified. This A function onConsumeCallback(data) { console.info("Consume callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { @@ -896,9 +896,9 @@ function unsubscribeCallback(err) { function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onDisconnect: onDisconnectCallback -} +}; Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -928,7 +928,7 @@ Unsubscribes from a notification. This API uses a promise to return the result. function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onDisconnect: onDisconnectCallback }; Notification.unsubscribe(subscriber).then(() => { @@ -968,9 +968,9 @@ function enableNotificationCallback(err) { console.info("enableNotification success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.enableNotification(bundle, false, enableNotificationCallback); ``` @@ -998,9 +998,9 @@ Sets whether to enable notification for a specified application. This API uses a **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.enableNotification(bundle, false).then(() => { console.info("enableNotification success"); }); @@ -1037,9 +1037,9 @@ function isNotificationEnabledCallback(err, data) { console.info("isNotificationEnabled success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` @@ -1072,9 +1072,9 @@ Checks whether notification is enabled for a specified application. This API use **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.isNotificationEnabled(bundle).then((data) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); @@ -1180,9 +1180,9 @@ function displayBadgeCallback(err) { console.info("displayBadge success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.displayBadge(bundle, false, displayBadgeCallback); ``` @@ -1210,9 +1210,9 @@ Sets whether to enable the notification badge for a specified application. This **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.displayBadge(bundle, false).then(() => { console.info("displayBadge success"); }); @@ -1249,9 +1249,9 @@ function isBadgeDisplayedCallback(err, data) { console.info("isBadgeDisplayed success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); ``` @@ -1284,9 +1284,9 @@ Checks whether the notification badge is enabled for a specified application. Th **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.isBadgeDisplayed(bundle).then((data) => { console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); }); @@ -1324,12 +1324,12 @@ function setSlotByBundleCallback(err) { console.info("setSlotByBundle success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationSlot = { +}; +let notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION -} +}; Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); ``` @@ -1357,12 +1357,12 @@ Sets the notification slot for a specified application. This API uses a promise **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationSlot = { +}; +let notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION -} +}; Notification.setSlotByBundle(bundle, notificationSlot).then(() => { console.info("setSlotByBundle success"); }); @@ -1399,9 +1399,9 @@ function getSlotsByBundleCallback(err, data) { console.info("getSlotsByBundle success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); ``` @@ -1434,9 +1434,9 @@ Obtains the notification slots of a specified application. This API uses a promi **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.getSlotsByBundle(bundle).then((data) => { console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); }); @@ -1473,9 +1473,9 @@ function getSlotNumByBundleCallback(err, data) { console.info("getSlotNumByBundle success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` @@ -1508,9 +1508,9 @@ Obtains the number of notification slots of a specified application. This API us **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.getSlotNumByBundle(bundle).then((data) => { console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); }); @@ -1549,14 +1549,14 @@ function removeCallback(err) { console.info("remove success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationKey = { +}; +let notificationKey = { id: 0, label: "label", -} -var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +}; +let reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(bundle, notificationKey, reason, removeCallback); ``` @@ -1585,14 +1585,14 @@ Removes a notification for a specified bundle. This API uses a promise to return **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationKey = { +}; +let notificationKey = { id: 0, label: "label", -} -var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +}; +let reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(bundle, notificationKey, reason).then(() => { console.info("remove success"); }); @@ -1623,7 +1623,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Example** ```js -var hashCode = 'hashCode' +let hashCode = 'hashCode'; function removeCallback(err) { if (err.code) { @@ -1632,7 +1632,7 @@ function removeCallback(err) { console.info("remove success"); } } -var reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; +let reason = Notification.RemoveReason.CANCEL_REASON_REMOVE; Notification.remove(hashCode, reason, removeCallback); ``` @@ -1660,8 +1660,8 @@ Removes a notification for a specified bundle. This API uses a promise to return **Example** ```js -var hashCode = 'hashCode' -var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; +let hashCode = 'hashCode'; +let reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(hashCode, reason).then(() => { console.info("remove success"); }); @@ -1698,9 +1698,9 @@ function removeAllCallback(err) { console.info("removeAll success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.removeAll(bundle, removeAllCallback); ``` @@ -1797,7 +1797,7 @@ function removeAllCallback(err) { } } -var userId = 1 +let userId = 1; Notification.removeAll(userId, removeAllCallback); ``` @@ -1822,7 +1822,7 @@ Removes all notifications for a specified user. This API uses a promise to retur **Example** ```js -var userId = 1 +let userId = 1; Notification.removeAll(userId).then(() => { console.info("removeAll success"); }); @@ -2025,7 +2025,7 @@ function cancelGroupCallback(err) { } } -var groupName = "GroupName"; +let groupName = "GroupName"; Notification.cancelGroup(groupName, cancelGroupCallback); ``` @@ -2049,7 +2049,7 @@ Cancels notifications under a notification group of this application. This API u **Example** ```js -var groupName = "GroupName"; +let groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { console.info("cancelGroup success"); }); @@ -2088,8 +2088,8 @@ function removeGroupByBundleCallback(err) { } } -var bundleOption = {bundle: "Bundle"}; -var groupName = "GroupName"; +let bundleOption = {bundle: "Bundle"}; +let groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); ``` @@ -2118,8 +2118,8 @@ Removes notifications under a notification group of a specified application. Thi **Example** ```js -var bundleOption = {bundle: "Bundle"}; -var groupName = "GroupName"; +let bundleOption = {bundle: "Bundle"}; +let groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { console.info("removeGroupByBundle success"); }); @@ -2157,11 +2157,11 @@ function setDoNotDisturbDateCallback(err) { } } -var doNotDisturbDate = { +let doNotDisturbDate = { type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); ``` @@ -2189,11 +2189,11 @@ Sets the DND time. This API uses a promise to return the result. **Example** ```js -var doNotDisturbDate = { +let doNotDisturbDate = { type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { console.info("setDoNotDisturbDate success"); }); @@ -2231,13 +2231,13 @@ function setDoNotDisturbDateCallback(err) { } } -var doNotDisturbDate = { +let doNotDisturbDate = { type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; -var userId = 1 +let userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` @@ -2265,13 +2265,13 @@ Sets the DND time for a specified user. This API uses a promise to return the re **Example** ```js -var doNotDisturbDate = { +let doNotDisturbDate = { type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; -var userId = 1 +let userId = 1; Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { console.info("setDoNotDisturbDate success"); @@ -2370,7 +2370,7 @@ function getDoNotDisturbDateCallback(err,data) { } } -var userId = 1 +let userId = 1; Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); ``` @@ -2404,7 +2404,7 @@ Obtains the DND time of a specified user. This API uses a promise to return the **Example** ```js -var userId = 1 +let userId = 1; Notification.getDoNotDisturbDate(userId).then((data) => { console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); @@ -2492,7 +2492,7 @@ Checks whether a specified template exists. This API uses an asynchronous callba **Example** ```javascript -var templateName = 'process'; +let templateName = 'process'; function isSupportTemplateCallback(err, data) { if (err.code) { console.info("isSupportTemplate failed " + JSON.stringify(err)); @@ -2529,7 +2529,7 @@ Checks whether a specified template exists. This API uses a promise to return th **Example** ```javascript -var templateName = 'process'; +let templateName = 'process'; Notification.isSupportTemplate(templateName).then((data) => { console.info("isSupportTemplate success, data: " + JSON.stringify(data)); @@ -2615,7 +2615,7 @@ function enabledNotificationCallback(err) { } }; -var enable = true +let enable = true; Notification.enableDistributed(enable, enabledNotificationCallback); ``` @@ -2643,7 +2643,7 @@ Sets whether this device supports distributed notifications. This API uses a pro **Example** ```javascript -var enable = true +let enable = true; Notification.enableDistributed(enable).then(() => { console.info("enableDistributed success"); }); @@ -2734,11 +2734,11 @@ function enableDistributedByBundleCallback(err) { } }; -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; -var enable = true +let enable = true; Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundleCallback); ``` @@ -2767,11 +2767,11 @@ Sets whether a specified application supports distributed notifications. This AP **Example** ```javascript -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; -var enable = true +let enable = true; Notification.enableDistributedByBundle(bundle, enable).then(() => { console.info("enableDistributedByBundle success"); }); @@ -2807,9 +2807,9 @@ function isDistributedEnabledByBundleCallback(err, data) { } }; -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); ``` @@ -2843,9 +2843,9 @@ Checks whether a specified application supports distributed notifications. This **Example** ```javascript -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; Notification.isDistributedEnabledByBundle(bundle).then((data) => { console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); @@ -2947,9 +2947,9 @@ function callback(err) { } } // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; // NotificationRequest object let request = { id: 1, @@ -2961,7 +2961,7 @@ let request = { additionalText: "test_additionalText" } } -} +}; Notification.publishAsBundle(request, representativeBundle, userId, callback); ``` @@ -2991,11 +2991,11 @@ Publishes a notification through the reminder agent. This API uses a promise to ```js // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; // NotificationRequest object -var request = { +let request = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -3005,7 +3005,7 @@ var request = { additionalText: "test_additionalText" } } -} +}; Notification.publishAsBundle(request, representativeBundle, userId).then(() => { console.info("publishAsBundle success"); @@ -3047,9 +3047,9 @@ function cancelAsBundleCallback(err) { } } // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); ``` @@ -3080,9 +3080,9 @@ Cancels a notification published by the reminder agent. This API uses a promise ```js // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { console.info("cancelAsBundle success"); @@ -3421,7 +3421,7 @@ function onConsumeCallback(data) { console.info('===> onConsume callback req.id:' + req.id); }; -var subscriber = { +let subscriber = { onConsume: onConsumeCallback }; @@ -3460,7 +3460,7 @@ function onCancelCallback(data) { console.info('===> onCancel callback req.id:' + req.id); } -var subscriber = { +let subscriber = { onCancel: onCancelCallback }; @@ -3498,7 +3498,7 @@ function onUpdateCallback(map) { console.info('===> onUpdateCallback map:' + JSON.stringify(map)); } -var subscriber = { +let subscriber = { onUpdate: onUpdateCallback }; @@ -3530,7 +3530,7 @@ function onConnectCallback() { console.info('===> onConnect in test'); } -var subscriber = { +let subscriber = { onConnect: onConnectCallback }; @@ -3572,7 +3572,7 @@ function onDisconnectCallback() { console.info('===> onDisconnect in test'); } -var subscriber = { +let subscriber = { onConnect: onConnectCallback, onDisconnect: onDisconnectCallback }; @@ -3608,7 +3608,7 @@ function onDestroyCallback() { console.info('===> onDestroy in test'); } -var subscriber = { +let subscriber = { onDestroy: onDestroyCallback }; @@ -3645,12 +3645,12 @@ function onDoNotDisturbDateChangeCallback(mode) { console.info('===> onDoNotDisturbDateChange:' + mode); } -var subscriber = { +let subscriber = { onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback }; Notification.subscribe(subscriber, subscribeCallback); -var doNotDisturbDate = { +let doNotDisturbDate = { type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) @@ -3695,12 +3695,12 @@ function onEnabledNotificationChangedCallback(callbackData) { console.info("enable: " + callbackData.enable); }; -var subscriber = { +let subscriber = { onEnabledNotificationChanged: onEnabledNotificationChangedCallback }; Notification.subscribe(subscriber, subscribeCallback); -var bundle = { +let bundle = { bundle: "bundleName1", } // Set the onEnabledNotificationChanged callback that is triggered when the notification enabled status changes. diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md index 2d8f497bede97cc9c6d1a8d408b6e80770a2396f..a878376a3c035ac7ad112d95a4d8ebfa47123ee6 100644 --- a/en/application-dev/reference/apis/js-apis-notificationManager.md +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -1,4 +1,4 @@ -# @ohos.notificationManager +# @ohos.notificationManager (NotificationManager) The **notificationManager** module provides notification management capabilities, covering notifications, notification slots, notification enabled status, and notification badge status. @@ -8,11 +8,11 @@ The **notificationManager** module provides notification management capabilities ## Modules to Import -```js -import Notification from '@ohos.notificationManager'; +```ts +import notificationManager from '@ohos.notificationManager'; ``` -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest, callback: AsyncCallback\): void @@ -40,7 +40,7 @@ Publishes a notification. This API uses an asynchronous callback to return the r **Example** -```js +```ts // publish callback function publishCallback(err) { if (err) { @@ -50,23 +50,21 @@ function publishCallback(err) { } } // NotificationRequest object -var notificationRequest = { +let notificationRequest = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", additionalText: "test_additionalText" } } -} -Notification.publish(notificationRequest, publishCallback) +}; +notificationManager.publish(notificationRequest, publishCallback); ``` - - -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest): Promise\ @@ -93,26 +91,26 @@ Publishes a notification. This API uses a promise to return the result. **Example** -```js +```ts // NotificationRequest object -var notificationRequest = { +let notificationRequest = { notificationId: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", additionalText: "test_additionalText" } } -} -Notification.publish(notificationRequest).then(() => { +}; +notificationManager.publish(notificationRequest).then(() => { console.info("publish success"); }); ``` -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void @@ -146,7 +144,7 @@ Publishes a notification to a specified user. This API uses an asynchronous call **Example** -```js +```ts // publish callback function publishCallback(err) { if (err) { @@ -156,23 +154,23 @@ function publishCallback(err) { } } // User ID -var userId = 1 +let userId = 1; // NotificationRequest object -var notificationRequest = { +let notificationRequest = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", additionalText: "test_additionalText" } } -} -Notification.publish(notificationRequest, userId, publishCallback); +}; +notificationManager.publish(notificationRequest, userId, publishCallback); ``` -## Notification.publish +## notificationManager.publish publish(request: NotificationRequest, userId: number): Promise\ @@ -205,28 +203,28 @@ Publishes a notification to a specified user. This API uses a promise to return **Example** -```js -var notificationRequest = { +```ts +let notificationRequest = { notificationId: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", additionalText: "test_additionalText" } } -} +}; -var userId = 1 +let userId = 1; -Notification.publish(notificationRequest, userId).then(() => { +notificationManager.publish(notificationRequest, userId).then(() => { console.info("publish success"); }); ``` -## Notification.cancel +## notificationManager.cancel cancel(id: number, label: string, callback: AsyncCallback\): void @@ -253,7 +251,7 @@ Cancels a notification with the specified ID and label. This API uses an asynchr **Example** -```js +```ts // cancel callback function cancelCallback(err) { if (err) { @@ -262,12 +260,10 @@ function cancelCallback(err) { console.info("cancel success"); } } -Notification.cancel(0, "label", cancelCallback) +notificationManager.cancel(0, "label", cancelCallback); ``` - - -## Notification.cancel +## notificationManager.cancel cancel(id: number, label?: string): Promise\ @@ -293,15 +289,13 @@ Cancels a notification with the specified ID and optional label. This API uses a **Example** -```js -Notification.cancel(0).then(() => { +```ts +notificationManager.cancel(0).then(() => { console.info("cancel success"); }); ``` - - -## Notification.cancel +## notificationManager.cancel cancel(id: number, callback: AsyncCallback\): void @@ -327,7 +321,7 @@ Cancels a notification with the specified ID. This API uses an asynchronous call **Example** -```js +```ts // cancel callback function cancelCallback(err) { if (err) { @@ -336,12 +330,10 @@ function cancelCallback(err) { console.info("cancel success"); } } -Notification.cancel(0, cancelCallback) +notificationManager.cancel(0, cancelCallback); ``` - - -## Notification.cancelAll +## notificationManager.cancelAll cancelAll(callback: AsyncCallback\): void @@ -365,7 +357,7 @@ Cancels all notifications. This API uses an asynchronous callback to return the **Example** -```js +```ts // cancel callback function cancelAllCallback(err) { if (err) { @@ -374,12 +366,10 @@ function cancelAllCallback(err) { console.info("cancelAll success"); } } -Notification.cancelAll(cancelAllCallback) +notificationManager.cancelAll(cancelAllCallback); ``` - - -## Notification.cancelAll +## notificationManager.cancelAll cancelAll(): Promise\ @@ -397,15 +387,13 @@ Cancels all notifications. This API uses a promise to return the result. **Example** -```js -Notification.cancelAll().then(() => { +```ts +notificationManager.cancelAll().then(() => { console.info("cancelAll success"); }); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(slot: NotificationSlot, callback: AsyncCallback\): void @@ -434,7 +422,7 @@ Adds a notification slot. This API uses an asynchronous callback to return the r **Example** -```js +```ts // addSlot callback function addSlotCallBack(err) { if (err) { @@ -444,15 +432,13 @@ function addSlotCallBack(err) { } } // NotificationSlot object -var notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION -} -Notification.addSlot(notificationSlot, addSlotCallBack) +let notificationSlot = { + type: notificationManager.SlotType.SOCIAL_COMMUNICATION +}; +notificationManager.addSlot(notificationSlot, addSlotCallBack); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(slot: NotificationSlot): Promise\ @@ -480,19 +466,17 @@ Adds a notification slot. This API uses a promise to return the result. **Example** -```js +```ts // NotificationSlot object -var notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION -} -Notification.addSlot(notificationSlot).then(() => { +let notificationSlot = { + type: notificationManager.SlotType.SOCIAL_COMMUNICATION +}; +notificationManager.addSlot(notificationSlot).then(() => { console.info("addSlot success"); }); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(type: SlotType, callback: AsyncCallback\): void @@ -517,7 +501,7 @@ Adds a notification slot of a specified type. This API uses an asynchronous call **Example** -```js +```ts // addSlot callback function addSlotCallBack(err) { if (err) { @@ -526,12 +510,10 @@ function addSlotCallBack(err) { console.info("addSlot success"); } } -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) +notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack); ``` - - -## Notification.addSlot +## notificationManager.addSlot addSlot(type: SlotType): Promise\ @@ -555,15 +537,13 @@ Adds a notification slot of a specified type. This API uses a promise to return **Example** -```js -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { +```ts +notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION).then(() => { console.info("addSlot success"); }); ``` - - -## Notification.addSlots +## notificationManager.addSlots addSlots(slots: Array\, callback: AsyncCallback\): void @@ -592,7 +572,7 @@ Adds an array of notification slots. This API uses an asynchronous callback to r **Example** -```js +```ts // addSlots callback function addSlotsCallBack(err) { if (err) { @@ -602,19 +582,17 @@ function addSlotsCallBack(err) { } } // NotificationSlot object -var notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION -} +let notificationSlot = { + type: notificationManager.SlotType.SOCIAL_COMMUNICATION +}; // NotificationSlotArray object -var notificationSlotArray = new Array(); +let notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray, addSlotsCallBack) +notificationManager.addSlots(notificationSlotArray, addSlotsCallBack); ``` - - -## Notification.addSlots +## notificationManager.addSlots addSlots(slots: Array\): Promise\ @@ -642,23 +620,21 @@ Adds an array of notification slots. This API uses a promise to return the resul **Example** -```js +```ts // NotificationSlot object -var notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION -} +let notificationSlot = { + type: notificationManager.SlotType.SOCIAL_COMMUNICATION +}; // NotificationSlotArray object -var notificationSlotArray = new Array(); +let notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray).then(() => { +notificationManager.addSlots(notificationSlotArray).then(() => { console.info("addSlots success"); }); ``` - - -## Notification.getSlot +## notificationManager.getSlot getSlot(slotType: SlotType, callback: AsyncCallback\): void @@ -683,7 +659,7 @@ Obtains a notification slot of a specified type. This API uses an asynchronous c **Example** -```js +```ts // getSlot callback function getSlotCallback(err,data) { if (err) { @@ -692,13 +668,11 @@ function getSlotCallback(err,data) { console.info("getSlot success"); } } -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.getSlot(slotType, getSlotCallback) +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.getSlot(slotType, getSlotCallback); ``` - - -## Notification.getSlot +## notificationManager.getSlot getSlot(slotType: SlotType): Promise\ @@ -728,16 +702,14 @@ Obtains a notification slot of a specified type. This API uses a promise to retu **Example** -```js -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.getSlot(slotType).then((data) => { +```ts +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.getSlot(slotType).then((data) => { console.info("getSlot success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getSlots +## notificationManager.getSlots getSlots(callback: AsyncCallback>): void @@ -761,7 +733,7 @@ Obtains all notification slots of this application. This API uses an asynchronou **Example** -```js +```ts // getSlots callback function getSlotsCallback(err,data) { if (err) { @@ -770,12 +742,10 @@ function getSlotsCallback(err,data) { console.info("getSlots success"); } } -Notification.getSlots(getSlotsCallback) +notificationManager.getSlots(getSlotsCallback); ``` - - -## Notification.getSlots +## notificationManager.getSlots getSlots(): Promise\> @@ -799,15 +769,13 @@ Obtains all notification slots of this application. This API uses a promise to r **Example** -```js -Notification.getSlots().then((data) => { +```ts +notificationManager.getSlots().then((data) => { console.info("getSlots success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.removeSlot +## notificationManager.removeSlot removeSlot(slotType: SlotType, callback: AsyncCallback\): void @@ -832,7 +800,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c **Example** -```js +```ts // removeSlot callback function removeSlotCallback(err) { if (err) { @@ -841,13 +809,11 @@ function removeSlotCallback(err) { console.info("removeSlot success"); } } -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType,removeSlotCallback) +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.removeSlot(slotType,removeSlotCallback); ``` - - -## Notification.removeSlot +## notificationManager.removeSlot removeSlot(slotType: SlotType): Promise\ @@ -871,16 +837,14 @@ Removes a notification slot of a specified type. This API uses a promise to retu **Example** -```js -var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType).then(() => { +```ts +let slotType = notificationManager.SlotType.SOCIAL_COMMUNICATION; +notificationManager.removeSlot(slotType).then(() => { console.info("removeSlot success"); }); ``` - - -## Notification.removeAllSlots +## notificationManager.removeAllSlots removeAllSlots(callback: AsyncCallback\): void @@ -904,7 +868,7 @@ Removes all notification slots. This API uses an asynchronous callback to return **Example** -```js +```ts function removeAllCallBack(err) { if (err) { console.info("removeAllSlots failed " + JSON.stringify(err)); @@ -912,12 +876,10 @@ function removeAllCallBack(err) { console.info("removeAllSlots success"); } } -Notification.removeAllSlots(removeAllCallBack) +notificationManager.removeAllSlots(removeAllCallBack); ``` - - -## Notification.removeAllSlots +## notificationManager.removeAllSlots removeAllSlots(): Promise\ @@ -935,15 +897,13 @@ Removes all notification slots. This API uses a promise to return the result. **Example** -```js -Notification.removeAllSlots().then(() => { +```ts +notificationManager.removeAllSlots().then(() => { console.info("removeAllSlots success"); }); ``` - - -## Notification.setNotificationEnable +## notificationManager.setNotificationEnable setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -974,7 +934,7 @@ Sets whether to enable notification for a specified application. This API uses a **Example** -```js +```ts function setNotificationEnablenCallback(err) { if (err) { console.info("setNotificationEnablenCallback failed " + JSON.stringify(err)); @@ -982,15 +942,13 @@ function setNotificationEnablenCallback(err) { console.info("setNotificationEnablenCallback success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -Notification.setNotificationEnable(bundle, false, setNotificationEnablenCallback); +}; +notificationManager.setNotificationEnable(bundle, false, setNotificationEnablenCallback); ``` - - -## Notification.setNotificationEnable +## notificationManager.setNotificationEnable setNotificationEnable(bundle: BundleOption, enable: boolean): Promise\ @@ -1020,18 +978,16 @@ Sets whether to enable notification for a specified application. This API uses a **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -Notification.setNotificationEnable(bundle, false).then(() => { +}; +notificationManager.setNotificationEnable(bundle, false).then(() => { console.info("setNotificationEnable success"); }); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void @@ -1061,7 +1017,7 @@ Checks whether notification is enabled for a specified application. This API use **Example** -```js +```ts function isNotificationEnabledCallback(err, data) { if (err) { console.info("isNotificationEnabled failed " + JSON.stringify(err)); @@ -1069,15 +1025,13 @@ function isNotificationEnabledCallback(err, data) { console.info("isNotificationEnabled success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); +}; +notificationManager.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(bundle: BundleOption): Promise\ @@ -1112,18 +1066,16 @@ Checks whether notification is enabled for a specified application. This API use **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -Notification.isNotificationEnabled(bundle).then((data) => { +}; +notificationManager.isNotificationEnabled(bundle).then((data) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(callback: AsyncCallback\): void @@ -1151,7 +1103,7 @@ Checks whether notification is enabled for this application. This API uses an as **Example** -```js +```ts function isNotificationEnabledCallback(err, data) { if (err) { console.info("isNotificationEnabled failed " + JSON.stringify(err)); @@ -1160,12 +1112,10 @@ function isNotificationEnabledCallback(err, data) { } } -Notification.isNotificationEnabled(isNotificationEnabledCallback); +notificationManager.isNotificationEnabled(isNotificationEnabledCallback); ``` - - -## Notification.isNotificationEnabled +## notificationManager.isNotificationEnabled isNotificationEnabled(): Promise\ @@ -1200,15 +1150,13 @@ Checks whether notification is enabled for the current application. This API use **Example** -```js -Notification.isNotificationEnabled().then((data) => { +```ts +notificationManager.isNotificationEnabled().then((data) => { console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.displayBadge +## notificationManager.displayBadge displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -1239,7 +1187,7 @@ Sets whether to enable the notification badge for a specified application. This **Example** -```js +```ts function displayBadgeCallback(err) { if (err) { console.info("displayBadge failed " + JSON.stringify(err)); @@ -1247,15 +1195,13 @@ function displayBadgeCallback(err) { console.info("displayBadge success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -Notification.displayBadge(bundle, false, displayBadgeCallback); +}; +notificationManager.displayBadge(bundle, false, displayBadgeCallback); ``` - - -## Notification.displayBadge +## notificationManager.displayBadge displayBadge(bundle: BundleOption, enable: boolean): Promise\ @@ -1285,18 +1231,16 @@ Sets whether to enable the notification badge for a specified application. This **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -Notification.displayBadge(bundle, false).then(() => { +}; +notificationManager.displayBadge(bundle, false).then(() => { console.info("displayBadge success"); }); ``` - - -## Notification.isBadgeDisplayed +## notificationManager.isBadgeDisplayed isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void @@ -1326,7 +1270,7 @@ Checks whether the notification badge is enabled for a specified application. Th **Example** -```js +```ts function isBadgeDisplayedCallback(err, data) { if (err) { console.info("isBadgeDisplayed failed " + JSON.stringify(err)); @@ -1334,15 +1278,13 @@ function isBadgeDisplayedCallback(err, data) { console.info("isBadgeDisplayed success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); +}; +notificationManager.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); ``` - - -## Notification.isBadgeDisplayed +## notificationManager.isBadgeDisplayed isBadgeDisplayed(bundle: BundleOption): Promise\ @@ -1377,18 +1319,16 @@ Checks whether the notification badge is enabled for a specified application. Th **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -Notification.isBadgeDisplayed(bundle).then((data) => { +}; +notificationManager.isBadgeDisplayed(bundle).then((data) => { console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.setSlotByBundle +## notificationManager.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void @@ -1417,11 +1357,9 @@ Sets the notification slot for a specified application. This API uses an asynchr | 1600003 | Failed to connect service. | | 17700001 | The specified bundle name was not found. | - - **Example** -```js +```ts function setSlotByBundleCallback(err) { if (err) { console.info("setSlotByBundle failed " + JSON.stringify(err)); @@ -1429,18 +1367,16 @@ function setSlotByBundleCallback(err) { console.info("setSlotByBundle success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION -} -Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); +}; +let notificationSlot = { + type: notificationManager.SlotType.SOCIAL_COMMUNICATION +}; +notificationManager.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); ``` - - -## Notification.setSlotByBundle +## notificationManager.setSlotByBundle setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ @@ -1470,21 +1406,19 @@ Sets the notification slot for a specified application. This API uses a promise **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -var notificationSlot = { - type: Notification.SlotType.SOCIAL_COMMUNICATION -} -Notification.setSlotByBundle(bundle, notificationSlot).then(() => { +}; +let notificationSlot = { + type: notificationManager.SlotType.SOCIAL_COMMUNICATION +}; +notificationManager.setSlotByBundle(bundle, notificationSlot).then(() => { console.info("setSlotByBundle success"); }); ``` - - -## Notification.getSlotsByBundle +## notificationManager.getSlotsByBundle getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void @@ -1514,7 +1448,7 @@ Obtains the notification slots of a specified application. This API uses an asyn **Example** -```js +```ts function getSlotsByBundleCallback(err, data) { if (err) { console.info("getSlotsByBundle failed " + JSON.stringify(err)); @@ -1522,15 +1456,13 @@ function getSlotsByBundleCallback(err, data) { console.info("getSlotsByBundle success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); +}; +notificationManager.getSlotsByBundle(bundle, getSlotsByBundleCallback); ``` - - -## Notification.getSlotsByBundle +## notificationManager.getSlotsByBundle getSlotsByBundle(bundle: BundleOption): Promise> @@ -1565,18 +1497,16 @@ Obtains the notification slots of a specified application. This API uses a promi **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -Notification.getSlotsByBundle(bundle).then((data) => { +}; +notificationManager.getSlotsByBundle(bundle).then((data) => { console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getSlotNumByBundle +## notificationManager.getSlotNumByBundle getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void @@ -1606,7 +1536,7 @@ Obtains the number of notification slots of a specified application. This API us **Example** -```js +```ts function getSlotNumByBundleCallback(err, data) { if (err) { console.info("getSlotNumByBundle failed " + JSON.stringify(err)); @@ -1614,15 +1544,13 @@ function getSlotNumByBundleCallback(err, data) { console.info("getSlotNumByBundle success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); +}; +notificationManager.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` - - -## Notification.getSlotNumByBundle +## notificationManager.getSlotNumByBundle getSlotNumByBundle(bundle: BundleOption): Promise\ @@ -1657,19 +1585,17 @@ Obtains the number of notification slots of a specified application. This API us **Example** -```js -var bundle = { +```ts +let bundle = { bundle: "bundleName1", -} -Notification.getSlotNumByBundle(bundle).then((data) => { +}; +notificationManager.getSlotNumByBundle(bundle).then((data) => { console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getAllActiveNotifications +## notificationManager.getAllActiveNotifications getAllActiveNotifications(callback: AsyncCallback>): void @@ -1697,7 +1623,7 @@ Obtains all active notifications. This API uses an asynchronous callback to retu **Example** -```js +```ts function getAllActiveNotificationsCallback(err, data) { if (err) { console.info("getAllActiveNotifications failed " + JSON.stringify(err)); @@ -1706,12 +1632,10 @@ function getAllActiveNotificationsCallback(err, data) { } } -Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); +notificationManager.getAllActiveNotifications(getAllActiveNotificationsCallback); ``` - - -## Notification.getAllActiveNotifications +## notificationManager.getAllActiveNotifications getAllActiveNotifications(): Promise\\> @@ -1739,15 +1663,13 @@ Obtains all active notifications. This API uses a promise to return the result. **Example** -```js -Notification.getAllActiveNotifications().then((data) => { +```ts +notificationManager.getAllActiveNotifications().then((data) => { console.info("getAllActiveNotifications success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getActiveNotificationCount +## notificationManager.getActiveNotificationCount getActiveNotificationCount(callback: AsyncCallback\): void @@ -1771,7 +1693,7 @@ Obtains the number of active notifications of this application. This API uses an **Example** -```js +```ts function getActiveNotificationCountCallback(err, data) { if (err) { console.info("getActiveNotificationCount failed " + JSON.stringify(err)); @@ -1780,12 +1702,10 @@ function getActiveNotificationCountCallback(err, data) { } } -Notification.getActiveNotificationCount(getActiveNotificationCountCallback); +notificationManager.getActiveNotificationCount(getActiveNotificationCountCallback); ``` - - -## Notification.getActiveNotificationCount +## notificationManager.getActiveNotificationCount getActiveNotificationCount(): Promise\ @@ -1809,15 +1729,13 @@ Obtains the number of active notifications of this application. This API uses a **Example** -```js -Notification.getActiveNotificationCount().then((data) => { +```ts +notificationManager.getActiveNotificationCount().then((data) => { console.info("getActiveNotificationCount success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.getActiveNotifications +## notificationManager.getActiveNotifications getActiveNotifications(callback: AsyncCallback>): void @@ -1841,7 +1759,7 @@ Obtains active notifications of this application. This API uses an asynchronous **Example** -```js +```ts function getActiveNotificationsCallback(err, data) { if (err) { console.info("getActiveNotifications failed " + JSON.stringify(err)); @@ -1850,12 +1768,10 @@ function getActiveNotificationsCallback(err, data) { } } -Notification.getActiveNotifications(getActiveNotificationsCallback); +notificationManager.getActiveNotifications(getActiveNotificationsCallback); ``` - - -## Notification.getActiveNotifications +## notificationManager.getActiveNotifications getActiveNotifications(): Promise\\> @@ -1879,15 +1795,13 @@ Obtains active notifications of this application. This API uses a promise to ret **Example** -```js -Notification.getActiveNotifications().then((data) => { +```ts +notificationManager.getActiveNotifications().then((data) => { console.info("removeGroupByBundle success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.cancelGroup +## notificationManager.cancelGroup cancelGroup(groupName: string, callback: AsyncCallback\): void @@ -1912,7 +1826,7 @@ Cancels notifications under a notification group of this application. This API u **Example** -```js +```ts function cancelGroupCallback(err) { if (err) { console.info("cancelGroup failed " + JSON.stringify(err)); @@ -1921,14 +1835,12 @@ function cancelGroupCallback(err) { } } -var groupName = "GroupName"; +let groupName = "GroupName"; -Notification.cancelGroup(groupName, cancelGroupCallback); +notificationManager.cancelGroup(groupName, cancelGroupCallback); ``` - - -## Notification.cancelGroup +## notificationManager.cancelGroup cancelGroup(groupName: string): Promise\ @@ -1952,16 +1864,14 @@ Cancels notifications under a notification group of this application. This API u **Example** -```js -var groupName = "GroupName"; -Notification.cancelGroup(groupName).then(() => { +```ts +let groupName = "GroupName"; +notificationManager.cancelGroup(groupName).then(() => { console.info("cancelGroup success"); }); ``` - - -## Notification.removeGroupByBundle +## notificationManager.removeGroupByBundle removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void @@ -1992,7 +1902,7 @@ Removes notifications under a notification group of a specified application. Thi **Example** -```js +```ts function removeGroupByBundleCallback(err) { if (err) { console.info("removeGroupByBundle failed " + JSON.stringify(err)); @@ -2001,15 +1911,13 @@ function removeGroupByBundleCallback(err) { } } -var bundleOption = {bundle: "Bundle"}; -var groupName = "GroupName"; +let bundleOption = {bundle: "Bundle"}; +let groupName = "GroupName"; -Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); +notificationManager.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); ``` - - -## Notification.removeGroupByBundle +## notificationManager.removeGroupByBundle removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ @@ -2039,17 +1947,15 @@ Removes notifications under a notification group of a specified application. Thi **Example** -```js -var bundleOption = {bundle: "Bundle"}; -var groupName = "GroupName"; -Notification.removeGroupByBundle(bundleOption, groupName).then(() => { +```ts +let bundleOption = {bundle: "Bundle"}; +let groupName = "GroupName"; +notificationManager.removeGroupByBundle(bundleOption, groupName).then(() => { console.info("removeGroupByBundle success"); }); ``` - - -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): void @@ -2078,7 +1984,7 @@ Sets the DND time. This API uses an asynchronous callback to return the result. **Example** -```js +```ts function setDoNotDisturbDateCallback(err) { if (err) { console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2087,18 +1993,16 @@ function setDoNotDisturbDateCallback(err) { } } -var doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, +let doNotDisturbDate = { + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; -Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); +notificationManager.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); ``` - - -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ @@ -2126,19 +2030,19 @@ Sets the DND time. This API uses a promise to return the result. **Example** -```js -var doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, +```ts +let doNotDisturbDate = { + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} -Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { +}; +notificationManager.setDoNotDisturbDate(doNotDisturbDate).then(() => { console.info("setDoNotDisturbDate success"); }); ``` -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallback\): void @@ -2169,7 +2073,7 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t **Example** -```js +```ts function setDoNotDisturbDateCallback(err) { if (err) { console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2178,20 +2082,18 @@ function setDoNotDisturbDateCallback(err) { } } -var doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, +let doNotDisturbDate = { + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; -var userId = 1 +let userId = 1; -Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); +notificationManager.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` - - -## Notification.setDoNotDisturbDate +## notificationManager.setDoNotDisturbDate setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ @@ -2221,22 +2123,22 @@ Sets the DND time for a specified user. This API uses a promise to return the re **Example** -```js -var doNotDisturbDate = { - type: Notification.DoNotDisturbType.TYPE_ONCE, +```ts +let doNotDisturbDate = { + type: notificationManager.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) -} +}; -var userId = 1 +let userId = 1; -Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { +notificationManager.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { console.info("setDoNotDisturbDate success"); }); ``` -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(callback: AsyncCallback\): void @@ -2264,7 +2166,7 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul **Example** -```js +```ts function getDoNotDisturbDateCallback(err,data) { if (err) { console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2273,12 +2175,10 @@ function getDoNotDisturbDateCallback(err,data) { } } -Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); +notificationManager.getDoNotDisturbDate(getDoNotDisturbDateCallback); ``` - - -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(): Promise\ @@ -2306,14 +2206,14 @@ Obtains the DND time. This API uses a promise to return the result. **Example** -```js -Notification.getDoNotDisturbDate().then((data) => { +```ts +notificationManager.getDoNotDisturbDate().then((data) => { console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(userId: number, callback: AsyncCallback\): void @@ -2343,7 +2243,7 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback **Example** -```js +```ts function getDoNotDisturbDateCallback(err,data) { if (err) { console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); @@ -2352,14 +2252,12 @@ function getDoNotDisturbDateCallback(err,data) { } } -var userId = 1 +let userId = 1; -Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); +notificationManager.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); ``` - - -## Notification.getDoNotDisturbDate +## notificationManager.getDoNotDisturbDate getDoNotDisturbDate(userId: number): Promise\ @@ -2394,16 +2292,16 @@ Obtains the DND time of a specified user. This API uses a promise to return the **Example** -```js -var userId = 1 +```ts +let userId = 1; -Notification.getDoNotDisturbDate(userId).then((data) => { +notificationManager.getDoNotDisturbDate(userId).then((data) => { console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` -## Notification.supportDoNotDisturbMode +## notificationManager.supportDoNotDisturbMode supportDoNotDisturbMode(callback: AsyncCallback\): void @@ -2431,7 +2329,7 @@ Checks whether DND mode is supported. This API uses an asynchronous callback to **Example** -```js +```ts function supportDoNotDisturbModeCallback(err,data) { if (err) { console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); @@ -2440,12 +2338,10 @@ function supportDoNotDisturbModeCallback(err,data) { } } -Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); +notificationManager.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); ``` - - -## Notification.supportDoNotDisturbMode +## notificationManager.supportDoNotDisturbMode supportDoNotDisturbMode(): Promise\ @@ -2473,15 +2369,13 @@ Checks whether DND mode is supported. This API uses a promise to return the resu **Example** -```js -Notification.supportDoNotDisturbMode().then((data) => { +```ts +notificationManager.supportDoNotDisturbMode().then((data) => { console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.isSupportTemplate +## notificationManager.isSupportTemplate isSupportTemplate(templateName: string, callback: AsyncCallback\): void @@ -2508,7 +2402,7 @@ Checks whether a specified template is supported. This API uses an asynchronous **Example** ```javascript -var templateName = 'process'; +let templateName = 'process'; function isSupportTemplateCallback(err, data) { if (err) { console.info("isSupportTemplate failed " + JSON.stringify(err)); @@ -2517,12 +2411,10 @@ function isSupportTemplateCallback(err, data) { } } -Notification.isSupportTemplate(templateName, isSupportTemplateCallback); +notificationManager.isSupportTemplate(templateName, isSupportTemplateCallback); ``` - - -## Notification.isSupportTemplate +## notificationManager.isSupportTemplate isSupportTemplate(templateName: string): Promise\ @@ -2554,16 +2446,14 @@ Checks whether a specified template is supported. This API uses a promise to ret **Example** ```javascript -var templateName = 'process'; +let templateName = 'process'; -Notification.isSupportTemplate(templateName).then((data) => { +notificationManager.isSupportTemplate(templateName).then((data) => { console.info("isSupportTemplate success, data: " + JSON.stringify(data)); }); ``` - - -## Notification.requestEnableNotification +## notificationManager.requestEnableNotification requestEnableNotification(callback: AsyncCallback\): void @@ -2596,12 +2486,10 @@ function requestEnableNotificationCallback(err) { } }; -Notification.requestEnableNotification(requestEnableNotificationCallback); +notificationManager.requestEnableNotification(requestEnableNotificationCallback); ``` - - -## Notification.requestEnableNotification +## notificationManager.requestEnableNotification requestEnableNotification(): Promise\ @@ -2620,14 +2508,14 @@ Requests notification to be enabled for this application. This API uses a promis **Example** ```javascript -Notification.requestEnableNotification().then(() => { +notificationManager.requestEnableNotification().then(() => { console.info("requestEnableNotification success"); }); ``` -## Notification.setDistributedEnable +## notificationManager.setDistributedEnable setDistributedEnable(enable: boolean, callback: AsyncCallback\): void @@ -2666,14 +2554,12 @@ function setDistributedEnableCallback() { } }; -var enable = true +let enable = true; -Notification.setDistributedEnable(enable, setDistributedEnableCallback); +notificationManager.setDistributedEnable(enable, setDistributedEnableCallback); ``` - - -## Notification.setDistributedEnable +## notificationManager.setDistributedEnable setDistributedEnable(enable: boolean): Promise\ @@ -2703,15 +2589,15 @@ Sets whether this device supports distributed notifications. This API uses a pro **Example** ```javascript -var enable = true +let enable = true; -Notification.setDistributedEnable(enable).then(() => { +notificationManager.setDistributedEnable(enable).then(() => { console.info("setDistributedEnable success"); }); ``` -## Notification.isDistributedEnabled +## notificationManager.isDistributedEnabled isDistributedEnabled(callback: AsyncCallback\): void @@ -2745,12 +2631,12 @@ function isDistributedEnabledCallback(err, data) { } }; -Notification.isDistributedEnabled(isDistributedEnabledCallback); +notificationManager.isDistributedEnabled(isDistributedEnabledCallback); ``` -## Notification.isDistributedEnabled +## notificationManager.isDistributedEnabled isDistributedEnabled(): Promise\ @@ -2776,14 +2662,14 @@ Checks whether this device supports distributed notifications. This API uses a p **Example** ```javascript -Notification.isDistributedEnabled() +notificationManager.isDistributedEnabled() .then((data) => { console.info("isDistributedEnabled success, data: " + JSON.stringify(data)); }); ``` -## Notification.setDistributedEnableByBundle +## notificationManager.setDistributedEnableByBundle setDistributedEnableByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void @@ -2800,7 +2686,7 @@ Sets whether a specified application supports distributed notifications. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| enable | boolean | Yes | Whether the application supports distributed notifications. | +| enable | boolean | Yes | Whether the device supports distributed notifications. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -2824,18 +2710,18 @@ function setDistributedEnableByBundleCallback(err) { } }; -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; -var enable = true +let enable = true -Notification.setDistributedEnableByBundle(bundle, enable, setDistributedEnableByBundleCallback); +notificationManager.setDistributedEnableByBundle(bundle, enable, setDistributedEnableByBundleCallback); ``` -## Notification.setDistributedEnableByBundle +## notificationManager.setDistributedEnableByBundle setDistributedEnableByBundle(bundle: BundleOption, enable: boolean): Promise\ @@ -2852,7 +2738,7 @@ Sets whether a specified application supports distributed notifications. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | -| enable | boolean | Yes | Whether the application supports distributed notifications. | +| enable | boolean | Yes | Whether the device supports distributed notifications. | **Error codes** @@ -2867,18 +2753,18 @@ Sets whether a specified application supports distributed notifications. This AP **Example** ```javascript -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; -var enable = true +let enable = true -Notification.setDistributedEnableByBundle(bundle, enable).then(() => { - console.info("setDistributedEnableByBundle success"); - }); +notificationManager.setDistributedEnableByBundle(bundle, enable).then(() => { + console.info("setDistributedEnableByBundle success"); +}); ``` -## Notification.isDistributedEnabledByBundle +## notificationManager.isDistributedEnabledByBundle isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\): void @@ -2918,16 +2804,14 @@ function isDistributedEnabledByBundleCallback(data) { } }; -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; -Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); +notificationManager.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); ``` - - -## Notification.isDistributedEnabledByBundle +## notificationManager.isDistributedEnabledByBundle isDistributedEnabledByBundle(bundle: BundleOption): Promise\ @@ -2964,17 +2848,17 @@ Checks whether a specified application supports distributed notifications. This **Example** ```javascript -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; -Notification.isDistributedEnabledByBundle(bundle).then((data) => { +notificationManager.isDistributedEnabledByBundle(bundle).then((data) => { console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); }); ``` -## Notification.getDeviceRemindType +## notificationManager.getDeviceRemindType getDeviceRemindType(callback: AsyncCallback\): void @@ -3011,12 +2895,10 @@ function getDeviceRemindTypeCallback(err, data) { } }; -Notification.getDeviceRemindType(getDeviceRemindTypeCallback); +notificationManager.getDeviceRemindType(getDeviceRemindTypeCallback); ``` - - -## Notification.getDeviceRemindType +## notificationManager.getDeviceRemindType getDeviceRemindType(): Promise\ @@ -3045,13 +2927,13 @@ Obtains the notification reminder type. This API uses a promise to return the re **Example** ```javascript -Notification.getDeviceRemindType().then((data) => { +notificationManager.getDeviceRemindType().then((data) => { console.info("getDeviceRemindType success, data: " + JSON.stringify(data)); }); ``` -## Notification.publishAsBundle +## notificationManager.publishAsBundle publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback\): void @@ -3086,7 +2968,7 @@ Publishes a notification through the reminder agent. This API uses an asynchrono **Example** -```js +```ts // publishAsBundle callback function callback(err) { if (err) { @@ -3096,26 +2978,26 @@ function callback(err) { } } // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; // NotificationRequest object let request = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", additionalText: "test_additionalText" } } -} +}; -Notification.publishAsBundle(request, representativeBundle, userId, callback); +notificationManager.publishAsBundle(request, representativeBundle, userId, callback); ``` -## Notification.publishAsBundle +## notificationManager.publishAsBundle publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): Promise\ @@ -3150,30 +3032,30 @@ Publishes a notification through the reminder agent. This API uses a promise to **Example** -```js +```ts // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; // NotificationRequest object -var request = { +let request = { id: 1, content: { - contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", additionalText: "test_additionalText" } } -} +}; -Notification.publishAsBundle(request, representativeBundle, userId).then(() => { +notificationManager.publishAsBundle(request, representativeBundle, userId).then(() => { console.info("publishAsBundle success"); }); ``` -## Notification.cancelAsBundle +## notificationManager.cancelAsBundle cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback\): void @@ -3208,7 +3090,7 @@ Cancels a notification published by the reminder agent. This API uses an asynchr **Example** -```js +```ts // cancelAsBundle function cancelAsBundleCallback(err) { if (err) { @@ -3218,14 +3100,14 @@ function cancelAsBundleCallback(err) { } } // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; -Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); +notificationManager.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); ``` -## Notification.cancelAsBundle +## notificationManager.cancelAsBundle cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ @@ -3259,18 +3141,18 @@ Cancels a notification published by the reminder agent. This API uses a promise **Example** -```js +```ts // Bundle name of the application whose notification function is taken over by the reminder agent -let representativeBundle = "com.example.demo" +let representativeBundle = "com.example.demo"; // User ID -let userId = 100 +let userId = 100; -Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { +notificationManager.cancelAsBundle(0, representativeBundle, userId).then(() => { console.info("cancelAsBundle success"); }); ``` -## Notification.setNotificationEnableSlot +## notificationManager.setNotificationEnableSlot setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void @@ -3288,7 +3170,7 @@ Sets whether to enable a specified notification slot type for a specified applic | -------- | ----------------------------- | ---- | ---------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type. | -| enable | boolean | Yes | Whether to enable the notification slot type. | +| enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** @@ -3302,7 +3184,7 @@ Sets whether to enable a specified notification slot type for a specified applic **Example** -```js +```ts // setNotificationEnableSlot function setNotificationEnableSlotCallback(err) { if (err) { @@ -3312,14 +3194,14 @@ function setNotificationEnableSlotCallback(err) { } }; -Notification.setNotificationEnableSlot( +notificationManager.setNotificationEnableSlot( { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, + notificationManager.SlotType.SOCIAL_COMMUNICATION, true, setNotificationEnableSlotCallback); ``` -## Notification.setNotificationEnableSlot +## notificationManager.setNotificationEnableSlot setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ @@ -3337,7 +3219,7 @@ Sets whether to enable a specified notification slot type for a specified applic | ------ | ----------------------------- | ---- | -------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type.| -| enable | boolean | Yes | Whether to enable the notification slot type. | +| enable | boolean | Yes | Whether to enable notification. | **Error codes** @@ -3350,17 +3232,17 @@ Sets whether to enable a specified notification slot type for a specified applic **Example** -```js +```ts // setNotificationEnableSlot -Notification.setNotificationEnableSlot( +notificationManager.setNotificationEnableSlot( { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, + notificationManager.SlotType.SOCIAL_COMMUNICATION, true).then(() => { console.info("setNotificationEnableSlot success"); }); ``` -## Notification.isNotificationSlotEnabled +## notificationManager.isNotificationSlotEnabled isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void @@ -3391,7 +3273,7 @@ Checks whether a specified notification slot type is enabled for a specified app **Example** -```js +```ts // isNotificationSlotEnabled function getEnableSlotCallback(err, data) { if (err) { @@ -3401,13 +3283,13 @@ function getEnableSlotCallback(err, data) { } }; -Notification.isNotificationSlotEnabled( +notificationManager.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, + notificationManager.SlotType.SOCIAL_COMMUNICATION, getEnableSlotCallback); ``` -## Notification.isNotificationSlotEnabled +## notificationManager.isNotificationSlotEnabled isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ @@ -3443,16 +3325,16 @@ Checks whether a specified notification slot type is enabled for a specified app **Example** -```js +```ts // isNotificationSlotEnabled -Notification.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION).then((data) => { +notificationManager.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, + notificationManager.SlotType.SOCIAL_COMMUNICATION).then((data) => { console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); }); ``` -## Notification.setSyncNotificationEnabledWithoutApp +## notificationManager.setSyncNotificationEnabledWithoutApp setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void @@ -3483,7 +3365,7 @@ Sets whether to enable the notification sync feature for devices where the appli **Example** -```js +```ts let userId = 100; let enable = true; @@ -3495,11 +3377,11 @@ function callback(err) { } } -Notification.setSyncNotificationEnabledWithoutApp(userId, enable, callback); +notificationManager.setSyncNotificationEnabledWithoutApp(userId, enable, callback); ``` -## Notification.setSyncNotificationEnabledWithoutApp +## notificationManager.setSyncNotificationEnabledWithoutApp setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\ @@ -3535,11 +3417,11 @@ Sets whether to enable the notification sync feature for devices where the appli **Example** -```js +```ts let userId = 100; let enable = true; -Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { +notificationManager.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { console.info('setSyncNotificationEnabledWithoutApp success'); }).catch((err) => { console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); @@ -3547,7 +3429,7 @@ Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { ``` -## Notification.getSyncNotificationEnabledWithoutApp +## notificationManager.getSyncNotificationEnabledWithoutApp getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void @@ -3577,7 +3459,7 @@ Obtains whether the notification sync feature is enabled for devices where the a **Example** -```js +```ts let userId = 100; function getSyncNotificationEnabledWithoutAppCallback(err, data) { @@ -3588,11 +3470,11 @@ function getSyncNotificationEnabledWithoutAppCallback(err, data) { } } -Notification.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEnabledWithoutAppCallback); +notificationManager.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEnabledWithoutAppCallback); ``` -## Notification.getSyncNotificationEnabledWithoutApp +## notificationManager.getSyncNotificationEnabledWithoutApp getSyncNotificationEnabledWithoutApp(userId: number): Promise\ @@ -3627,21 +3509,16 @@ Obtains whether the notification sync feature is enabled for devices where the a **Example** -```js +```ts let userId = 100; -Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { +notificationManager.getSyncNotificationEnabledWithoutApp(userId).then((data) => { console.info('getSyncNotificationEnabledWithoutApp, data:' + data); }).catch((err) => { console.info('getSyncNotificationEnabledWithoutApp, err:' + err); }); - .catch((err) => { - console.info('getSyncNotificationEnabledWithoutApp, err:', err); - }); ``` - - ## DoNotDisturbDate **System capability**: SystemCapability.Notification.Notification @@ -3654,8 +3531,6 @@ Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { | begin | Date | Yes | Yes | DND start time.| | end | Date | Yes | Yes | DND end time.| - - ## DoNotDisturbType **System capability**: SystemCapability.Notification.Notification diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md index ed0ad9400ed59c637b5495c7b20f8770b0b4329c..2fc2390a979d6c1a2de7555313a496223dacc4ab 100644 --- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -1,6 +1,6 @@ -# @ohos.notificationSubscribe +# @ohos.notificationSubscribe (NotificationSubscribe) -The **NotificationSubscribe** module provides APIs for notification subscription, notification unsubscription, subscription removal, and more. In general cases, only system applications can call these APIs. +The **notificationSubscribe** module provides APIs for notification subscription, notification unsubscription, subscription removal, and more. In general cases, only system applications can call these APIs. > **NOTE** > @@ -9,7 +9,7 @@ The **NotificationSubscribe** module provides APIs for notification subscription ## Modules to Import ```js -import NotificationSubscribe from '@ohos.notificationSubscribe'; +import notificationSubscribe from '@ohos.notificationSubscribe'; ``` @@ -56,17 +56,15 @@ function subscribeCallback(err) { function onConsumeCallback(data) { console.info("Consume callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onConsume: onConsumeCallback -} -var info = { +}; +let info = { bundleNames: ["bundleName1","bundleName2"] -} -NotificationSubscribe.subscribe(subscriber, info, subscribeCallback); +}; +notificationSubscribe.subscribe(subscriber, info, subscribeCallback); ``` - - ## NotificationSubscribe.subscribe subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void @@ -107,10 +105,10 @@ function subscribeCallback(err) { function onConsumeCallback(data) { console.info("Consume callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onConsume: onConsumeCallback -} -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +}; +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` @@ -148,10 +146,10 @@ Subscribes to a notification with the subscription information specified. This A function onConsumeCallback(data) { console.info("Consume callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onConsume: onConsumeCallback }; -NotificationSubscribe.subscribe(subscriber).then(() => { +notificationSubscribe.subscribe(subscriber).then(() => { console.info("subscribe success"); }); ``` @@ -198,14 +196,12 @@ function unsubscribeCallback(err) { function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onDisconnect: onDisconnectCallback -} -NotificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); +}; +notificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); ``` - - ## NotificationSubscribe.unsubscribe unsubscribe(subscriber: NotificationSubscriber): Promise\ @@ -238,16 +234,14 @@ Unsubscribes from a notification. This API uses a promise to return the result. function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } -var subscriber = { +let subscriber = { onDisconnect: onDisconnectCallback }; -NotificationSubscribe.unsubscribe(subscriber).then(() => { +notificationSubscribe.unsubscribe(subscriber).then(() => { console.info("unsubscribe success"); }); ``` - - ## NotificationSubscribe.remove remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason, callback: AsyncCallback\): void @@ -289,15 +283,15 @@ function removeCallback(err) { console.info("remove success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationKey = { +}; +let notificationKey = { id: 0, label: "label", -} -var reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; -NotificationSubscribe.remove(bundle, notificationKey, reason, removeCallback); +}; +let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +notificationSubscribe.remove(bundle, notificationKey, reason, removeCallback); ``` @@ -335,21 +329,19 @@ Removes a notification for a specified application. This API uses a promise to r **Example** ```js -var bundle = { +let bundle = { bundle: "bundleName1", -} -var notificationKey = { +}; +let notificationKey = { id: 0, label: "label", -} -var reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; -NotificationSubscribe.remove(bundle, notificationKey, reason).then(() => { +}; +let reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +notificationSubscribe.remove(bundle, notificationKey, reason).then(() => { console.info("remove success"); }); ``` - - ## NotificationSubscribe.remove remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): void @@ -382,7 +374,7 @@ Removes a specified notification. This API uses an asynchronous callback to retu **Example** ```js -var hashCode = 'hashCode' +let hashCode = 'hashCode'; function removeCallback(err) { if (err) { @@ -391,12 +383,10 @@ function removeCallback(err) { console.info("remove success"); } } -var reason = NotificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; -NotificationSubscribe.remove(hashCode, reason, removeCallback); +let reason = NotificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; +notificationSubscribe.remove(hashCode, reason, removeCallback); ``` - - ## NotificationSubscribe.remove remove(hashCode: string, reason: RemoveReason): Promise\ @@ -428,15 +418,13 @@ Removes a specified notification. This API uses a promise to return the result. **Example** ```js -var hashCode = 'hashCode' -var reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; -NotificationSubscribe.remove(hashCode, reason).then(() => { +let hashCode = 'hashCode'; +let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +notificationSubscribe.remove(hashCode, reason).then(() => { console.info("remove success"); }); ``` - - ## NotificationSubscribe.removeAll removeAll(bundle: BundleOption, callback: AsyncCallback\): void @@ -475,14 +463,12 @@ function removeAllCallback(err) { console.info("removeAll success"); } } -var bundle = { +let bundle = { bundle: "bundleName1", -} +}; NotificationSubscribe.removeAll(bundle, removeAllCallback); ``` - - ## NotificationSubscribe.removeAll removeAll(callback: AsyncCallback\): void @@ -520,11 +506,9 @@ function removeAllCallback(err) { } } -NotificationSubscribe.removeAll(removeAllCallback); +notificationSubscribe.removeAll(removeAllCallback); ``` - - ## NotificationSubscribe.removeAll removeAll(bundle?: BundleOption): Promise\ @@ -556,7 +540,7 @@ Removes all notifications for a specified application. This API uses a promise t ```js // If no application is specified, notifications of all applications are deleted. -NotificationSubscribe.removeAll().then(() => { +notificationSubscribe.removeAll().then(() => { console.info("removeAll success"); }); ``` @@ -600,9 +584,9 @@ function removeAllCallback(err) { } } -var userId = 1 +let userId = 1; -NotificationSubscribe.removeAll(userId, removeAllCallback); +notificationSubscribe.removeAll(userId, removeAllCallback); ``` ## Notification.removeAll @@ -643,13 +627,11 @@ function removeAllCallback(err) { } } -var userId = 1 +let userId = 1; -NotificationSubscribe.removeAll(userId, removeAllCallback); +notificationSubscribe.removeAll(userId, removeAllCallback); ``` - - ## NotificationSubscriber Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](#notificationsubscribe). @@ -689,11 +671,11 @@ function onConsumeCallback(data) { console.info('===> onConsume callback req.id:' + req.id); }; -var subscriber = { +let subscriber = { onConsume: onConsumeCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` ### onCancel @@ -729,11 +711,11 @@ function onCancelCallback(data) { console.info('===> onCancel callback req.id:' + req.id); } -var subscriber = { +let subscriber = { onCancel: onCancelCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` ### onUpdate @@ -767,11 +749,11 @@ function onUpdateCallback(map) { console.info('===> onUpdateCallback map:' + JSON.stringify(map)); } -var subscriber = { +let subscriber = { onUpdate: onUpdateCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` ### onConnect @@ -799,11 +781,11 @@ function onConnectCallback() { console.info('===> onConnect in test'); } -var subscriber = { +let subscriber = { onConnect: onConnectCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` ### onDisconnect @@ -841,15 +823,15 @@ function onDisconnectCallback() { console.info('===> onDisconnect in test'); } -var subscriber = { +let subscriber = { onConnect: onConnectCallback, onDisconnect: onDisconnectCallback }; // The onConnect callback is invoked when subscription to the notification is complete. -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); // The onDisconnect callback is invoked when unsubscription to the notification is complete. -NotificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); +notificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); ``` ### onDestroy @@ -877,11 +859,11 @@ function onDestroyCallback() { console.info('===> onDestroy in test'); } -var subscriber = { +let subscriber = { onDestroy: onDestroyCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` ### onDoNotDisturbDateChange @@ -915,11 +897,11 @@ function onDoNotDisturbDateChangeCallback(mode) { console.info('===> onDoNotDisturbDateChange:' + mode); } -var subscriber = { +let subscriber = { onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` @@ -956,11 +938,11 @@ function onEnabledNotificationChangedCallback(callbackData) { console.info("enable: ", callbackData.enable); }; -var subscriber = { +let subscriber = { onEnabledNotificationChanged: onEnabledNotificationChangedCallback }; -NotificationSubscribe.subscribe(subscriber, subscribeCallback); +notificationSubscribe.subscribe(subscriber, subscribeCallback); ``` ## BundleOption @@ -1011,7 +993,7 @@ NotificationSubscribe.subscribe(subscriber, subscribeCallback); ## NotificationSorting -Provides sorting information of activity notifications. +Provides sorting information of active notifications. **System capability**: SystemCapability.Notification.Notification 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-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index f903401701e9f68ae6277a687215310f59afc34c..c023229badd1808170022d641415172bf2f899d0 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,4 +1,4 @@ -# @ohos.account.osAccount +# @ohos.account.osAccount (OS Account Management) The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. @@ -155,7 +155,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.| **Error codes** @@ -192,7 +192,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re | Type | Description | | :--------------------- | :--------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.| **Error codes** @@ -483,7 +483,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If true is returned, the current account has been verified. If false is returned, the current account has not been verified.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Error codes** @@ -1690,7 +1690,7 @@ Creates an OS account and associates it with the specified domain account. This | Type | Description | | ---------------------------------------------- | -------------------------------------- | -| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the OS account created.| +| Promise<[OsAccountInfo](#osaccountinfo)> | Promise used to return the information about the created OS account.| **Error codes** @@ -2709,6 +2709,7 @@ Obtains the constraint source information of an OS account. This API uses a prom console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); } ``` + ### isMultiOsAccountEnable(deprecated) isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void @@ -2725,7 +2726,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.| **Example** @@ -2756,7 +2757,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re | Type | Description | | :--------------------- | :--------------------------------------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.| **Example** @@ -3694,7 +3695,7 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -Obtains the OS account ID based on the SN. This API uses a promise to return the result. +Obtains the OS account ID based on the serial number. This API uses a promise to return the result. > **NOTE** > @@ -4360,7 +4361,7 @@ Register a credential inputer. let authType = account_osAccount.AuthType.DOMAIN; let password = new Uint8Array([0, 0, 0, 0, 0]); try { - InputerMgr.registerInputer(authType, { + inputerMgr.registerInputer(authType, { onGetData: (authSubType, callback) => { callback.onSetData(authSubType, password); } 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..e8215f250a75223b6bb16024dea6a153adf71fd5 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 @@ -292,6 +292,7 @@ power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) rebootDevice(reason: string): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [power.reboot](#powerreboot9) instead. Reboots the system. @@ -316,6 +317,7 @@ power.rebootDevice('reboot_test'); isScreenOn(callback: AsyncCallback<boolean>): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead. Checks the screen status of the current device. This API uses an asynchronous callback to return the result. @@ -344,6 +346,7 @@ power.isScreenOn((err, data) => { isScreenOn(): Promise<boolean> +> NOTE
> This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead. Checks the screen status of the current device. This API uses a promise to return the result. 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 27a450de58306f1b018468d6f2590778a9f0d484..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 @@ -# @ohos.prompt +# @ohos.prompt (Prompt) The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md index 0faa9cf211bbd0a673287c34b8d9ad45d34374e6..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 @@ -# @ohos.promptAction +# @ohos.promptAction (Prompt) The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. 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..af2635b955827a772846784a127a6819ff037a37 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,13 +1,12 @@ -# @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. > **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 supports return of error codes since API version 9. - +> - This module supports return of error codes since API version 9. ## Modules to Import @@ -15,7 +14,6 @@ The **RPC** module implements communication between processes, including inter-p import rpc from '@ohos.rpc'; ``` - ## ErrorCode9+ The APIs of this module return exceptions since API version 9. The following table lists the error codes. @@ -42,11 +40,11 @@ The APIs of this module return exceptions since API version 9. The following tab ## MessageSequence9+ - Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. + Provides APIs for reading and writing data in specific format. During RPC or IPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. ### create - create(): MessageSequence + static create(): MessageSequence Creates a **MessageSequence** object. This API is a static method. @@ -60,7 +58,7 @@ The APIs of this module return exceptions since API version 9. The following tab **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); console.log("RpcClient: data is " + data); ``` @@ -75,7 +73,7 @@ Reclaims the **MessageSequence** object that is no longer used. **Example** - ``` + ```ts let reply = rpc.MessageSequence.create(); reply.reclaim(); ``` @@ -105,7 +103,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -146,7 +144,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -187,7 +185,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeInterfaceToken("aaa"); @@ -219,23 +217,22 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode | ------- | ----- | | 1900010 | read data from message sequence failed | - **Example** - ``` - class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { - try { - let interfaceToken = data.readInterfaceToken(); - console.log("RpcServer: interfaceToken is " + interfaceToken); - } catch(error) { - console.info("RpcServer: read interfaceToken failed, errorCode " + error.code); - console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message); - } - return true; - } - } - ``` +```ts +class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + try { + let interfaceToken = data.readInterfaceToken(); + console.log("RpcServer: interfaceToken is " + interfaceToken); + } catch(error) { + console.info("RpcServer: read interfaceToken failed, errorCode " + error.code); + console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message); + } + return true; + } +} +``` ### getSize @@ -253,7 +250,7 @@ Obtains the data size of this **MessageSequence** object. **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); let size = data.getSize(); console.log("RpcClient: size is " + size); @@ -275,7 +272,7 @@ Obtains the capacity of this **MessageSequence** object. **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); let result = data.getCapacity(); console.log("RpcClient: capacity is " + result); @@ -285,7 +282,7 @@ Obtains the capacity of this **MessageSequence** object. setSize(size: number): void -Sets the size of data contained in this **MessageSequence** object. +Sets the size of the data contained in this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -293,11 +290,11 @@ Sets the size of data contained in this **MessageSequence** object. | Name| Type | Mandatory| Description| | ------ | ------ | ---- | ------ | - | size | number | Yes| Data size to set, in bytes.| + | size | number | Yes | Data size to set, in bytes.| **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.setSize(16); @@ -332,7 +329,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.setCapacity(100); @@ -347,7 +344,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode getWritableBytes(): number -Obtains the writable capacity of this **MessageSequence** object. +Obtains the writable capacity (in bytes) of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -355,19 +352,19 @@ Obtains the writable capacity of this **MessageSequence** object. | Type| Description| | ------ | ------ | - | number | **MessageSequence** writable capacity obtained, in bytes.| + | number | Writable capacity of the **MessageSequence** instance, in bytes.| **Example** - ``` - class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { - let getWritableBytes = data.getWritableBytes(); - console.log("RpcServer: getWritableBytes is " + getWritableBytes); - return true; - } - } - ``` +```ts +class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let getWritableBytes = data.getWritableBytes(); + console.log("RpcServer: getWritableBytes is " + getWritableBytes); + return true; + } +} +``` ### getReadableBytes @@ -381,18 +378,18 @@ Obtains the readable capacity of this **MessageSequence** object. | Type| Description| | ------ | ------- | - | number | **MessageSequence** readable capacity obtained, in bytes.| + | number | Readable capacity of the **MessageSequence** instance, in bytes.| **Example** - ``` - class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { - let result = data.getReadableBytes(); - console.log("RpcServer: getReadableBytes is " + result); - return true; - } - } + ```ts +class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let result = data.getReadableBytes(); + console.log("RpcServer: getReadableBytes is " + result); + return true; + } +} ``` ### getReadPosition @@ -411,7 +408,7 @@ Obtains the read position of this **MessageSequence** object. **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); let readPos = data.getReadPosition(); console.log("RpcClient: readPos is " + readPos); @@ -433,7 +430,7 @@ Obtains the write position of this **MessageSequence** object. **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); data.writeInt(10); let bwPos = data.getWritePosition(); @@ -456,7 +453,7 @@ Moves the read pointer to the specified position. **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); data.writeInt(12); data.writeString("sequence"); @@ -488,7 +485,7 @@ Moves the write pointer to the specified position. **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); data.writeInt(4); try { @@ -526,7 +523,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeByte(2); @@ -560,7 +557,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeByte(2); @@ -601,7 +598,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeShort(8); @@ -635,7 +632,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeShort(8); @@ -676,7 +673,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeInt(10); @@ -710,7 +707,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeInt(10); @@ -751,7 +748,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeLong(10000); @@ -785,7 +782,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeLong(10000); @@ -826,7 +823,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeFloat(1.2); @@ -860,7 +857,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeFloat(1.2); @@ -901,7 +898,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeDouble(10.2); @@ -935,7 +932,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeDouble(10.2); @@ -976,7 +973,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeBoolean(false); @@ -1010,7 +1007,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeBoolean(false); @@ -1051,7 +1048,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeChar(97); @@ -1085,7 +1082,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeChar(97); @@ -1126,7 +1123,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeString('abc'); @@ -1160,7 +1157,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeString('abc'); @@ -1201,7 +1198,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -1255,7 +1252,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -1310,7 +1307,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; try { @@ -1345,7 +1342,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; try { @@ -1387,7 +1384,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); let byteArrayVar = [1, 2, 3, 4, 5]; try { @@ -1429,7 +1426,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeShortArray([11, 12, 13]); @@ -1463,7 +1460,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeShortArray([11, 12, 13]); @@ -1504,7 +1501,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeShortArray([11, 12, 13]); @@ -1545,7 +1542,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeIntArray([100, 111, 112]); @@ -1579,7 +1576,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeIntArray([100, 111, 112]); @@ -1620,7 +1617,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeIntArray([100, 111, 112]); @@ -1661,7 +1658,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeLongArray([1111, 1112, 1113]); @@ -1695,7 +1692,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeLongArray([1111, 1112, 1113]); @@ -1736,7 +1733,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeLongArray([1111, 1112, 1113]); @@ -1777,7 +1774,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeFloatArray([1.2, 1.3, 1.4]); @@ -1811,7 +1808,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeFloatArray([1.2, 1.3, 1.4]); @@ -1852,7 +1849,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeFloatArray([1.2, 1.3, 1.4]); @@ -1893,7 +1890,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeDoubleArray([11.1, 12.2, 13.3]); @@ -1927,7 +1924,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeDoubleArray([11.1, 12.2, 13.3]); @@ -1968,7 +1965,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeDoubleArray([11.1, 12.2, 13.3]); @@ -2009,7 +2006,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeBooleanArray([false, true, false]); @@ -2043,7 +2040,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeBooleanArray([false, true, false]); @@ -2084,7 +2081,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeBooleanArray([false, true, false]); @@ -2125,7 +2122,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeCharArray([97, 98, 88]); @@ -2159,7 +2156,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeCharArray([97, 98, 88]); @@ -2200,7 +2197,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeCharArray([97, 98, 88]); @@ -2242,7 +2239,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeStringArray(["abc", "def"]); @@ -2276,7 +2273,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeStringArray(["abc", "def"]); @@ -2317,7 +2314,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let data = rpc.MessageSequence.create(); try { data.writeStringArray(["abc", "def"]); @@ -2352,7 +2349,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -2394,7 +2391,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -2411,7 +2408,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -2467,7 +2464,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class MyParcelable { num: number; str: string; @@ -2524,7 +2521,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class MyParcelable { num: number; str: string; @@ -2584,7 +2581,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -2631,7 +2628,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -2684,7 +2681,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -2712,7 +2709,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode static closeFileDescriptor(fd: number): void -Closes a file descriptor. +Closes a file descriptor. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -2724,7 +2721,7 @@ Closes a file descriptor. **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); @@ -2740,7 +2737,7 @@ Closes a file descriptor. static dupFileDescriptor(fd: number) :number -Duplicates a file descriptor. +Duplicates a file descriptor. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -2766,7 +2763,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); @@ -2795,7 +2792,7 @@ Checks whether this **MessageSequence** object contains file descriptors. **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; @@ -2840,7 +2837,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; @@ -2853,7 +2850,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### readFileDescriptor readFileDescriptor(): number @@ -2878,7 +2874,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; @@ -2897,7 +2893,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### writeAshmem writeAshmem(ashmem: Ashmem): void @@ -2922,7 +2917,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let sequence = new rpc.MessageSequence(); let ashmem; try { @@ -2964,7 +2959,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let sequence = new rpc.MessageSequence(); let ashmem; try { @@ -2988,7 +2983,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### getRawDataCapacity getRawDataCapacity(): number @@ -3005,13 +2999,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageSequenc **Example** - ``` + ```ts let sequence = new rpc.MessageSequence(); let result = sequence.getRawDataCapacity(); console.log("RpcTest: sequence get RawDataCapacity result is : " + result); ``` - ### writeRawData writeRawData(rawData: number[], size: number): void @@ -3037,7 +3030,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let sequence = new rpc.MessageSequence(); let arr = [1, 2, 3, 4, 5]; try { @@ -3048,7 +3041,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### readRawData readRawData(size: number): number[] @@ -3079,7 +3071,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let sequence = new rpc.MessageSequence(); let arr = [1, 2, 3, 4, 5]; try { @@ -3105,7 +3097,7 @@ Provides APIs for reading and writing data in specific format. During RPC, the s ### create -create(): MessageParcel +static create(): MessageParcel Creates a **MessageParcel** object. This method is a static method. @@ -3119,7 +3111,7 @@ Creates a **MessageParcel** object. This method is a static method. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); console.log("RpcClient: data is " + data); ``` @@ -3134,7 +3126,7 @@ Reclaims the **MessageParcel** object that is no longer used. **Example** - ``` + ```ts let reply = rpc.MessageParcel.create(); reply.reclaim(); ``` @@ -3161,7 +3153,7 @@ Serializes a remote object and writes it to this **MessageParcel** object. **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -3202,7 +3194,7 @@ Reads the remote object from this **MessageParcel** object. You can use this met **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -3250,7 +3242,7 @@ Writes an interface token to this **MessageParcel** object. The remote object ca **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeInterfaceToken("aaa"); console.log("RpcServer: writeInterfaceToken is " + result); @@ -3273,7 +3265,7 @@ Reads the interface token from this **MessageParcel** object. The interface toke **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let interfaceToken = data.readInterfaceToken(); @@ -3283,7 +3275,6 @@ Reads the interface token from this **MessageParcel** object. The interface toke } ``` - ### getSize getSize(): number @@ -3300,13 +3291,12 @@ Obtains the data size of this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let size = data.getSize(); console.log("RpcClient: size is " + size); ``` - ### getCapacity getCapacity(): number @@ -3323,13 +3313,12 @@ Obtains the capacity of this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.getCapacity(); console.log("RpcClient: capacity is " + result); ``` - ### setSize setSize(size: number): boolean @@ -3352,13 +3341,12 @@ Sets the size of data contained in this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let setSize = data.setSize(16); console.log("RpcClient: setSize is " + setSize); ``` - ### setCapacity setCapacity(size: number): boolean @@ -3381,13 +3369,12 @@ Sets the storage capacity of this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.setCapacity(100); console.log("RpcClient: setCapacity is " + result); ``` - ### getWritableBytes getWritableBytes(): number @@ -3404,7 +3391,7 @@ Obtains the writable capacity of this **MessageParcel** object. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let getWritableBytes = data.getWritableBytes(); @@ -3414,7 +3401,6 @@ Obtains the writable capacity of this **MessageParcel** object. } ``` - ### getReadableBytes getReadableBytes(): number @@ -3431,7 +3417,7 @@ Obtains the readable capacity of this **MessageParcel** object. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { let result = data.getReadableBytes(); @@ -3441,7 +3427,6 @@ Obtains the readable capacity of this **MessageParcel** object. } ``` - ### getReadPosition getReadPosition(): number @@ -3458,13 +3443,12 @@ Obtains the read position of this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let readPos = data.getReadPosition(); console.log("RpcClient: readPos is " + readPos); ``` - ### getWritePosition getWritePosition(): number @@ -3481,14 +3465,13 @@ Obtains the write position of this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); data.writeInt(10); let bwPos = data.getWritePosition(); console.log("RpcClient: bwPos is " + bwPos); ``` - ### rewindRead rewindRead(pos: number): boolean @@ -3511,7 +3494,7 @@ Moves the read pointer to the specified position. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); data.writeInt(12); data.writeString("parcel"); @@ -3522,7 +3505,6 @@ Moves the read pointer to the specified position. console.log("RpcClient: rewindRead is " + number2); ``` - ### rewindWrite rewindWrite(pos: number): boolean @@ -3545,7 +3527,7 @@ Moves the write pointer to the specified position. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); data.writeInt(4); data.rewindWrite(0); @@ -3554,7 +3536,6 @@ Moves the write pointer to the specified position. console.log("RpcClient: rewindWrite is: " + number); ``` - ### writeByte writeByte(val: number): boolean @@ -3577,13 +3558,12 @@ Writes a Byte value to this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeByte(2); console.log("RpcClient: writeByte is: " + result); ``` - ### readByte readByte(): number @@ -3600,7 +3580,7 @@ Reads the Byte value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeByte(2); console.log("RpcClient: writeByte is: " + result); @@ -3608,7 +3588,6 @@ Reads the Byte value from this **MessageParcel** object. console.log("RpcClient: readByte is: " + ret); ``` - ### writeShort writeShort(val: number): boolean @@ -3627,17 +3606,16 @@ Writes a Short int value to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeShort(8); console.log("RpcClient: writeShort is: " + result); ``` - ### readShort readShort(): number @@ -3654,7 +3632,7 @@ Reads the Short int value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeShort(8); console.log("RpcClient: writeShort is: " + result); @@ -3662,7 +3640,6 @@ Reads the Short int value from this **MessageParcel** object. console.log("RpcClient: readShort is: " + ret); ``` - ### writeInt writeInt(val: number): boolean @@ -3685,13 +3662,12 @@ Writes an Int value to this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeInt(10); console.log("RpcClient: writeInt is " + result); ``` - ### readInt readInt(): number @@ -3708,7 +3684,7 @@ Reads the Int value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeInt(10); console.log("RpcClient: writeInt is " + result); @@ -3716,7 +3692,6 @@ Reads the Int value from this **MessageParcel** object. console.log("RpcClient: readInt is " + ret); ``` - ### writeLong writeLong(val: number): boolean @@ -3735,17 +3710,16 @@ Writes a Long int value to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeLong(10000); console.log("RpcClient: writeLong is " + result); ``` - ### readLong readLong(): number @@ -3762,7 +3736,7 @@ Reads the Long int value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeLong(10000); console.log("RpcClient: writeLong is " + result); @@ -3770,7 +3744,6 @@ Reads the Long int value from this **MessageParcel** object. console.log("RpcClient: readLong is " + ret); ``` - ### writeFloat writeFloat(val: number): boolean @@ -3789,17 +3762,16 @@ Writes a Float value to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeFloat(1.2); console.log("RpcClient: writeFloat is " + result); ``` - ### readFloat readFloat(): number @@ -3816,7 +3788,7 @@ Reads the Float value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeFloat(1.2); console.log("RpcClient: writeFloat is " + result); @@ -3824,7 +3796,6 @@ Reads the Float value from this **MessageParcel** object. console.log("RpcClient: readFloat is " + ret); ``` - ### writeDouble writeDouble(val: number): boolean @@ -3843,17 +3814,16 @@ Writes a Double value to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeDouble(10.2); console.log("RpcClient: writeDouble is " + result); ``` - ### readDouble readDouble(): number @@ -3870,7 +3840,7 @@ Reads the Double value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeDouble(10.2); console.log("RpcClient: writeDouble is " + result); @@ -3896,17 +3866,16 @@ Writes a Boolean value to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeBoolean(false); console.log("RpcClient: writeBoolean is " + result); ``` - ### readBoolean readBoolean(): boolean @@ -3923,7 +3892,7 @@ Reads the Boolean value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeBoolean(false); console.log("RpcClient: writeBoolean is " + result); @@ -3931,7 +3900,6 @@ Reads the Boolean value from this **MessageParcel** object. console.log("RpcClient: readBoolean is " + ret); ``` - ### writeChar writeChar(val: number): boolean @@ -3950,17 +3918,16 @@ Writes a Char value to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeChar(97); console.log("RpcClient: writeChar is " + result); ``` - ### readChar readChar(): number @@ -3977,7 +3944,7 @@ Reads the Char value from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeChar(97); console.log("RpcClient: writeChar is " + result); @@ -3985,7 +3952,6 @@ Reads the Char value from this **MessageParcel** object. console.log("RpcClient: readChar is " + ret); ``` - ### writeString writeString(val: string): boolean @@ -4004,17 +3970,16 @@ Writes a string to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeString('abc'); console.log("RpcClient: writeString is " + result); ``` - ### readString readString(): string @@ -4031,7 +3996,7 @@ Reads the string from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeString('abc'); console.log("RpcClient: writeString is " + result); @@ -4039,7 +4004,6 @@ Reads the string from this **MessageParcel** object. console.log("RpcClient: readString is " + ret); ``` - ### writeSequenceable writeSequenceable(val: Sequenceable): boolean @@ -4058,11 +4022,11 @@ Writes a sequenceable object to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -4087,7 +4051,6 @@ Writes a sequenceable object to this **MessageParcel** object. console.log("RpcClient: writeSequenceable is " + result); ``` - ### readSequenceable readSequenceable(dataIn: Sequenceable): boolean @@ -4110,7 +4073,7 @@ Reads member variables from this **MessageParcel** object. **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -4138,7 +4101,6 @@ Reads member variables from this **MessageParcel** object. console.log("RpcClient: writeSequenceable is " + result2); ``` - ### writeByteArray writeByteArray(byteArray: number[]): boolean @@ -4157,18 +4119,17 @@ Writes a byte array to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; let result = data.writeByteArray(ByteArrayVar); console.log("RpcClient: writeByteArray is " + result); ``` - ### readByteArray readByteArray(dataIn: number[]): void @@ -4185,7 +4146,7 @@ Reads a byte array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; let result = data.writeByteArray(ByteArrayVar); @@ -4194,7 +4155,6 @@ Reads a byte array from this **MessageParcel** object. data.readByteArray(array); ``` - ### readByteArray readByteArray(): number[] @@ -4211,7 +4171,7 @@ Reads the byte array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; let result = data.writeByteArray(ByteArrayVar); @@ -4220,7 +4180,6 @@ Reads the byte array from this **MessageParcel** object. console.log("RpcClient: readByteArray is " + array); ``` - ### writeShortArray writeShortArray(shortArray: number[]): boolean @@ -4239,17 +4198,16 @@ Writes a short array to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeShortArray([11, 12, 13]); console.log("RpcClient: writeShortArray is " + result); ``` - ### readShortArray readShortArray(dataIn: number[]): void @@ -4266,7 +4224,7 @@ Reads a short array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeShortArray([11, 12, 13]); console.log("RpcClient: writeShortArray is " + result); @@ -4274,7 +4232,6 @@ Reads a short array from this **MessageParcel** object. data.readShortArray(array); ``` - ### readShortArray readShortArray(): number[] @@ -4291,7 +4248,7 @@ Reads the short array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeShortArray([11, 12, 13]); console.log("RpcClient: writeShortArray is " + result); @@ -4299,7 +4256,6 @@ Reads the short array from this **MessageParcel** object. console.log("RpcClient: readShortArray is " + array); ``` - ### writeIntArray writeIntArray(intArray: number[]): boolean @@ -4318,17 +4274,16 @@ Writes an integer array to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeIntArray([100, 111, 112]); console.log("RpcClient: writeIntArray is " + result); ``` - ### readIntArray readIntArray(dataIn: number[]): void @@ -4345,7 +4300,7 @@ Reads an integer array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeIntArray([100, 111, 112]); console.log("RpcClient: writeIntArray is " + result); @@ -4353,7 +4308,6 @@ Reads an integer array from this **MessageParcel** object. data.readIntArray(array); ``` - ### readIntArray readIntArray(): number[] @@ -4370,7 +4324,7 @@ Reads the integer array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeIntArray([100, 111, 112]); console.log("RpcClient: writeIntArray is " + result); @@ -4378,7 +4332,6 @@ Reads the integer array from this **MessageParcel** object. console.log("RpcClient: readIntArray is " + array); ``` - ### writeLongArray writeLongArray(longArray: number[]): boolean @@ -4397,17 +4350,16 @@ Writes a long array to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeLongArray([1111, 1112, 1113]); console.log("RpcClient: writeLongArray is " + result); ``` - ### readLongArray readLongArray(dataIn: number[]): void @@ -4424,7 +4376,7 @@ Reads a long array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeLongArray([1111, 1112, 1113]); console.log("RpcClient: writeLongArray is " + result); @@ -4432,7 +4384,6 @@ Reads a long array from this **MessageParcel** object. data.readLongArray(array); ``` - ### readLongArray readLongArray(): number[] @@ -4449,7 +4400,7 @@ Reads the long array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeLongArray([1111, 1112, 1113]); console.log("RpcClient: writeLongArray is " + result); @@ -4457,7 +4408,6 @@ Reads the long array from this **MessageParcel** object. console.log("RpcClient: readLongArray is " + array); ``` - ### writeFloatArray writeFloatArray(floatArray: number[]): boolean @@ -4476,17 +4426,16 @@ Writes a FloatArray to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeFloatArray([1.2, 1.3, 1.4]); console.log("RpcClient: writeFloatArray is " + result); ``` - ### readFloatArray readFloatArray(dataIn: number[]): void @@ -4503,7 +4452,7 @@ Reads a FloatArray from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeFloatArray([1.2, 1.3, 1.4]); console.log("RpcClient: writeFloatArray is " + result); @@ -4511,7 +4460,6 @@ Reads a FloatArray from this **MessageParcel** object. data.readFloatArray(array); ``` - ### readFloatArray readFloatArray(): number[] @@ -4528,7 +4476,7 @@ Reads the FloatArray from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeFloatArray([1.2, 1.3, 1.4]); console.log("RpcClient: writeFloatArray is " + result); @@ -4536,7 +4484,6 @@ Reads the FloatArray from this **MessageParcel** object. console.log("RpcClient: readFloatArray is " + array); ``` - ### writeDoubleArray writeDoubleArray(doubleArray: number[]): boolean @@ -4555,17 +4502,16 @@ Writes a DoubleArray to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeDoubleArray([11.1, 12.2, 13.3]); console.log("RpcClient: writeDoubleArray is " + result); ``` - ### readDoubleArray readDoubleArray(dataIn: number[]): void @@ -4582,7 +4528,7 @@ Reads a DoubleArray from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeDoubleArray([11.1, 12.2, 13.3]); console.log("RpcClient: writeDoubleArray is " + result); @@ -4590,7 +4536,6 @@ Reads a DoubleArray from this **MessageParcel** object. data.readDoubleArray(array); ``` - ### readDoubleArray readDoubleArray(): number[] @@ -4607,7 +4552,7 @@ Reads the DoubleArray from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeDoubleArray([11.1, 12.2, 13.3]); console.log("RpcClient: writeDoubleArray is " + result); @@ -4615,7 +4560,6 @@ Reads the DoubleArray from this **MessageParcel** object. console.log("RpcClient: readDoubleArray is " + array); ``` - ### writeBooleanArray writeBooleanArray(booleanArray: boolean[]): boolean @@ -4634,17 +4578,16 @@ Writes a Boolean array to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeBooleanArray([false, true, false]); console.log("RpcClient: writeBooleanArray is " + result); ``` - ### readBooleanArray readBooleanArray(dataIn: boolean[]): void @@ -4661,7 +4604,7 @@ Reads a Boolean array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeBooleanArray([false, true, false]); console.log("RpcClient: writeBooleanArray is " + result); @@ -4669,7 +4612,6 @@ Reads a Boolean array from this **MessageParcel** object. data.readBooleanArray(array); ``` - ### readBooleanArray readBooleanArray(): boolean[] @@ -4686,7 +4628,7 @@ Reads the Boolean array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeBooleanArray([false, true, false]); console.log("RpcClient: writeBooleanArray is " + result); @@ -4694,7 +4636,6 @@ Reads the Boolean array from this **MessageParcel** object. console.log("RpcClient: readBooleanArray is " + array); ``` - ### writeCharArray writeCharArray(charArray: number[]): boolean @@ -4713,17 +4654,16 @@ Writes a character array to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeCharArray([97, 98, 88]); console.log("RpcClient: writeCharArray is " + result); ``` - ### readCharArray readCharArray(dataIn: number[]): void @@ -4740,7 +4680,7 @@ Reads a character array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeCharArray([97, 98, 99]); console.log("RpcClient: writeCharArray is " + result); @@ -4748,7 +4688,6 @@ Reads a character array from this **MessageParcel** object. data.readCharArray(array); ``` - ### readCharArray readCharArray(): number[] @@ -4765,7 +4704,7 @@ Reads the character array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeCharArray([97, 98, 99]); console.log("RpcClient: writeCharArray is " + result); @@ -4773,7 +4712,6 @@ Reads the character array from this **MessageParcel** object. console.log("RpcClient: readCharArray is " + array); ``` - ### writeStringArray writeStringArray(stringArray: string[]): boolean @@ -4792,17 +4730,16 @@ Writes a string array to this **MessageParcel** object. | Type | Description| | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeStringArray(["abc", "def"]); console.log("RpcClient: writeStringArray is " + result); ``` - ### readStringArray readStringArray(dataIn: string[]): void @@ -4819,7 +4756,7 @@ Reads a string array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeStringArray(["abc", "def"]); console.log("RpcClient: writeStringArray is " + result); @@ -4827,7 +4764,6 @@ Reads a string array from this **MessageParcel** object. data.readStringArray(array); ``` - ### readStringArray readStringArray(): string[] @@ -4844,7 +4780,7 @@ Reads the string array from this **MessageParcel** object. **Example** - ``` + ```ts let data = rpc.MessageParcel.create(); let result = data.writeStringArray(["abc", "def"]); console.log("RpcClient: writeStringArray is " + result); @@ -4852,7 +4788,6 @@ Reads the string array from this **MessageParcel** object. console.log("RpcClient: readStringArray is " + array); ``` - ### writeNoException8+ writeNoException(): void @@ -4863,7 +4798,7 @@ Writes information to this **MessageParcel** object indicating that no exception **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -4905,7 +4840,7 @@ Reads the exception information from this **MessageParcel** object. **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -4922,7 +4857,7 @@ Reads the exception information from this **MessageParcel** object. }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -4967,11 +4902,11 @@ Writes a sequenceable array to this **MessageParcel** object. | Type | Description | | ------- | --------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -4999,7 +4934,6 @@ Writes a sequenceable array to this **MessageParcel** object. console.log("RpcClient: writeSequenceableArray is " + result); ``` - ### readSequenceableArray8+ readSequenceableArray(sequenceableArray: Sequenceable[]): void @@ -5016,7 +4950,7 @@ Reads a sequenceable array from this **MessageParcel** object. **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -5046,7 +4980,6 @@ Reads a sequenceable array from this **MessageParcel** object. data.readSequenceableArray(b); ``` - ### writeRemoteObjectArray8+ writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean @@ -5065,11 +4998,11 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. | Type | Description | | ------- | -------------------------------------------------------------------------------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -5099,7 +5032,6 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. console.log("RpcClient: writeRemoteObjectArray is " + result); ``` - ### readRemoteObjectArray8+ readRemoteObjectArray(objects: IRemoteObject[]): void @@ -5116,7 +5048,7 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -5147,7 +5079,6 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. data.readRemoteObjectArray(b); ``` - ### readRemoteObjectArray8+ readRemoteObjectArray(): IRemoteObject[] @@ -5164,7 +5095,7 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -5196,12 +5127,11 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. console.log("RpcClient: readRemoteObjectArray is " + b); ``` - ### closeFileDescriptor8+ static closeFileDescriptor(fd: number): void -Closes a file descriptor. +Closes a file descriptor. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -5213,19 +5143,18 @@ Closes a file descriptor. **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); rpc.MessageParcel.closeFileDescriptor(fd); ``` - ### dupFileDescriptor8+ static dupFileDescriptor(fd: number) :number -Duplicates a file descriptor. +Duplicates a file descriptor. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -5243,14 +5172,13 @@ Duplicates a file descriptor. **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); let newFd = rpc.MessageParcel.dupFileDescriptor(fd); ``` - ### containFileDescriptors8+ containFileDescriptors(): boolean @@ -5263,11 +5191,11 @@ Checks whether this **MessageParcel** object contains a file descriptor. | Type | Description | | ------- | ------------------------------------------------------------------ | - | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| + | boolean |Returns **true** if the **MessageSequence** object contains a file descriptor; returns **false** otherwise.| **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; @@ -5279,7 +5207,6 @@ Checks whether this **MessageParcel** object contains a file descriptor. console.log("RpcTest: parcel after write fd containFd result is : " + containFD); ``` - ### writeFileDescriptor8+ writeFileDescriptor(fd: number): boolean @@ -5302,7 +5229,7 @@ Writes a file descriptor to this **MessageParcel** object. **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; @@ -5311,7 +5238,6 @@ Writes a file descriptor to this **MessageParcel** object. console.log("RpcTest: parcel writeFd result is : " + writeResult); ``` - ### readFileDescriptor8+ readFileDescriptor(): number @@ -5328,7 +5254,7 @@ Reads the file descriptor from this **MessageParcel** object. **Example** - ``` + ```ts import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; @@ -5338,7 +5264,6 @@ Reads the file descriptor from this **MessageParcel** object. console.log("RpcTest: parcel read fd is : " + readFD); ``` - ### writeAshmem8+ writeAshmem(ashmem: Ashmem): boolean @@ -5357,18 +5282,17 @@ Writes an anonymous shared object to this **MessageParcel** object. | Type | Description | | ------- | -------------------------------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let parcel = new rpc.MessageParcel(); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024); let isWriteSuccess = parcel.writeAshmem(ashmem); console.log("RpcTest: write ashmem to result is : " + isWriteSuccess); ``` - ### readAshmem8+ readAshmem(): Ashmem @@ -5385,7 +5309,7 @@ Reads the anonymous shared object from this **MessageParcel** object. **Example** - ``` + ```ts let parcel = new rpc.MessageParcel(); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024); let isWriteSuccess = parcel.writeAshmem(ashmem); @@ -5394,7 +5318,6 @@ Reads the anonymous shared object from this **MessageParcel** object. console.log("RpcTest: read ashmem to result is : " + readAshmem); ``` - ### getRawDataCapacity8+ getRawDataCapacity(): number @@ -5411,13 +5334,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel* **Example** - ``` + ```ts let parcel = new rpc.MessageParcel(); let result = parcel.getRawDataCapacity(); console.log("RpcTest: parcel get RawDataCapacity result is : " + result); ``` - ### writeRawData8+ writeRawData(rawData: number[], size: number): boolean @@ -5437,18 +5359,17 @@ Writes raw data to this **MessageParcel** object. | Type | Description | | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let parcel = new rpc.MessageParcel(); let arr = [1, 2, 3, 4, 5]; let isWriteSuccess = parcel.writeRawData(arr, arr.length); console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess); ``` - ### readRawData8+ readRawData(size: number): number[] @@ -5471,7 +5392,7 @@ Reads raw data from this **MessageParcel** object. **Example** - ``` + ```ts let parcel = new rpc.MessageParcel(); let arr = [1, 2, 3, 4, 5]; let isWriteSuccess = parcel.writeRawData(arr, arr.length); @@ -5480,7 +5401,6 @@ Reads raw data from this **MessageParcel** object. console.log("RpcTest: parcel read raw data result is : " + result); ``` - ## Parcelable9+ Writes an object to a **MessageSequence** and reads it from the **MessageSequence** during IPC. @@ -5504,10 +5424,9 @@ Marshals this **Parcelable** object into a **MessageSequence** object. | Type | Description | | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** - ``` + ```ts class MyParcelable { num: number; str: string; @@ -5535,7 +5454,6 @@ Marshals this **Parcelable** object into a **MessageSequence** object. console.log("RpcClient: readParcelable is " + result2); ``` - ### unmarshalling unmarshalling(dataIn: MessageSequence): boolean @@ -5558,7 +5476,7 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object. **Example** - ``` + ```ts class MyParcelable { num: number; str: string; @@ -5586,7 +5504,6 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object. console.log("RpcClient: readParcelable is " + result2); ``` - ## Sequenceable(deprecated) >This class is no longer maintained since API version 9. You are advised to use the [Parcelable](#parcelable9). @@ -5612,10 +5529,9 @@ Marshals the sequenceable object into a **MessageParcel** object. | Type | Description | | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -5643,7 +5559,6 @@ Marshals the sequenceable object into a **MessageParcel** object. console.log("RpcClient: readSequenceable is " + result2); ``` - ### unmarshalling unmarshalling(dataIn: MessageParcel): boolean @@ -5666,7 +5581,7 @@ Unmarshals this sequenceable object from a **MessageParcel** object. **Example** - ``` + ```ts class MySequenceable { num: number; str: string; @@ -5694,7 +5609,6 @@ Unmarshals this sequenceable object from a **MessageParcel** object. console.log("RpcClient: readSequenceable is " + result2); ``` - ## IRemoteBroker Provides the holder of a remote proxy object. @@ -5715,17 +5629,38 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl **Example** - ``` + ```ts class TestAbility extends rpc.RemoteObject { asObject() { return this; } } + let remoteObject = new TestAbility().asObject(); ``` **Example** - ``` + ```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 TestProxy { remote: rpc.RemoteObject; constructor(remote) { @@ -5735,6 +5670,8 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl return this.remote; } } + let iRemoteObject = new TestProxy(proxy).asObject(); + ``` ## DeathRecipient @@ -5751,7 +5688,7 @@ Called to perform subsequent operations when a death notification of the remote **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -5795,7 +5732,7 @@ Provides methods to query of obtain interface descriptors, add or delete death n getLocalInterface(descriptor: string): IRemoteBroker -Obtains the interface. +Obtains the interface descriptor. **System capability**: SystemCapability.Communication.IPC.Core @@ -5817,7 +5754,7 @@ Obtains the interface. queryLocalInterface(descriptor: string): IRemoteBroker -Obtains the interface. +Queries the interface descriptor. **System capability**: SystemCapability.Communication.IPC.Core @@ -5833,7 +5770,6 @@ Obtains the interface. | ------------- | --------------------------------------------- | | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| - ### sendRequest(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -5857,7 +5793,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| ### sendRequest8+(deprecated) @@ -5928,7 +5864,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | - ### sendRequest8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -5949,12 +5884,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | - ### registerDeathRecipient9+ registerDeathRecipient(recipient: DeathRecipient, flags: number): void -Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. +Registers a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core @@ -5962,7 +5896,7 @@ Adds a callback for receiving death notifications of the remote object. This met | Name | Type | Mandatory| Description | | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.| | flags | number | Yes | Flag of the death notification.| **Error Code** @@ -5973,7 +5907,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode | ------- | -------- | | 1900008 | proxy or remote object is invalid | - ### addDeathrecipient(deprecated) >This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). @@ -5995,14 +5928,14 @@ Adds a callback for receiving death notifications of the remote object. This met | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| + | boolean | Returns **true** if the callback is added successfully; return **false** otherwise.| ### unregisterDeathRecipient9+ unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void -Removes the callback used to receive death notifications of the remote object. +Unregisters the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core @@ -6010,7 +5943,7 @@ Removes the callback used to receive death notifications of the remote object. | Name | Type | Mandatory| Description | | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.| | flags | number | Yes | Flag of the death notification.| **Error Code** @@ -6021,7 +5954,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode | ------- | -------- | | 1900008 | proxy or remote object is invalid | - ### removeDeathRecipient(deprecated) >This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). @@ -6043,8 +5975,7 @@ Removes the callback used to receive death notifications of the remote object. | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| - + | boolean | Returns **true** if the callback is removed; returns **false** otherwise.| ### getDescriptor9+ @@ -6115,7 +6046,6 @@ Provides APIs to implement **IRemoteObject**. | MIN_TRANSACTION_ID | 1 (0x00000001) | Minimum valid instruction code. | | MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | Maximum valid instruction code. | - ### sendRequest(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -6139,11 +6069,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6160,7 +6090,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -6181,7 +6111,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch reply.reclaim(); ``` - ### sendMessageRequest9+ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> @@ -6207,7 +6136,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6224,7 +6153,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -6251,7 +6180,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn }); ``` - ### sendRequest8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -6279,7 +6207,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6296,7 +6224,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); @@ -6341,10 +6269,9 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | - **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6361,7 +6288,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; function sendRequestCallback(result) { if (result.errCode === 0) { @@ -6390,7 +6317,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn } ``` - ### sendRequest8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -6413,7 +6339,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6430,7 +6356,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; function sendRequestCallback(result) { if (result.errCode === 0) { @@ -6454,7 +6380,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch proxy.sendRequest(1, data, reply, option, sendRequestCallback); ``` - ### getLocalInterface9+ getLocalInterface(interface: string): IRemoteBroker @@ -6485,7 +6410,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6502,7 +6427,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode }; let want = { "bundleName":"com.ohos.server", - "abilityName":"com.ohos.server.MainAbility", + "abilityName":"com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); try { @@ -6514,7 +6439,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### queryLocalInterface(deprecated) >This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). @@ -6539,7 +6463,7 @@ Obtains the **LocalInterface** object of an interface token. **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6556,19 +6480,18 @@ Obtains the **LocalInterface** object of an interface token. }; let want = { "bundleName":"com.ohos.server", - "abilityName":"com.ohos.server.MainAbility", + "abilityName":"com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let broker = proxy.queryLocalInterface("testObject"); console.log("RpcClient: queryLocalInterface is " + broker); ``` - ### registerDeathRecipient9+ registerDeathRecipient(recipient: DeathRecipient, flags: number): void -Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. +Registers a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core @@ -6576,7 +6499,7 @@ Adds a callback for receiving death notifications of the remote object. This met | Name | Type | Mandatory| Description | | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.| | flags | number | Yes | Flag of the death notification.| **Error Code** @@ -6589,7 +6512,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6606,7 +6529,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); class MyDeathRecipient { @@ -6623,7 +6546,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### addDeathRecippient(deprecated) >This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). @@ -6645,11 +6567,11 @@ Adds a callback for receiving the death notifications of the remote object, incl | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| + | boolean | Returns **true** if the callback is added successfully; return **false** otherwise.| **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6666,7 +6588,7 @@ Adds a callback for receiving the death notifications of the remote object, incl }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); class MyDeathRecipient { @@ -6682,7 +6604,7 @@ Adds a callback for receiving the death notifications of the remote object, incl unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean -Removes the callback used to receive death notifications of the remote object. +Unregisters the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core @@ -6690,7 +6612,7 @@ Removes the callback used to receive death notifications of the remote object. | Name | Type | Mandatory| Description | | --------- | --------------------------------- | ---- | -------------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.| | flags | number | Yes | Flag of the death notification.| **Error Code** @@ -6703,7 +6625,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6720,7 +6642,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); class MyDeathRecipient { @@ -6738,7 +6660,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### removeDeathRecipient(deprecated) >This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). @@ -6760,11 +6681,11 @@ Removes the callback used to receive death notifications of the remote object. | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| + | boolean | Returns **true** if the callback is removed; returns **false** otherwise.| **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6781,7 +6702,7 @@ Removes the callback used to receive death notifications of the remote object. }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); class MyDeathRecipient { @@ -6794,7 +6715,6 @@ Removes the callback used to receive death notifications of the remote object. proxy.removeDeathRecipient(deathRecipient, 0); ``` - ### getDescriptor9+ getDescriptor(): string @@ -6820,7 +6740,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6837,7 +6757,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); try { @@ -6849,7 +6769,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### getInterfaceDescriptor(deprecated) >This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). @@ -6868,7 +6787,7 @@ Obtains the interface descriptor of this proxy object. **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6885,14 +6804,13 @@ Obtains the interface descriptor of this proxy object. }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let descriptor = proxy.getInterfaceDescriptor(); console.log("RpcClient: descriptor is " + descriptor); ``` - ### isObjectDead isObjectDead(): boolean @@ -6909,7 +6827,7 @@ Checks whether the **RemoteObject** is dead. **Example** - ``` + ```ts import FA from "@ohos.ability.featureAbility"; let proxy; let connect = { @@ -6926,14 +6844,13 @@ Checks whether the **RemoteObject** is dead. }; let want = { "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "abilityName": "com.ohos.server.EntryAbility", }; FA.connectAbility(want, connect); let isDead = proxy.isObjectDead(); console.log("RpcClient: isObjectDead is " + isDead); ``` - ## MessageOption Provides common message options (flag and wait time). Use the specified flag to construct the **MessageOption** object. @@ -6963,6 +6880,16 @@ A constructor used to create a **MessageOption** object. | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| +**Example** + + ```ts + class TestRemoteObject extends rpc.MessageOption { + constructor(async) { + super(async); + } + } + ``` + ### constructor constructor(syncFlags?: number, waitTime?: number) @@ -6978,7 +6905,15 @@ A constructor used to create a **MessageOption** object. | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. | | waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| +**Example** + ```ts + class TestRemoteObject extends rpc.MessageOption { + constructor(syncFlags,waitTime) { + super(syncFlags,waitTime); + } + } + ``` ### isAsync9+ isAsync(): boolean; @@ -6991,8 +6926,14 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously. | Type | Description | | ------- | ------------------------------------ | - | boolean | Call mode obtained.| + | boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.| +**Example** + + ```ts + let option = new rpc.MessageOption(); + let isAsync = option.isAsync(); + ``` ### setAsync9+ @@ -7002,6 +6943,13 @@ Sets whether **SendMessageRequest** is called synchronously or asynchronously. **System capability**: SystemCapability.Communication.IPC.Core +**Example** + + ```ts + let option = new rpc.MessageOption(); + let setAsync = option.setAsync(true); + console.log("Set synchronization flag"); + ``` ### getFlags @@ -7017,6 +6965,22 @@ Obtains the call flag, which can be synchronous or asynchronous. | ------ | ------------------------------------ | | number | Call mode obtained.| +**Example** + + ```ts + try { + let option = new rpc.MessageOption(); + console.info("create object successfully."); + let flog = option.getFlags(); + console.info("run getFlags success, flog is " + flog); + option.setFlags(1) + console.info("run setFlags success"); + let flog2 = option.getFlags(); + console.info("run getFlags success, flog2 is " + flog2); + } catch (error) { + console.info("error " + error); + } + ``` ### setFlags @@ -7032,6 +6996,19 @@ Sets the call flag, which can be synchronous or asynchronous. | ------ | ------ | ---- | ------------------------ | | flags | number | Yes | Call flag to set.| +**Example** + + ```ts + try { + let option = new rpc.MessageOption(); + option.setFlags(1) + console.info("run setFlags success"); + let flog = option.getFlags(); + console.info("run getFlags success, flog is " + flog); + } catch (error) { + console.info("error " + error); + } + ``` ### getWaitTime @@ -7047,6 +7024,20 @@ Obtains the maximum wait time for this RPC call. | ------ | ----------------- | | number | Maximum wait time obtained.| +**Example** + + ```ts + try { + let option = new rpc.MessageOption(); + let time = option.getWaitTime(); + console.info("run getWaitTime success"); + option.setWaitTime(16); + let time2 = option.getWaitTime(); + console.info("run getWaitTime success, time is " + time); + } catch (error) { + console.info("error " + error); + } + ``` ### setWaitTime @@ -7062,6 +7053,18 @@ Sets the maximum wait time for this RPC call. | -------- | ------ | ---- | --------------------- | | waitTime | number | Yes | Maximum wait time to set.| +**Example** + + ```ts + try { + let option = new rpc.MessageOption(); + option.setWaitTime(16); + let time = option.getWaitTime(); + console.info("run getWaitTime success, time is " + time); + } catch (error) { + console.info("error " + error); + } + ``` ## IPCSkeleton @@ -7071,7 +7074,7 @@ Obtains IPC context information, including the UID and PID, local and remote dev static getContextObject(): IRemoteObject -Obtains the system capability manager. +Obtains the system capability manager. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -7083,17 +7086,16 @@ Obtains the system capability manager. **Example** - ``` + ```ts let samgr = rpc.IPCSkeleton.getContextObject(); console.log("RpcServer: getContextObject result: " + samgr); ``` - ### getCallingPid static getCallingPid(): number -Obtains the PID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the PID of the process will be returned. +Obtains the PID of the caller. This API is a static method, which is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the PID of the process will be returned. **System capability**: SystemCapability.Communication.IPC.Core @@ -7105,7 +7107,7 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callerPid = rpc.IPCSkeleton.getCallingPid(); @@ -7115,12 +7117,11 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob } ``` - ### getCallingUid static getCallingUid(): number -Obtains the UID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the UID of the process will be returned. +Obtains the UID of the caller. This API is a static method, which is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the UID of the process will be returned. **System capability**: SystemCapability.Communication.IPC.Core @@ -7132,7 +7133,7 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callerUid = rpc.IPCSkeleton.getCallingUid(); @@ -7142,7 +7143,6 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob } ``` - ### getCallingTokenId8+ static getCallingTokenId(): number; @@ -7151,16 +7151,15 @@ Obtains the caller's token ID, which is used to verify the caller identity. **System capability**: SystemCapability.Communication.IPC.Core - **Return value** - + | Type | Description | | ------ | --------------------- | | number | Token ID of the caller obtained.| - + **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); @@ -7187,7 +7186,7 @@ Obtains the ID of the device hosting the caller's process. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID(); @@ -7197,12 +7196,11 @@ Obtains the ID of the device hosting the caller's process. } ``` - ### getLocalDeviceID static getLocalDeviceID(): string -Obtains the local device ID. +Obtains the local device ID. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -7214,7 +7212,7 @@ Obtains the local device ID. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID(); @@ -7224,12 +7222,11 @@ Obtains the local device ID. } ``` - ### isLocalCalling static isLocalCalling(): boolean -Checks whether the remote process is a process of the local device. +Checks whether the remote process is a process of the local device. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -7241,7 +7238,7 @@ Checks whether the remote process is a process of the local device. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let isLocalCalling = rpc.IPCSkeleton.isLocalCalling(); @@ -7251,12 +7248,11 @@ Checks whether the remote process is a process of the local device. } ``` - ### flushCmdBuffer9+ static flushCmdBuffer(object: IRemoteObject): void -Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. +Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. This API is a static method. It is recommended that this method be called before any time-sensitive operation is performed. **System capability**: SystemCapability.Communication.IPC.Core @@ -7269,7 +7265,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7284,14 +7280,13 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp } ``` - ### flushCommands(deprecated) >This API is no longer maintained since API version 9. You are advised to use [flushCmdBuffer](#flushcmdbuffer9). static flushCommands(object: IRemoteObject): number -Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. +Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. This API is a static method. It is recommended that this method be called before any time-sensitive operation is performed. **System capability**: SystemCapability.Communication.IPC.Core @@ -7309,7 +7304,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -7338,7 +7333,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp static resetCallingIdentity(): string -Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. +Changes the UID and PID of the remote user to the UID and PID of the local user. This API is a static method. You can use it in scenarios such as identity authentication. **System capability**: SystemCapability.Communication.IPC.Core @@ -7350,7 +7345,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); @@ -7365,7 +7360,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. static restoreCallingIdentity(identity: string): void -Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. +Changes the UID and PID of the remote user to the UID and PID of the local user. This API is a static method. You can use it in scenarios such as identity authentication. **System capability**: SystemCapability.Communication.IPC.Core @@ -7377,7 +7372,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = null; @@ -7392,14 +7387,13 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. } ``` - ### setCallingIdentity(deprecated) >This API is no longer maintained since API version 9. You are advised to use [restoreCallingIdentity](#restorecallingidentity9). static setCallingIdentity(identity: string): boolean -Restores the UID and PID of the remote user. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. +Restores the UID and PID of the remote user. This API is a static method. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. **System capability**: SystemCapability.Communication.IPC.Core @@ -7417,7 +7411,7 @@ Restores the UID and PID of the remote user. It is usually called when the UID a **Example** - ``` + ```ts class Stub extends rpc.RemoteObject { onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = null; @@ -7433,7 +7427,6 @@ Restores the UID and PID of the remote user. It is usually called when the UID a } ``` - ## RemoteObject Provides methods to implement **RemoteObject**. The service provider must inherit from this class. @@ -7476,11 +7469,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch | Type | Description | | ------- | --------------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.| **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -7519,7 +7512,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch reply.reclaim(); ``` - ### sendRequest8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -7547,7 +7539,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -7617,7 +7609,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7648,7 +7640,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn }); ``` - ### sendMessageRequest9+ sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void @@ -7669,7 +7660,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7697,7 +7688,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn testRemoteObject.sendMessageRequest(1, data, reply, option, sendRequestCallback); ``` - ### sendRequest8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). @@ -7720,7 +7710,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -7762,7 +7752,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch testRemoteObject.sendRequest(1, data, reply, option, sendRequestCallback); ``` - ### onRemoteRequest8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [onRemoteMessageRequest](#onremotemessagerequest9). @@ -7790,7 +7779,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques **Example** - ```ets + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -7847,12 +7836,12 @@ Provides a response to **sendMessageRequest()**. The server processes the reques | Type | Description | | ----------------- | ---------------------------------------------------------------------------------------------- | - | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| + | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. The value **true** means the operation is successful; the value **false** means the opposite.| | Promise\ | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. | **Example**: Overload **onRemoteMessageRequest** to process requests synchronously. - ```ets + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7872,7 +7861,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques **Example**: Overload **onRemoteMessageRequest** to process requests asynchronously. - ```ets + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7895,7 +7884,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques **Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests synchronously. - ```ets + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7926,7 +7915,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques **Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests asynchronously. - ```ets + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7957,7 +7946,6 @@ Provides a response to **sendMessageRequest()**. The server processes the reques } ``` - ### getCallingUid getCallingUid(): number @@ -7973,7 +7961,7 @@ Obtains the UID of the remote process. **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -7999,7 +7987,7 @@ Obtains the PID of the remote process. **Example** - ``` + ```ts class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); @@ -8013,7 +8001,7 @@ Obtains the PID of the remote process. getLocalInterface(descriptor: string): IRemoteBroker -Obtains the interface. +Obtains the interface descriptor. **System capability**: SystemCapability.Communication.IPC.Core @@ -8032,7 +8020,7 @@ Obtains the interface. **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -8057,7 +8045,6 @@ Obtains the interface. } ``` - ### queryLocalInterface(deprecated) >This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). @@ -8082,7 +8069,7 @@ Checks whether the remote object corresponding to the specified interface token **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -8106,7 +8093,6 @@ Checks whether the remote object corresponding to the specified interface token let broker = testRemoteObject.queryLocalInterface("testObject"); ``` - ### getDescriptor9+ getDescriptor(): string @@ -8131,7 +8117,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -8157,7 +8143,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode console.log("RpcServer: descriptor is: " + descriptor); ``` - ### getInterfaceDescriptor(deprecated) >This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). @@ -8176,7 +8161,7 @@ Obtains the interface descriptor. **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -8201,7 +8186,6 @@ Obtains the interface descriptor. console.log("RpcServer: descriptor is: " + descriptor); ``` - ### modifyLocalInterface9+ modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void @@ -8217,10 +8201,9 @@ Binds an interface descriptor to an **IRemoteBroker** object. | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | | descriptor | string | Yes | Interface descriptor.| - **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -8267,7 +8250,7 @@ Binds an interface descriptor to an **IRemoteBroker** object. **Example** - ``` + ```ts class MyDeathRecipient { onRemoteDied() { console.log("server died"); @@ -8294,15 +8277,14 @@ Binds an interface descriptor to an **IRemoteBroker** object. let testRemoteObject = new TestRemoteObject("testObject"); ``` - ## Ashmem8+ Provides methods related to anonymous shared memory objects, including creating, closing, mapping, and unmapping an **Ashmem** object, reading data from and writing data to an **Ashmem** object, obtaining the **Ashmem** size, and setting **Ashmem** protection. -The table below describes the protection types of the mapped memory. - **System capability**: SystemCapability.Communication.IPC.Core +The table below describes the protection types of the mapped memory. + | Name | Value | Description | | ---------- | --- | ------------------ | | PROT_EXEC | 4 | The mapped memory is executable. | @@ -8310,12 +8292,11 @@ The table below describes the protection types of the mapped memory. | PROT_READ | 1 | The mapped memory is readable. | | PROT_WRITE | 2 | The mapped memory is writeable. | - ### create9+ static create(name: string, size: number): Ashmem -Creates an **Ashmem** object with the specified name and size. +Creates an **Ashmem** object with the specified name and size. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -8332,10 +8313,9 @@ Creates an **Ashmem** object with the specified name and size. | ------ | ---------------------------------------------- | | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| - **Example** - ``` + ```ts let ashmem; try { ashmem = rpc.Ashmem.create("ashmem", 1024*1024); @@ -8347,14 +8327,13 @@ Creates an **Ashmem** object with the specified name and size. console.log("RpcTest: get ashemm by create : " + ashmem + " size is : " + size); ``` - ### createAshmem8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [create](#create9). static createAshmem(name: string, size: number): Ashmem -Creates an **Ashmem** object with the specified name and size. +Creates an **Ashmem** object with the specified name and size. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core @@ -8373,18 +8352,17 @@ Creates an **Ashmem** object with the specified name and size. **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let size = ashmem.getAshmemSize(); console.log("RpcTest: get ashemm by createAshmem : " + ashmem + " size is : " + size); ``` - ### create9+ static create(ashmem: Ashmem): Ashmem -Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. +Creates an **Ashmem** object by copying the file descriptor of an existing **Ashmem** object. The two **Ashmem** objects point to the same shared memory region. **System capability**: SystemCapability.Communication.IPC.Core @@ -8403,7 +8381,7 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **Example** - ``` + ```ts let ashmem2; try { let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); @@ -8416,14 +8394,13 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing console.log("RpcTest: get ashemm by create : " + ashmem2 + " size is : " + size); ``` - ### createAshmemFromExisting8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [create](#create9). static createAshmemFromExisting(ashmem: Ashmem): Ashmem -Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. +Creates an **Ashmem** object by copying the file descriptor of an existing **Ashmem** object. The two **Ashmem** objects point to the same shared memory region. **System capability**: SystemCapability.Communication.IPC.Core @@ -8441,14 +8418,13 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem); let size = ashmem2.getAshmemSize(); console.log("RpcTest: get ashemm by createAshmemFromExisting : " + ashmem2 + " size is : " + size); ``` - ### closeAshmem8+ closeAshmem(): void @@ -8459,12 +8435,11 @@ Closes this **Ashmem** object. **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.closeAshmem(); ``` - ### unmapAshmem8+ unmapAshmem(): void @@ -8475,12 +8450,11 @@ Deletes the mappings for the specified address range of this **Ashmem** object. **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.unmapAshmem(); ``` - ### getAshmemSize8+ getAshmemSize(): number @@ -8497,13 +8471,12 @@ Obtains the memory size of this **Ashmem** object. **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let size = ashmem.getAshmemSize(); console.log("RpcTest: get ashmem is " + ashmem + " size is : " + size); ``` - ### mapTypedAshmem9+ mapTypedAshmem(mapType: number): void @@ -8528,7 +8501,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); try { ashmem.mapTypedAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); @@ -8538,7 +8511,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### mapAshmem8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [mapTypedAshmem](#maptypedashmem9). @@ -8559,17 +8531,16 @@ Creates the shared file mapping on the virtual address space of this process. Th | Type | Description | | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the mapping is created; returns **false** otherwise.| **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapReadAndWrite = ashmem.mapAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); console.log("RpcTest: map ashmem result is : " + mapReadAndWrite); ``` - ### mapReadWriteAshmem9+ mapReadWriteAshmem(): void @@ -8588,7 +8559,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); try { ashmem.mapReadWriteAshmem(); @@ -8598,7 +8569,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### mapReadAndWriteAshmem8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [mapReadWriteAshmem](#mapreadwriteashmem9). @@ -8613,17 +8583,16 @@ Maps the shared file to the readable and writable virtual address space of the p | Type | Description | | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the mapping is created; returns **false** otherwise.| **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); console.log("RpcTest: map ashmem result is : " + mapResult); ``` - ### mapReadonlyAshmem9+ mapReadonlyAshmem(): void @@ -8642,7 +8611,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); try { ashmem.mapReadonlyAshmem(); @@ -8652,7 +8621,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### mapReadOnlyAshmem8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [mapReadonlyAshmem](#mapreadonlyashmem9). @@ -8667,17 +8635,16 @@ Maps the shared file to the read-only virtual address space of the process. | Type | Description | | ------- | ----------------------------------------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | boolean | Returns **true** if the mapping is created; returns **false** otherwise.| **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadOnlyAshmem(); console.log("RpcTest: Ashmem mapReadOnlyAshmem result is : " + mapResult); ``` - ### setProtectionType9+ setProtectionType(protectionType: number): void @@ -8702,7 +8669,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); try { ashmem.setProtection(ashmem.PROT_READ); @@ -8712,7 +8679,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### setProtection8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [setProtectionType](#setprotectiontype9). @@ -8737,13 +8703,12 @@ Sets the protection level of the memory region to which the shared file is mappe **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let result = ashmem.setProtection(ashmem.PROT_READ); console.log("RpcTest: Ashmem setProtection result is : " + result); ``` - ### writeAshmem9+ writeAshmem(buf: number[], size: number, offset: number): void @@ -8770,7 +8735,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.mapReadWriteAshmem(); var ByteArrayVar = [1, 2, 3, 4, 5]; @@ -8782,7 +8747,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### writeToAshmem8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [writeAshmem](#writeashmem9). @@ -8805,11 +8769,11 @@ Writes data to the shared file associated with this **Ashmem** object. | Type | Description | | ------- | ----------------------------------------------------------------------------------------- | - | boolean | Returns **true** is the data is written successfully; returns **false** otherwise.| + | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.| **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); console.info("RpcTest map ashmem result is " + mapResult); @@ -8818,7 +8782,6 @@ Writes data to the shared file associated with this **Ashmem** object. console.log("RpcTest: write to Ashmem result is : " + writeResult); ``` - ### readAshmem9+ readAshmem(size: number, offset: number): number[] @@ -8850,7 +8813,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode **Example** - ``` + ```ts let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.mapReadWriteAshmem(); var ByteArrayVar = [1, 2, 3, 4, 5]; @@ -8864,7 +8827,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode } ``` - ### readFromAshmem8+(deprecated) >This API is no longer maintained since API version 9. You are advised to use [readAshmem](#readashmem9). @@ -8890,7 +8852,7 @@ Reads data from the shared file associated with this **Ashmem** object. **Example** - ``` + ```ts let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); console.info("RpcTest map ashmem result is " + mapResult); @@ -8899,4 +8861,5 @@ Reads data from the shared file associated with this **Ashmem** object. console.log("RpcTest: write to Ashmem result is : " + writeResult); let readResult = ashmem.readFromAshmem(5, 0); console.log("RpcTest: read to Ashmem result is : " + readResult); - ``` + ``` + diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index e3718c5878ccae3e63f8bdfae8b37061599fffda..bddad259f782ca6ece549da06ab6ae4e69bbc441 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 @@ -135,6 +135,7 @@ runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. Checks whether a specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. @@ -164,6 +165,7 @@ runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, ( isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> +> NOTE
> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. Checks whether a specified type of **RunningLock** is supported. This API uses a promise to return the result. @@ -198,6 +200,7 @@ runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND) createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. Creates a **RunningLock** object. @@ -230,6 +233,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> +> NOTE
> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. Creates a **RunningLock** object. @@ -389,6 +393,7 @@ runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) lock(timeout: number): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9) instead. Locks and holds a **RunningLock** object. @@ -420,6 +425,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B unlock(): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9) instead. Releases a **RunningLock** object. @@ -445,6 +451,7 @@ runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.B isUsed(): boolean +> NOTE
> This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9) instead. Checks the hold status of the **Runninglock** object. 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 81c05044174b46f17b6d5224f923167256290e4f..0c0243c3dbe85939b1da5623baac1b3137926e15 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** > @@ -687,7 +687,7 @@ promise.then(data => { }); ``` -## sim.**setShowName**8+ +## sim.setShowName8+ setShowName\(slotId: number, name: string, callback: AsyncCallback\): void @@ -716,7 +716,7 @@ sim.setShowName(0, name, (err, data) => { }); ``` -## sim.**setShowName**8+ +## sim.setShowName8+ setShowName\(slotId: number, name: string\): Promise\ @@ -753,7 +753,7 @@ promise.then(data => { }); ``` -## sim.**getShowName**8+ +## sim.getShowName8+ getShowName(slotId: number, callback: AsyncCallback): void @@ -781,7 +781,7 @@ sim.getShowName(0, (err, data) => { ``` -## sim.**getShowName**8+ +## sim.getShowName8+ getShowName(slotId: number): Promise @@ -816,7 +816,7 @@ promise.then(data => { }); ``` -## sim.**setShowNumber**8+ +## sim.setShowNumber8+ setShowNumber\(slotId: number, number: string, callback: AsyncCallback\): void @@ -846,7 +846,7 @@ sim.setShowNumber(0, number, (err, data) => { ``` -## sim.**setShowNumber**8+ +## sim.setShowNumber8+ setShowNumber\(slotId: number, number: string\): Promise\ @@ -883,7 +883,7 @@ promise.then(data => { }); ``` -## sim.**getShowNumber**8+ +## sim.getShowNumber8+ getShowNumber(slotId: number, callback: AsyncCallback): void @@ -911,7 +911,7 @@ sim.getShowNumber(0, (err, data) => { ``` -## sim.**getShowNumber**8+ +## sim.getShowNumber8+ getShowNumber(slotId: number): Promise @@ -946,7 +946,7 @@ promise.then(data => { }); ``` -## sim.**activateSim**8+ +## sim.activateSim8+ activateSim(slotId: number, callback: AsyncCallback): void @@ -974,7 +974,7 @@ sim.activateSim(0, (err, data) => { ``` -## sim.**activateSim**8+ +## sim.activateSim8+ activateSim(slotId: number): Promise\ @@ -1009,7 +1009,7 @@ promise.then(data => { }); ``` -## sim.**deactivateSim**8+ +## sim.deactivateSim8+ deactivateSim(slotId: number, callback: AsyncCallback): void @@ -1037,7 +1037,7 @@ sim.deactivateSim(0, (err, data) => { ``` -## sim.**deactivateSim**8+ +## sim.deactivateSim8+ deactivateSim(slotId: number): Promise\ @@ -1346,7 +1346,7 @@ promise.then(data => { }); ``` -## sim.**unlockPin**7+ +## sim.unlockPin7+ unlockPin(slotId: number, pin: string, callback: AsyncCallback): void @@ -1376,7 +1376,7 @@ sim.unlockPin(0, pin, (err, data) => { ``` -## sim.**unlockPin**7+ +## sim.unlockPin7+ unlockPin(slotId: number, pin: string): Promise<LockStatusResponse\> @@ -1413,7 +1413,7 @@ promise.then(data => { }); ``` -## sim.**unlockPuk**7+ +## sim.unlockPuk7+ unlockPuk(slotId: number, newPin: string, puk: string ,callback: AsyncCallback): void @@ -1445,7 +1445,7 @@ sim.unlockPuk(0, newPin, puk, (err, data) => { ``` -## sim.**unlockPuk**7+ +## sim.unlockPuk7+ unlockPuk(slotId: number, newPin: string, puk: string): Promise<LockStatusResponse\> @@ -1484,7 +1484,7 @@ promise.then(data => { }); ``` -## sim.**unlockPin**28+ +## sim.unlockPin28+ unlockPin2(slotId: number, pin2: string, callback: AsyncCallback): void @@ -1514,7 +1514,7 @@ sim.unlockPin2(0, pin2, (err, data) => { ``` -## sim.**unlockPin**28+ +## sim.unlockPin28+ unlockPin2(slotId: number, pin2: string): Promise<LockStatusResponse\> @@ -1551,7 +1551,7 @@ promise.then(data => { }); ``` -## sim.**unlockPuk**28+ +## sim.unlockPuk28+ unlockPuk2(slotId: number, newPin2: string, puk2: string, callback: AsyncCallback): void @@ -1583,7 +1583,7 @@ sim.unlockPuk2(0, newPin2, puk2, (err, data) => { ``` -## sim.**unlockPuk2**8+ +## sim.unlockPuk28+ unlockPuk2(slotId: number, newPin2: string, puk2: string): Promise<LockStatusResponse\> diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index c26311312c5cc2360ddf4f3784f66bba05b0f5b1..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** > diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index 32c4d78bfbd2fbace12d6294d03488f06aed27ba..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 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..18c6c703d5e033c216fb47594fa8116fc581dfc6 100644 --- a/en/application-dev/reference/apis/js-apis-system-device.md +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -1,15 +1,16 @@ -# @system.device +# @system.device (Device Information) The **device** module provides APIs for checking information about the current device. > **NOTE** +> > - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [@ohos.deviceInfo](js-apis-device-info.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. ## Modules to Import -``` +```typescript import device from '@system.device'; ``` @@ -39,14 +40,14 @@ Obtains the device information. | -------- | -------- | -------- | | brand | string | Brand.| | manufacturer | string | Manufacturer.| -| model | string | Model. | +| model | string | Model.| | product | string | Product number.| | language4+ | string | System language.| | region4+ | string | System region.| | windowWidth | number | Window width.| | windowHeight | number | Window height.| | screenDensity4+ | number | Screen density.| -| screenShape4+ | string | Screen shape. The options are as follows:
- **rect**: rectangle screen
- **circle**: circle screen| +| screenShape4+ | string | Screen shape. The options are as follows:
- **rect**: rectangular screen
- **circle**: round screen| | apiVersion4+ | number | API version.| | releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions.| | deviceType4+ | string | Device type.| @@ -55,11 +56,11 @@ Obtains the device information. | Error Code| Description| | -------- | -------- | -| 200 | The returned result contains information that cannot be obtained.| +| 200 | Certain information cannot be obtained.| **Example** -``` +```typescript export default { getInfo() { device.getInfo({ 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-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index 608bb4d3d3ee2ec6d4c48e7d9b7a4abd01e52c2e..91b35f9b29ce4a18b32e19741b14337322ab00bf 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,4 +1,4 @@ -# @system.notification +# @system.notification (Notification) > **NOTE** > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). @@ -9,7 +9,7 @@ ## Modules to Import -``` +```ts import notification from '@system.notification'; ``` @@ -59,9 +59,9 @@ export default { clickAction: { bundleName: 'com.example.testapp', abilityName: 'notificationDemo', - uri: '/path/to/notification', - }, + uri: '/path/to/notification' + } }); - }, + } } ``` 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 1d47c8883ae8d3cc4be49d19845ce1b3e3d5bb2a..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 @@ -# @system.router +# @system.router (Page Routing) The **Router** module provides APIs to access pages through URIs. 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-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index 3138f52c7089ba4a53809711c442b79f6a1aa1aa..9235dace79f11592adb3d84fbde631c33ec21780 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -1,4 +1,4 @@ -# tagSession +# tagSession (Standard NFC Tag Session) The **tagSession** module provides common APIs for establishing connections and transferring data. @@ -26,9 +26,12 @@ getTagInfo(): tag.TagInfo Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getTagInfo](js-apis-nfcTag.md#taggettaginfo9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -54,9 +57,12 @@ connectTag(): boolean; Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.connect](#tagsessionconnect9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -76,15 +82,52 @@ let connectStatus = tag.getIsoDep(tagInfo).connectTag(); console.log("connectStatus: " + connectStatus); ``` +### tagSession.connect9+ + +connect(): void; + +Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +try { + tag.getIsoDep(tagInfo).connect(); + console.log("tag connect success"); +} catch (busiError) { + console.log("tag connect busiError: " + busiError); +} +``` + ### tagSession.reset() reset(): void Resets the connection to this tag. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.resetConnection](#tagsessionresetconnection9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Example** @@ -97,15 +140,52 @@ import tag from '@ohos.nfc.tag'; tag.getIsoDep(tagInfo).reset(); ``` +### tagSession.resetConnection()9+ + +resetConnection(): void + +Resets the connection to this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +try { + tag.getIsoDep(tagInfo).resetConnection(); + console.log("tag resetConnection success"); +} catch (busiError) { + console.log("tag resetConnection busiError: " + busiError); +} +``` + ### tagSession.isTagConnected isTagConnected(): boolean Checks whether the tag is connected. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.isConnected](#tagsessionisconnected9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -125,15 +205,50 @@ let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected(); console.log("isTagConnected: " + isTagConnected); ``` +### tagSession.isConnected9+ + +isConnected(): boolean + +Checks whether the tag is connected. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the tag is connected; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +try { + var isConnected = tag.getIsoDep(tagInfo).isConnected(); + console.log("tag isConnected = " + isConnected); +} catch (busiError) { + console.log("tag isConnected busiError: " + busiError); +} +``` + ### tagSession.getMaxSendLength getMaxSendLength(): number Obtains the maximum length of the data that can be sent to this tag. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.getMaxTransmitSize](#tagsessiongetmaxtransmitsize9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -152,15 +267,57 @@ let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength(); console.log("tag maxSendLen: " + maxSendLen); ``` +### tagSession.getMaxTransmitSize9+ + +getMaxTransmitSize(): number + +Obtains the maximum length of the data that can be sent to this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Maximum data length obtained. The value cannot be a negative number.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +try { + var maxTransmitSize = tag.getIsoDep(tagInfo).getMaxTransmitSize(); + console.log("tag maxTransmitSize = " + maxTransmitSize); +} catch (busiError) { + console.log("tag getMaxTransmitSize busiError: " + busiError); +} +``` + ### tagSession.getSendDataTimeout getSendDataTimeout(): number Obtains the timeout period for sending data to this tag, in milliseconds. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.getTimeout](#tagsessiongettimeout9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Return value** @@ -180,15 +337,58 @@ let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout(); console.log("tag sendDataTimeout: " + sendDataTimeout); ``` +### tagSession.getTimeout9+ + +getTimeout(): number + +Obtains the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +try { + var timeout = tag.getIsoDep(tagInfo).getTimeout(); + console.log("tag timeout = " + timeout); +} catch (busiError) { + console.log("tag getTimeout busiError: " + busiError); +} +``` + ### tagSession.setSendDataTimeout setSendDataTimeout(timeout: number): boolean Sets the timeout period for sending data to this tag, in milliseconds. +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.setTimeout](#tagsessionsettimeout9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -215,15 +415,59 @@ let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs); console.log("tag setSendDataTimeout setStatus: " + setStatus); ``` +### tagSession.setTimeout9+ + +setTimeout(timeout: number): void + +Sets the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let timeoutMs = 700; // Change it as required. +try { + tag.getIsoDep(tagInfo).setTimeout(timeoutMs); + console.log("tag setTimeout success"); +} catch (busiError) { + console.log("tag setTimeout busiError: " + busiError); +} +``` + ### tagSession.sendData sendData(data: number[]): Promise Sends data to this tag. 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 [tagSession.transmit](#tagsessiontransmit9). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -267,9 +511,12 @@ sendData(data: number[], callback: AsyncCallback): void Sends data to this tag. This API uses an asynchronous callback to return the result. +> **NOTE** +> This parameter is supported since API version 7 and discarded since API version 9. You are advised to use [tagSession.transmit](#tagsessiontransmit9-1). + **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC.Core +**System capability**: SystemCapability.Communication.NFC.Tag **Parameters** @@ -303,3 +550,123 @@ tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> { } }); ``` + +### tagSession.transmit9+ + +transmit(data: number[]): Promise + +Transmits data to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to transmit. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise | Promise used to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +try { + if (!tag.getIsoDep(tagInfo).isConnected()) { + tag.getIsoDep(tagInfo).connect(); + } +} catch (busiError) { + console.log("tag connect busiError: " + busiError); + return; +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +try { + tag.getIsoDep(tagInfo).transmit(cmdData).then((response) => { + console.log("tagSession transmit Promise response: " + response); + }).catch((err)=> { + console.log("tagSession transmit Promise err: " + err); + }); +} catch (busiError) { + console.log("tag transmit busiError: " + busiError); + return; +} +``` + +### tagSession.transmit9+ + +transmit(data: number[], callback: AsyncCallback): void + +Transmits data to this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Tag + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to transmit. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**. | +| callback | AsyncCallback | Yes| Callback invoked to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +try { + if (!tag.getIsoDep(tagInfo).isConnected()) { + tag.getIsoDep(tagInfo).connect(); + } +} catch (busiError) { + console.log("tag connect busiError: " + busiError); + return; +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +try { + tag.getIsoDep(tagInfo).transmit(cmdData, (err, response)=> { + if (err) { + console.log("tagSession transmit AsyncCallback err: " + err); + } else { + console.log("tagSession transmit AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("tag transmit busiError: " + busiError); + return; +} + +``` 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..5291826d6fab799eb0684753379399562772f4cf 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 @@ -118,6 +118,7 @@ try { subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead. Subscribes to thermal level changes. @@ -142,6 +143,7 @@ thermal.subscribeThermalLevel((level) => { unsubscribeThermalLevel(callback?: AsyncCallback\): void +> NOTE
> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead. Unsubscribes from thermal level changes. @@ -166,6 +168,7 @@ thermal.unsubscribeThermalLevel(() => { getThermalLevel(): ThermalLevel +> NOTE
> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead. Obtains the current thermal level. diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md index 0b52b8721ba891eacb099b86907458d72064dd9a..e66c1569fb5fae99e9124183e02b4ed32fb46d9c 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. @@ -13,6 +13,8 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## Action +Enumerates touch actions. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | @@ -24,6 +26,8 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## ToolType +Enumerates tool types. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | @@ -39,6 +43,8 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## SourceType +Enumerates source types. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name | Value | Description | @@ -49,6 +55,8 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## Touch +Defines a touch action. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name| Type| Readable| Writable| Description| @@ -74,6 +82,8 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ## TouchEvent +Defines a touch event. + **System capability**: SystemCapability.MultimodalInput.Input.Core | Name| Type| Readable| Writable| Description| 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..a0a0dc40c837d45da72209b5faa6a57ed0b95909 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. @@ -583,7 +584,7 @@ let ret = usb.usbFunctionsToString(funcs); ## usb.setCurrentFunctions -setCurrentFunctions(funcs: FunctionType): Promise\ +setCurrentFunctions(funcs: FunctionType): Promise\ Sets the current USB function list in Device mode. @@ -601,13 +602,17 @@ Sets the current USB function list in Device mode. | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| +| Promise\ | Promise used to return the result.| **Example** ```js let funcs = HDC; -let ret = usb.setCurrentFunctions(funcs); +usb.setCurrentFunctions(funcs).then(() => { + console.info('usb setCurrentFunctions successfully.'); +}).catch(err => { + console.error('usb setCurrentFunctions failed: ' + err.code + ' message: ' + err.message); +}); ``` ## usb.getCurrentFunctions @@ -684,7 +689,7 @@ let ret = usb.getSupportedModes(0); ## usb.setPortRoles -setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ +setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer). @@ -704,12 +709,17 @@ Sets the role types supported by a specified port, which can be **powerRole** (f | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| +| Promise\ | Promise used to return the result. | **Example** ```js -let ret = usb.getSupportedModes(0); +let portId = 1; +usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { + console.info('usb setPortRoles successfully.'); +}).catch(err => { + console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); +}); ``` ## USBEndpoint diff --git a/en/application-dev/reference/apis/js-apis-userFileManager.md b/en/application-dev/reference/apis/js-apis-userFileManager.md index 5249fa7cc0feff1afbf6e79fe7fb3263434d346a..4de8727e244f81858ca14137197ca676c0a2c792 100644 --- a/en/application-dev/reference/apis/js-apis-userFileManager.md +++ b/en/application-dev/reference/apis/js-apis-userFileManager.md @@ -1,4 +1,4 @@ -# @ohos.filemanagement.userFileManager +# @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). @@ -38,6 +38,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and **Example** ```ts +// The userFileManager instance obtained is a global object. It is used by default in subsequent operations. If the code snippet is not added, an error will be reported indicating that mgr is not defined. const context = getContext(this); let mgr = userFileManager.getUserFileMgr(context); ``` @@ -127,7 +128,7 @@ async function example() { predicates: predicates }; try { - var fetchResult = await mgr.getPhotoAssets(fetchOptions); + let fetchResult = await mgr.getPhotoAssets(fetchOptions); if (fetchResult != undefined) { console.info('fetchResult success'); let fileAsset = await fetchResult.getFirstObject(); @@ -410,7 +411,7 @@ Obtains the system album. This API uses a promise to return the result. async function example() { console.info('getPrivateAlbumDemo'); try { - var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let trashAlbum = await fetchResult.getFirstObject(); console.info('first album.albumName = ' + trashAlbum.albumName); } catch (err) { 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..f555df967ddc3a5f11d498bae739be54d1ad53ad 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; - // ... + // 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-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 6af6bc0a51e3a862a159b6bf450c9ce90bd31346..9eb6f28a9880ada20a1a5c6bce2bac006a6efd5f 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -263,7 +263,7 @@ Represents the WLAN configuration. ## IpType7+ -Enumerate the IP address types. +Enumerates the IP address types. **System API**: This is a system API. diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md index 8e3526343a3f62066af7686b4fbe5cb587fa1cbc..46c43be00e3df1ec2f9cc56ea2f0f834a0c6cc12 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManager.md +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -1,5 +1,4 @@ # WLAN - The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. > **NOTE** @@ -1038,7 +1037,7 @@ Removes the specified network configuration. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| id | number | Yes| ID of the network configuration to remove.| + | id | number | Yes| ID of the network configuration to remove.| **Return value** @@ -1788,7 +1787,7 @@ Unregisters the WLAN state change events. ``` -## wifi.on('wifiConnectionChange')7+ +## wifi.on('wifiConnectionChange')9+ on(type: "wifiConnectionChange", callback: Callback<number>): void diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md index f024294ddbc393a57394a1ad20d2686d30060e52..656fa873965ceceb94e2e675380ad72577017a33 100644 --- a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -1,5 +1,4 @@ # WLAN Extension Interface - This **wifiext** module provides WLAN extension interfaces for non-universal products. > **NOTE** @@ -26,9 +25,9 @@ Enables the WLAN hotspot. **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.| ## wifiext.disableHotspot @@ -43,9 +42,9 @@ Disables the WLAN hotspot. **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.| ## wifiext.getSupportedPowerModel @@ -60,9 +59,9 @@ Obtains the supported power models. This API uses a promise to return the result **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| +| Type| Description| +| -------- | -------- | +| Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| ## PowerModel @@ -90,9 +89,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel @@ -107,9 +106,9 @@ Obtains the power model. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| ## wifiext.getPowerModel @@ -124,16 +123,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| ## wifiext.setPowerModel setPowerModel(model: PowerModel) : boolean; - Sets the power model. +Sets the power model. **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT @@ -141,12 +140,12 @@ setPowerModel(model: PowerModel) : boolean; **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | model | [PowerModel](#powermodel) | Yes| Power model to set.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** - | **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.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 70961ffe279bf5543bbe28168f8571a54ca46651..51efac191d9492b2861eb3f42a58082b019b1e3a 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,4 +1,4 @@ -# @ohos.wifiext +# @ohos.wifiext (WLAN Extension) This **wifiext** module provides WLAN extension interfaces for non-universal products. @@ -26,9 +26,9 @@ Enables the WLAN hotspot. **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.| ## wifiext.disableHotspot @@ -43,9 +43,9 @@ Disables the WLAN hotspot. **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.| ## wifiext.getSupportedPowerModel @@ -60,9 +60,9 @@ Obtains the supported power models. This API uses a promise to return the result **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| +| Type| Description| +| -------- | -------- | +| Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| ## PowerModel @@ -90,9 +90,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel @@ -107,9 +107,9 @@ Obtains the power model. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| ## wifiext.getPowerModel @@ -124,16 +124,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| ## wifiext.setPowerModel setPowerModel(model: PowerModel) : boolean; - Sets the power model. +Sets the power model. **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT @@ -141,12 +141,12 @@ setPowerModel(model: PowerModel) : boolean; **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | model | [PowerModel](#powermodel) | Yes| Power model to set.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** - | **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.| 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/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/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..34e2663dc5e17b7c950a50bf140b3204f4f74e73 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); @@ -1735,9 +1735,9 @@ Creates a radial gradient and returns a **CanvasGradient** object. // Radial gradient: inner circle(200,200,r:50) outer circle(200,200,r:200) var gradient = ctx.createRadialGradient(200,200,50, 200,200,200); // 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-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-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/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index eb5d3e065f671025dbdd28450b53f2fa955996c2..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. 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.| +| 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 @@ -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** > @@ -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 @@ -355,9 +356,9 @@ struct ImageExample3 { ### Rendering Sandbox Images ```ts -import fileio from '@ohos.fileio' -import fs from '@ohos.file.fs' -import context from '@ohos.application.context' +import fileio from '@ohos.fileio'; +import fs from '@ohos.file.fs'; +import context from '@ohos.app.ability.context'; @Entry @Component 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-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 1e0ce0647f6067d5396e131e6bcc7ac75bc6a718..138578c1ecd983536ea7688a1892baa7dec2a0ab 100644 --- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -773,7 +773,7 @@ Clears the content in a rectangle on the canvas. Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffffff') + .backgroundColor('#ffff00') .onReady(() =>{ this.context.fillStyle = 'rgb(0,0,255)' this.context.fillRect(20,20,200,200) @@ -1583,7 +1583,7 @@ struct Fill { region.lineTo(270, 90) region.closePath() // Fill path - this.context.fillStyle = 'green' + this.context.fillStyle = '#00ff00' this.context.fill(region, "evenodd") }) } @@ -1749,7 +1749,7 @@ Rotates a canvas clockwise around its coordinate axes. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.rotate(45 * Math.PI / 180) // Rotate the rectangle 45 degrees + this.context.rotate(45 * Math.PI / 180) this.context.fillRect(70, 20, 50, 50) }) } @@ -2417,7 +2417,7 @@ Restores the saved drawing context. .backgroundColor('#ffff00') .onReady(() =>{ this.context.save() // save the default state - this.context.fillStyle = "green" + this.context.fillStyle = "#00ff00" this.context.fillRect(20, 20, 100, 100) this.context.restore() // restore to the default state this.context.fillRect(150, 75, 100, 100) @@ -2455,7 +2455,7 @@ Saves all states of the canvas in the stack. This API is usually called when the .backgroundColor('#ffff00') .onReady(() =>{ this.context.save() // save the default state - this.context.fillStyle = "green" + this.context.fillStyle = "#00ff00" this.context.fillRect(20, 20, 100, 100) this.context.restore() // restore to the default state this.context.fillRect(150, 75, 100, 100) @@ -2502,9 +2502,9 @@ Creates a linear gradient. .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) }) @@ -2553,9 +2553,9 @@ Creates a linear gradient. .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.context.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.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500) }) 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-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-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index dc3c3e9859a27813299a3ccb9e1ddaff47b88cea..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 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-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/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md index b286cbf232d6d334444b164117fa289b79f9a6c4..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,8 +34,11 @@ - 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 @@ -70,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-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-nfc.md b/en/application-dev/reference/errorcodes/errorcode-nfc.md index 500d870366c8a88a9036454ada2d0ffe0a3c04a9..1de2fd7e62e83f485b8377a61b0e7146d59ce62c 100644 --- a/en/application-dev/reference/errorcodes/errorcode-nfc.md +++ b/en/application-dev/reference/errorcodes/errorcode-nfc.md @@ -4,7 +4,7 @@ **Error Message** -NFC opening or closing state is abnormal in service. +NFC state is abnormal in service. **Description** @@ -12,11 +12,13 @@ The NFC service fails to enable or disable NFC. **Possible Causes** -Communication with the NFC service failed. +1. Communication with the NFC service failed. +2. The NFC chip communication is abnormal. **Solution** -Enable or disable NFC again. +1. Enable or disable NFC again. +2. Enable or disable NFC again or restart the device, and try again. ## 3100201 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-syntax-hml.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md index 2ebbe2b66d3bc4feac7fb0d090e2833e761f88c9..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 @@ -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": { diff --git a/en/application-dev/reference/native-lib/third_party_libuv/libuv.md b/en/application-dev/reference/native-lib/third_party_libuv/libuv.md index 5fbe6060835a391832904bd396635bdf00e2585d..452aa2861b7a42ad7fb714ec167f7bde93407e7e 100644 --- a/en/application-dev/reference/native-lib/third_party_libuv/libuv.md +++ b/en/application-dev/reference/native-lib/third_party_libuv/libuv.md @@ -6,13 +6,16 @@ -libuv is a cross-platform library that implements asynchronous I/O based on event loops. It is mainly used in Node.js. +[libuv](http://libuv.org/) is a cross-platform library that implements asynchronous I/O based on event loops. It is used in **Node.js**. ## Supported Capabilities -libuv implements cross-platform asynchronous I/O based on event loops. +Implements cross-platform asynchronous I/O based on event loops. -It supports standard lib interfaces. +Supports standard lib interfaces. +## API List + +[API documentation](http://docs.libuv.org/en/v1.x/api.html) 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 05d2d2864de5dc34947f43d1b54ab2480e039747..1be1ec0532e899d933aaa672d3e49437c5822b68 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -3,14 +3,15 @@ - Access Control - [Access Control (Permission) Overview](accesstoken-overview.md) - [Permission Application Guide](accesstoken-guidelines.md) - - [Permission Verification Guide](permission-verify-guidelines.md) - - [App Permission List](permission-list.md) + - [API Access Permission Verification](permission-verify-guidelines.md) + - [Application Permission List](permission-list.md) - User Authentication - [User Authentication Overview](userauth-overview.md) - [User Authentication Development](userauth-guidelines.md) - HUKS - [HUKS Overview](huks-overview.md) - [HUKS Development](huks-guidelines.md) + - [HUKS Cipher Algorithm Specifications](huks-appendix.md) - Crypto Framework - [Crypto Framework Overview](cryptoFramework-overview.md) - [Crypto Framework Development](cryptoFramework-guidelines.md) diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index 0e45400d14daae6417908bf13ed0127d1ccb7284..93b5b158051c29b5860ccb1480788db3a677a183 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -2,7 +2,7 @@ ## When to Use -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)](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 [Application Permission List](permission-list.md). This document describes the following operations: @@ -13,7 +13,7 @@ This document describes the following operations: ## Declaring Permissions in the Configuration File -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. The application bundle and configuration file vary with the application model. +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. > **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). @@ -119,7 +119,7 @@ For example, if an application needs to access audio files of a user and capture 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. -> **NOTE**
Each time before an API protected by a permission is accessed, the **requestPermissionsFromUser()** 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. +> **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. ### Stage Model @@ -127,20 +127,20 @@ 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()** 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()** indicates whether the application has the target permission. If yes, the target API can be called normally. - +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 window from '@ohos.window'; import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; import { Permissions } from '@ohos.abilityAccessCtrl'; export default class EntryAbility extends UIAbility { // ... - onWindowStageCreate(windowStage: Window.WindowStage) { + onWindowStageCreate(windowStage: window.WindowStage) { // Main window is created, set main page for this ability let context = this.context; let AtManager = abilityAccessCtrl.createAtManager(); @@ -220,7 +220,7 @@ onWindowStageCreate() { 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 [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install-list-capabilityjson). +- `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. @@ -244,4 +244,3 @@ By default, the **user_grant** permissions must be dynamically authorized by the } ] ``` - \ No newline at end of file diff --git a/en/application-dev/security/app-provision-structure.md b/en/application-dev/security/app-provision-structure.md index d31cd6c690769d9a3ec6767a7f8187f5d9bfc4e7..a772f024a4179af75e30dcf4f6bc0483ed0f86b0 100644 --- a/en/application-dev/security/app-provision-structure.md +++ b/en/application-dev/security/app-provision-structure.md @@ -4,18 +4,18 @@ 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. -| Name | Description | Data Type| Yes | 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| +| 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| +| 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 | 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 | +| 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: @@ -58,42 +58,42 @@ An example of the **HarmonyAppProvision** file is as follows: | 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| | ------------------------ | ------------------------------- | ------- | -------- | --------- | -| 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 | +| 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 [ACL](accesstoken-overview.md) configured for your application. It should be noted that you still need to add the ACL information to the **requestPermissions** attribute in the application configuration file. +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| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| 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 add the ACL information to the **requestPermissions** attribute in the application configuration 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. | Name | Description | Data Type| Mandatory | Initial Value Allowed| | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| restricted-permissions | [Restricted permissions](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. | 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 | Optional| 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 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/huks_architect.png b/en/application-dev/security/figures/huks_architect.png new file mode 100644 index 0000000000000000000000000000000000000000..854786917dc93499808fe72b2fc62e29e5ad2830 Binary files /dev/null and b/en/application-dev/security/figures/huks_architect.png differ diff --git a/en/application-dev/security/figures/huks_import_wrapped_key.png b/en/application-dev/security/figures/huks_import_wrapped_key.png new file mode 100644 index 0000000000000000000000000000000000000000..8ab098ace4f24884fa754acfc66f70b3df4b6162 Binary files /dev/null and b/en/application-dev/security/figures/huks_import_wrapped_key.png differ diff --git a/en/application-dev/security/figures/huks_key_user_auth_work_flow.png b/en/application-dev/security/figures/huks_key_user_auth_work_flow.png new file mode 100644 index 0000000000000000000000000000000000000000..476279901c0600132f6311c7b4ab316c5319da5f Binary files /dev/null and b/en/application-dev/security/figures/huks_key_user_auth_work_flow.png differ diff --git a/en/application-dev/security/figures/huks_keymaterial_rsa_priv_struct.png b/en/application-dev/security/figures/huks_keymaterial_rsa_priv_struct.png new file mode 100644 index 0000000000000000000000000000000000000000..089588873dbc42463ec61431956b691f0703c136 Binary files /dev/null and b/en/application-dev/security/figures/huks_keymaterial_rsa_priv_struct.png differ diff --git a/en/application-dev/security/figures/huks_keymaterial_struct.png b/en/application-dev/security/figures/huks_keymaterial_struct.png new file mode 100644 index 0000000000000000000000000000000000000000..f117e7de8391b8d7914e781f7214f6a2f48957b1 Binary files /dev/null and b/en/application-dev/security/figures/huks_keymaterial_struct.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-appendix.md b/en/application-dev/security/huks-appendix.md new file mode 100644 index 0000000000000000000000000000000000000000..99e76ccf150371654bbb67261a5a87c080743ed9 --- /dev/null +++ b/en/application-dev/security/huks-appendix.md @@ -0,0 +1,226 @@ +# HUKS Cipher Algorithm Specifications + +## Supported Algorithm Types and Parameter Combinations + +### Key Import/Generation + +| Algorithm                   | API Level| Supported Key Length (Bit) | +| -------------- | :---------------: | ------------------ | +| AES | 8+ | 128, 192, 256| +| RSA | 8+ | 512, 768, 1024, 2048, 3072, 4096| +| HMAC | 8+ | 8 to 1024 (inclusive)
The value must be an integer multiple of 8. | +| ECC | 8+ | 224, 256, 384, 521| +| Ed25519 | 8+ | 256 | +| X25519 | 8+ | 256 | +| DSA | 8+ | 8 to 1024 (inclusive)
The value must be an integer multiple of 8. | +| DH | 8+ | 2048, 3072, 4096 | +| SM2 | 9+ | 256 | +| SM3 | 9+ | 256 | +| SM4 | 9+ | 128 | + +### Encryption and Decryption + +| Algorithm                   | API Level| Remarks | +| ----------------------- | :----: | ---------------- | +| AES/CBC/NoPadding
AES/ECB/NoPadding
AES/CTR/NoPadding
AES/GCM/NoPadding
AES/CBC/PKCS7
AES/ECB/PKCS7 | 8+ | The initialization vector (IV) is mandatory in CBC, ECB, or CTR mode.
The **Nonce**, **AAD**, and **AEAD** parameters are mandatory in GCM mode. | +| RSA/ECB/NoPadding
RSA/ECB/PKCS1_V1_5
RSA/ECB/OAEP | 8+ | | +| SM4/CTR/NoPadding
SM4/ECB/NoPadding
SM4/CBC/NoPadding
SM4/ECB/PKCS7
SM4/CBC/PKCS7 | 9+ | | + + + +### Signing and Signature Verification + + +| Algorithm | API Level| Remarks | +| --------- | :----------: | ----------------- | +| RSA/MD5/PKCS1_V1_5
RSA/SHA1/PKCS1_V1_5
RSA/SHA224/PKCS1_V1_5
RSA/SHA256/PKCS1_V1_5
RSA/SHA384/PKCS1_V1_5
RSA/SHA512/PKCS1_V1_5
RSA/SHA1/PSS
RSA/SHA224/PSS
RSA/SHA256/PSS
RSA/SHA384/PSS | 8+ | | +| RSA/NoDigest/PKCS1_V1_5 | 9+ | | +| DSA/SHA1
DSA/SHA224
DSA/SHA256
DSA/SHA384
DSA/SHA512 | 8+ | | +| DSA/NoDigest | 9+ | | +| ECC/SHA1
ECC/SHA224
ECC/SHA256
ECC/SHA384
ECC/SHA512 | 8+ | | +| ECC/NoDigest | 9+ | | +| ED25519/SHA1
ED25519/SHA224
ED25519/SHA256
ED25519/SHA384
ED25519/SHA512 |8+ | | +| ED25519/NoDigest | 9+ | | +| SM2/SM3
SM2/NoDigest |9+ | | + +### Key Agreement + +| Algorithm                   | API Level| Remarks | +| ------ | :-----------: | ------------------------------ | +| ECDH | 8+ | The key must be of the ECC type. | +| DH | 8+ | | +| X25519 | 8+ | | + +### Key Derivation + +| Algorithm                   |API Level | Derived Key and Length (Bit) | Remarks | +| ------------------------- | :-----------: | :----------: | ----------------- | +| HKDF/SHA256
HKDF/SHA384
HKDF/SHA512 | 8+ | Algorithm: AES, HMAC, and SM4
Length: 256, 384, 512 | The derived key can be stored in the HUKS or directly returned in plaintext.| +| PBKDF2/SHA256
PBKDF2/SHA384
PBKDF2/SHA512 | 8+ | Algorithm: AES, HMAC, and SM4
Length: 256, 384, 512 | The derived key can be stored in the HUKS or directly returned in plaintext.| + +### Key Attestation + +| Algorithm                   |API Level| Remarks | +| ------------------ | :-----: | ------------------------------------------------------------ | +| RSA | 9+ | Only the keys using the PSS padding are supported. | +| ECC | 9+ | | +| X25519 | 9+ | | + +## Key Material Formats +HUKS defines a set of formats for the material of key pairs, public keys, and private keys of different cipher algorithms. + +### Key Pair Material +Key pair material = Key pair material header + Original key pair material + +The following uses the RSA key as an example. The application needs to apply for a Uint8Array and assign the variables to the corresponding positions based on the memory structure of the RSA key pair material. + +**Figure 1** Memory structure of the SRSA key material + +![huks_keymaterial_struct](figures/huks_keymaterial_struct.png) + +```ts +let rsa2048KeyPairMaterial = new Uint8Array([ + 0x01, 0x00, 0x00, 0x00, // Key algorithm: huks.HuksKeyAlg.HUKS_ALG_RSA = 1 + 0x00, 0x08, 0x00, 0x00, // Key size: 2048 bits + 0x00, 0x01, 0x00, 0x00, // Length of modulus n: 256 bytes + 0x03, 0x00, 0x00, 0x00, // Length of the public key exponent e: 3 bytes + 0x00, 0x01, 0x00, 0x00, // Length of the private key exponent d: 256 bytes + // Modulus n + 0xc5, 0x35, 0x62, 0x48, 0xc4, 0x92, 0x87, 0x73, 0x0d, 0x42, 0x96, 0xfc, 0x7b, 0x11, 0x05, 0x06, + 0x0f, 0x8d, 0x66, 0xc1, 0x0e, 0xad, 0x37, 0x44, 0x92, 0x95, 0x2f, 0x6a, 0x55, 0xba, 0xec, 0x1d, + 0x54, 0x62, 0x0a, 0x4b, 0xd3, 0xc7, 0x05, 0xe4, 0x07, 0x40, 0xd9, 0xb7, 0xc2, 0x12, 0xcb, 0x9a, + 0x90, 0xad, 0xe3, 0x24, 0xe8, 0x5e, 0xa6, 0xf8, 0xd0, 0x6e, 0xbc, 0xd1, 0x69, 0x7f, 0x6b, 0xe4, + 0x2b, 0x4e, 0x1a, 0x65, 0xbb, 0x73, 0x88, 0x6b, 0x7c, 0xaf, 0x7e, 0xd0, 0x47, 0x26, 0xeb, 0xa5, + 0xbe, 0xd6, 0xe8, 0xee, 0x9c, 0xa5, 0x66, 0xa5, 0xc9, 0xd3, 0x25, 0x13, 0xc4, 0x0e, 0x6c, 0xab, + 0x50, 0xb6, 0x50, 0xc9, 0xce, 0x8f, 0x0a, 0x0b, 0xc6, 0x28, 0x69, 0xe9, 0x83, 0x69, 0xde, 0x42, + 0x56, 0x79, 0x7f, 0xde, 0x86, 0x24, 0xca, 0xfc, 0xaa, 0xc0, 0xf3, 0xf3, 0x7f, 0x92, 0x8e, 0x8a, + 0x12, 0x52, 0xfe, 0x50, 0xb1, 0x5e, 0x8c, 0x01, 0xce, 0xfc, 0x7e, 0xf2, 0x4f, 0x5f, 0x03, 0xfe, + 0xa7, 0xcd, 0xa1, 0xfc, 0x94, 0x52, 0x00, 0x8b, 0x9b, 0x7f, 0x09, 0xab, 0xa8, 0xa4, 0xf5, 0xb4, + 0xa5, 0xaa, 0xfc, 0x72, 0xeb, 0x17, 0x40, 0xa9, 0xee, 0xbe, 0x8f, 0xc2, 0xd1, 0x80, 0xc2, 0x0d, + 0x44, 0xa9, 0x59, 0x44, 0x59, 0x81, 0x3b, 0x5d, 0x4a, 0xde, 0xfb, 0xae, 0x24, 0xfc, 0xa3, 0xd9, + 0xbc, 0x57, 0x55, 0xc2, 0x26, 0xbc, 0x19, 0xa7, 0x9a, 0xc5, 0x59, 0xa3, 0xee, 0x5a, 0xef, 0x41, + 0x80, 0x7d, 0xf8, 0x5e, 0xc1, 0x1d, 0x32, 0x38, 0x41, 0x5b, 0xb6, 0x92, 0xb8, 0xb7, 0x03, 0x0d, + 0x3e, 0x59, 0x0f, 0x1c, 0xb3, 0xe1, 0x2a, 0x95, 0x1a, 0x3b, 0x50, 0x4f, 0xc4, 0x1d, 0xcf, 0x73, + 0x7c, 0x14, 0xca, 0xe3, 0x0b, 0xa7, 0xc7, 0x1a, 0x41, 0x4a, 0xee, 0xbe, 0x1f, 0x43, 0xdd, 0xf9, + // Public key exponent e + 0x01, 0x00, 0x01, + // Private key exponent d + 0x88, 0x4b, 0x82, 0xe7, 0xe3, 0xe3, 0x99, 0x75, 0x6c, 0x9e, 0xaf, 0x17, 0x44, 0x3e, 0xd9, 0x07, + 0xfd, 0x4b, 0xae, 0xce, 0x92, 0xc4, 0x28, 0x44, 0x5e, 0x42, 0x79, 0x08, 0xb6, 0xc3, 0x7f, 0x58, + 0x2d, 0xef, 0xac, 0x4a, 0x07, 0xcd, 0xaf, 0x46, 0x8f, 0xb4, 0xc4, 0x43, 0xf9, 0xff, 0x5f, 0x74, + 0x2d, 0xb5, 0xe0, 0x1c, 0xab, 0xf4, 0x6e, 0xd5, 0xdb, 0xc8, 0x0c, 0xfb, 0x76, 0x3c, 0x38, 0x66, + 0xf3, 0x7f, 0x01, 0x43, 0x7a, 0x30, 0x39, 0x02, 0x80, 0xa4, 0x11, 0xb3, 0x04, 0xd9, 0xe3, 0x57, + 0x23, 0xf4, 0x07, 0xfc, 0x91, 0x8a, 0xc6, 0xcc, 0xa2, 0x16, 0x29, 0xb3, 0xe5, 0x76, 0x4a, 0xa8, + 0x84, 0x19, 0xdc, 0xef, 0xfc, 0xb0, 0x63, 0x33, 0x0b, 0xfa, 0xf6, 0x68, 0x0b, 0x08, 0xea, 0x31, + 0x52, 0xee, 0x99, 0xef, 0x43, 0x2a, 0xbe, 0x97, 0xad, 0xb3, 0xb9, 0x66, 0x7a, 0xae, 0xe1, 0x8f, + 0x57, 0x86, 0xe5, 0xfe, 0x14, 0x3c, 0x81, 0xd0, 0x64, 0xf8, 0x86, 0x1a, 0x0b, 0x40, 0x58, 0xc9, + 0x33, 0x49, 0xb8, 0x99, 0xc6, 0x2e, 0x94, 0x70, 0xee, 0x09, 0x88, 0xe1, 0x5c, 0x4e, 0x6c, 0x22, + 0x72, 0xa7, 0x2a, 0x21, 0xdd, 0xd7, 0x1d, 0xfc, 0x63, 0x15, 0x0b, 0xde, 0x06, 0x9c, 0xf3, 0x28, + 0xf3, 0xac, 0x4a, 0xa8, 0xb5, 0x50, 0xca, 0x9b, 0xcc, 0x0a, 0x04, 0xfe, 0x3f, 0x98, 0x68, 0x81, + 0xac, 0x24, 0x53, 0xea, 0x1f, 0x1c, 0x6e, 0x5e, 0xca, 0xe8, 0x31, 0x0d, 0x08, 0x12, 0xf3, 0x26, + 0xf8, 0x5e, 0xeb, 0x10, 0x27, 0xae, 0xaa, 0xc3, 0xad, 0x6c, 0xc1, 0x89, 0xdb, 0x7d, 0x5a, 0x12, + 0x55, 0xad, 0x11, 0x19, 0xa1, 0xa9, 0x8f, 0x0b, 0x6d, 0x78, 0x8d, 0x1c, 0xdf, 0xe5, 0x63, 0x82, + 0x0b, 0x7d, 0x23, 0x04, 0xb4, 0x75, 0x8c, 0xed, 0x77, 0xfc, 0x1a, 0x85, 0x29, 0x11, 0xe0, 0x61, + ]); +``` + +The key algorithm is a value of [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg). + +- **RSA Key Pair Material Format** + | Key Algorithm| Key Size| Modulus n Length Ln| Public Key Exponent e Length Le | Private Key Exponent d Length Ld| n | e | d | + | :----: |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|Ln bytes|Le bytes|Ld bytes| + + +- **ECC Key Pair Material Format** + | Key Algorithm| Key Size| Coordinate x Length Lx| Coordinate y Length Ly| Coordinate z Length Lz| x | y | z | + | :----: |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|Lx bytes|Ly bytes|Lz bytes| + + +- **DSA Key Pair Material Format** + | Key Algorithm| Key Size| Private Key x Length Lx| Public Key y Length Ly| Prime p Length Lp| Prime Factor q Length Lq| g length Lg| x | y | p | q | g | + | :----: |:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|Lx bytes|Ly bytes|Lp bytes|Lq bytes|Lg bytes| + + +- **DH Key Pair Material Format** + | Key Algorithm| Key Size| Public Key pk Length Lpk| Private Key sk Length Lsk| Reserved Field| pk | sk | + |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|Lpk bytes|Lsk bytes| + + +- **Curve25519 Key Pair Material Format** + | Key Algorithm| Key Size| Public Key pk Length Lpk| Private Key sk Length Lsk| Reserved Field| pk | sk | + |:----:|:----:|:----:|:----:|:----:|:----:|:----:| + |4 bytes|4 bytes|4 bytes|4 bytes|4 bytes|Lpk bytes|Lsk bytes| + + +### Public Key Material + +When a public key is exported or imported, the key material is encapsulated in the DER format defined in X.509. + +The following is ECC public key in EDR format: +```ts +let eccP256PubKey = new Uint8Array([ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde, + 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, + 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8, + 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, + 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e]); +``` + +### Private Key Material + +The private key material is in the same format as the key pair material. When the private key material is encapsulated, the public key length in the header of the key pair material is set to 0 and original key pair material and the private key material are combined. + +Private key material = Header of the key pair material + Original private key material + +The following uses the RSA private key material as an example: + +![huks_keymaterial_rsa_priv_struct](figures/huks_keymaterial_rsa_priv_struct.png) + +```ts +let rsa2048PrivateKeyMaterial = new Uint8Array([ + 0x01, 0x00, 0x00, 0x00, // Key algorithm: huks.HuksKeyAlg.HUKS_ALG_RSA = 1 + 0x00, 0x08, 0x00, 0x00, // Key size: 2048 bits + 0x00, 0x01, 0x00, 0x00, // Length of modulus n: 256 byptes + 0x00, 0x00, 0x00, 0x00, // Length of the public key exponent e: 0 + 0x00, 0x01, 0x00, 0x00, // Length of the private key exponent d: 256 bytes + // Modulus n + 0xc5, 0x35, 0x62, 0x48, 0xc4, 0x92, 0x87, 0x73, 0x0d, 0x42, 0x96, 0xfc, 0x7b, 0x11, 0x05, 0x06, + 0x0f, 0x8d, 0x66, 0xc1, 0x0e, 0xad, 0x37, 0x44, 0x92, 0x95, 0x2f, 0x6a, 0x55, 0xba, 0xec, 0x1d, + 0x54, 0x62, 0x0a, 0x4b, 0xd3, 0xc7, 0x05, 0xe4, 0x07, 0x40, 0xd9, 0xb7, 0xc2, 0x12, 0xcb, 0x9a, + 0x90, 0xad, 0xe3, 0x24, 0xe8, 0x5e, 0xa6, 0xf8, 0xd0, 0x6e, 0xbc, 0xd1, 0x69, 0x7f, 0x6b, 0xe4, + 0x2b, 0x4e, 0x1a, 0x65, 0xbb, 0x73, 0x88, 0x6b, 0x7c, 0xaf, 0x7e, 0xd0, 0x47, 0x26, 0xeb, 0xa5, + 0xbe, 0xd6, 0xe8, 0xee, 0x9c, 0xa5, 0x66, 0xa5, 0xc9, 0xd3, 0x25, 0x13, 0xc4, 0x0e, 0x6c, 0xab, + 0x50, 0xb6, 0x50, 0xc9, 0xce, 0x8f, 0x0a, 0x0b, 0xc6, 0x28, 0x69, 0xe9, 0x83, 0x69, 0xde, 0x42, + 0x56, 0x79, 0x7f, 0xde, 0x86, 0x24, 0xca, 0xfc, 0xaa, 0xc0, 0xf3, 0xf3, 0x7f, 0x92, 0x8e, 0x8a, + 0x12, 0x52, 0xfe, 0x50, 0xb1, 0x5e, 0x8c, 0x01, 0xce, 0xfc, 0x7e, 0xf2, 0x4f, 0x5f, 0x03, 0xfe, + 0xa7, 0xcd, 0xa1, 0xfc, 0x94, 0x52, 0x00, 0x8b, 0x9b, 0x7f, 0x09, 0xab, 0xa8, 0xa4, 0xf5, 0xb4, + 0xa5, 0xaa, 0xfc, 0x72, 0xeb, 0x17, 0x40, 0xa9, 0xee, 0xbe, 0x8f, 0xc2, 0xd1, 0x80, 0xc2, 0x0d, + 0x44, 0xa9, 0x59, 0x44, 0x59, 0x81, 0x3b, 0x5d, 0x4a, 0xde, 0xfb, 0xae, 0x24, 0xfc, 0xa3, 0xd9, + 0xbc, 0x57, 0x55, 0xc2, 0x26, 0xbc, 0x19, 0xa7, 0x9a, 0xc5, 0x59, 0xa3, 0xee, 0x5a, 0xef, 0x41, + 0x80, 0x7d, 0xf8, 0x5e, 0xc1, 0x1d, 0x32, 0x38, 0x41, 0x5b, 0xb6, 0x92, 0xb8, 0xb7, 0x03, 0x0d, + 0x3e, 0x59, 0x0f, 0x1c, 0xb3, 0xe1, 0x2a, 0x95, 0x1a, 0x3b, 0x50, 0x4f, 0xc4, 0x1d, 0xcf, 0x73, + 0x7c, 0x14, 0xca, 0xe3, 0x0b, 0xa7, 0xc7, 0x1a, 0x41, 0x4a, 0xee, 0xbe, 0x1f, 0x43, 0xdd, 0xf9, + // Private key exponent d + 0x88, 0x4b, 0x82, 0xe7, 0xe3, 0xe3, 0x99, 0x75, 0x6c, 0x9e, 0xaf, 0x17, 0x44, 0x3e, 0xd9, 0x07, + 0xfd, 0x4b, 0xae, 0xce, 0x92, 0xc4, 0x28, 0x44, 0x5e, 0x42, 0x79, 0x08, 0xb6, 0xc3, 0x7f, 0x58, + 0x2d, 0xef, 0xac, 0x4a, 0x07, 0xcd, 0xaf, 0x46, 0x8f, 0xb4, 0xc4, 0x43, 0xf9, 0xff, 0x5f, 0x74, + 0x2d, 0xb5, 0xe0, 0x1c, 0xab, 0xf4, 0x6e, 0xd5, 0xdb, 0xc8, 0x0c, 0xfb, 0x76, 0x3c, 0x38, 0x66, + 0xf3, 0x7f, 0x01, 0x43, 0x7a, 0x30, 0x39, 0x02, 0x80, 0xa4, 0x11, 0xb3, 0x04, 0xd9, 0xe3, 0x57, + 0x23, 0xf4, 0x07, 0xfc, 0x91, 0x8a, 0xc6, 0xcc, 0xa2, 0x16, 0x29, 0xb3, 0xe5, 0x76, 0x4a, 0xa8, + 0x84, 0x19, 0xdc, 0xef, 0xfc, 0xb0, 0x63, 0x33, 0x0b, 0xfa, 0xf6, 0x68, 0x0b, 0x08, 0xea, 0x31, + 0x52, 0xee, 0x99, 0xef, 0x43, 0x2a, 0xbe, 0x97, 0xad, 0xb3, 0xb9, 0x66, 0x7a, 0xae, 0xe1, 0x8f, + 0x57, 0x86, 0xe5, 0xfe, 0x14, 0x3c, 0x81, 0xd0, 0x64, 0xf8, 0x86, 0x1a, 0x0b, 0x40, 0x58, 0xc9, + 0x33, 0x49, 0xb8, 0x99, 0xc6, 0x2e, 0x94, 0x70, 0xee, 0x09, 0x88, 0xe1, 0x5c, 0x4e, 0x6c, 0x22, + 0x72, 0xa7, 0x2a, 0x21, 0xdd, 0xd7, 0x1d, 0xfc, 0x63, 0x15, 0x0b, 0xde, 0x06, 0x9c, 0xf3, 0x28, + 0xf3, 0xac, 0x4a, 0xa8, 0xb5, 0x50, 0xca, 0x9b, 0xcc, 0x0a, 0x04, 0xfe, 0x3f, 0x98, 0x68, 0x81, + 0xac, 0x24, 0x53, 0xea, 0x1f, 0x1c, 0x6e, 0x5e, 0xca, 0xe8, 0x31, 0x0d, 0x08, 0x12, 0xf3, 0x26, + 0xf8, 0x5e, 0xeb, 0x10, 0x27, 0xae, 0xaa, 0xc3, 0xad, 0x6c, 0xc1, 0x89, 0xdb, 0x7d, 0x5a, 0x12, + 0x55, 0xad, 0x11, 0x19, 0xa1, 0xa9, 0x8f, 0x0b, 0x6d, 0x78, 0x8d, 0x1c, 0xdf, 0xe5, 0x63, 0x82, + 0x0b, 0x7d, 0x23, 0x04, 0xb4, 0x75, 0x8c, 0xed, 0x77, 0xfc, 0x1a, 0x85, 0x29, 0x11, 0xe0, 0x61, + ]); +``` diff --git a/en/application-dev/security/huks-guidelines.md b/en/application-dev/security/huks-guidelines.md index cfeb93d8d766b4c8b791db43a7be18e95583c575..bae3fd15ece4cbe1ceac8b56dfec1f62723d04f4 100644 --- a/en/application-dev/security/huks-guidelines.md +++ b/en/application-dev/security/huks-guidelines.md @@ -1,186 +1,363 @@ + # HUKS Development -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. +## Key Generation -> **NOTE**
-> -> This document is based on API version 9 and applies only to ArkTS development. +The HUKS provides the capability of randomly generating keys for services. For a key generated by the HUKS, its plaintext will never be exposed outside throughout the lifecycle. This ensures that no one can access the plaintext of the key. Even the service that generates the key can call APIs provided by the HUKS to perform key operations and obtain the operation result, rather than accessing the key. -### **Prerequisites** +**How to Develop** -The HUKS module must have been imported. +Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. You need to pass in the key alias in **keyAlias**, a key attribute set in **options**, and **callback** to result the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). -```ts -import huks from '@ohos.security.huks' -``` -### Generating a Key -Generate a key for an application by specifying the alias and key parameters. +1. Determine the key alias. +2. Initialize the key attributes.
Use [HuksParam](../reference/apis/js-apis-huks.md#huksparam) to encapsulate key attributes. Use a **HuksParam** array to assign values to the **properties** field of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions). The parameters [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose) are mandatory. +3. Pass in the key alias and key parameter set to generate a key. + + > **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. -> -> 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. +> The key alias cannot exceed 64 bytes. + +**Sample code** + +```ts +/* + * Generate a DH key and return the result by a callback. + */ +import huks from '@ohos.security.huks'; + +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let keyAlias = 'dh_key'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_DH +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048 +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} + +/* + * Generate a key. + */ +function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throw (error); + } + }); +} + +async function publicGenKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + try { + await generateKeyItem(keyAlias, huksOptions) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + + +async function TestGenKey() { + await publicGenKeyFunc(keyAlias, huksOptions); +} +``` + +## Key Import +If the key is generated outside the HUKS (for example, generated through key agreement or by a server), the application can import the key to the HUKS for management. The HUKS supports import of keys in plaintext. However, if keys are imported in plaintext, the keys are exposed in the REE memory. This operation applies to lightweight devices or security-insensitive services. For security-sensitive services, use the secure import provided by the HUKS. Secure import allows the keys generate keys by services to be transferred to the HUKS through an end-to-end encrypted transmission channel. + +Once a key is imported to the HUKS, its plaintext will not be exposed outside the HUKS throughout the lifecycle of the key. + -**Supported Key Types** -The following lists the mandatory parameters for key generation, including the key algorithm, key length, and key usage. +### Importing a Key in Plaintext -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | -| ------------------ | :----------------------------------------------------------- | ------------------------------------------------------------ | -| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128 HUKS_AES_KEY_SIZE_192 HUKS_AES_KEY_SIZE_256 | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT HUKS_KEY_PURPOSE_DERIVE | -| HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_X25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_ED25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_DH | HUKS_DH_KEY_SIZE_2048, HUKS_DH_KEY_SIZE_3072, HUKS_DH_KEY_SIZE_4096| HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_ECDH | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_SM2 | HUKS_SM2_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | -| HUKS_ALG_SM4 | HUKS_SM4_KEY_SIZE_128 | HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT | -Before you get started, understand the following variables: +Use [huks.importKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksimportkeyitem9) to import a key in plaintext. You need to pass in the key alias in **keyAlias**, key material and attribute set in **options**, and **callback** to return the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). -| Parameter | Type | Mandatory| Description | -| ---------------- | ----------- | ---- | ------------------------------------------------------------ | -| genKeyAlias | string | Yes | Alias of the key generated. | -| genKeyProperties | HuksOptions | Yes | Tags required for generating the key. The key algorithm, key usage, and key length are mandatory.| -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +1. Determine the key alias. +2. Encapsulate the key material and key attribute set.
The key material must comply with [HUKS key material formats](./huks-appendix.md#key-material-formats). The **inData** value of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions) must be in the Uint8Array form. Encapsulate key attributes in [HuksParam](../reference/apis/js-apis-huks.md#huksparam), and use a **HuksParam** array to assign values to the **properties** field. The key attribute set must contain [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose). +3. Import the key. + + + +**Sample code** ```ts -/* Generate an ECC key of 256 bits. */ -let keyAlias = 'keyAlias'; +/* + /* Import an AES key of 256 bits. */ + */ + +/* Key */ +let plainTextSize32 = new Uint8Array([ + 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, + 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9 +]); + +/* + * Determine the key alias. + */ +let keyAlias = 'AES256Alias_sample'; + +/* + * Encapsulate the key attribute set and key material. + */ let properties = new Array(); -// Mandatory parameter. properties[0] = { tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC + value: huks.HuksKeyAlg.HUKS_ALG_AES }; -// Mandatory parameter. properties[1] = { tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 }; -// Mandatory parameter. properties[2] = { tag: huks.HuksTag.HUKS_TAG_PURPOSE, value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY -}; -// Optional parameter. -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT }; let options = { - properties: properties + properties: properties, + inData: plainTextSize32 }; + +/* + * Import the key. + */ try { - huks.generateKeyItem(keyAlias, options, function (error, data) { + huks.importKeyItem(keyAlias, options, function (error, data) { if (error) { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); } else { - console.info(`callback: generateKeyItem key success`); + console.info(`callback: importKeyItem success`); } }); } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); +} +``` + +**Verification** + +Check whether the key exists. If yes, the key is imported successfully. + +**Sample code** + +```ts +import huks from '@ohos.security.huks'; + +let keyAlias = 'AES256Alias_sample'; +let isKeyExist; + +let keyProperties = new Array(); +keyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +let huksOptions = { + properties: keyProperties, // It cannot be empty. + inData: new Uint8Array(new Array()) // It cannot be empty. +} +try { + huks.isKeyItemExist(keyAlias, huksOptions, function (error, data) { + if (error) { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } else { + if (data !== null && data.valueOf() !== null) { + isKeyExist = data.valueOf(); + console.info(`callback: isKeyItemExist success, isKeyExist = ${isKeyExist}`); + } + } + }); +} catch (error) { + console.error(`callback: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` +### Importing a Wrapped Key +Compared with import of plaintext, secure import has complex key material and operations. The following figure illustrates the development process of secure import. -### Key Import and Export -The **HUKS** module allows the public key of its own asymmetric key (public and private key pair) to be exported based on the key alias. -The **HUKS** module also supports import of external keys. Except the public keys of asymmetric keys, the keys imported into the HUKS cannot be exported in their lifecycle. If the alias of the key to be imported already exists in HUKS, the newly imported key will overwrite the existing one. +**Figure 2** Development process of secure import -The development procedure is as follows: +![huks_import_wrapped_key](figures/huks_import_wrapped_key.png) -1. Generate a key. -2. Export the key. -3. Import the key. -**Supported Types of Keys to Import** -AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4 -**Supported Types of Keys to Export** +**Available APIs** -RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2 +You need to use the APIs for generating a key, exporting a public key, importing a wrapped key, and deleting a key in sequence. -> **NOTE**
-> -> The key alias cannot exceed 64 bytes. +**Table 1** APIs for secure import + +| API | Description | +| -------------------------------------- | ----------------------------| +|generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Generates a key.| +|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Exports the public key of a key pair.| +|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void|Imports a wrapped key.| +|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void|Deletes a key.| -Before you get started, understand the following variables: +>**NOTE**
The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **LengthData-Data** format. Specifically, the application needs to apply for a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table. -| Parameter | Type | Mandatory| Description | -| -------------- | ----------- | ---- | ------------------------ | -| exportKeyAlias | string | Yes | Alias of the key to generate. | -| importKeyAlias | string | Yes | Alias of the key to import. | -| huksOptions | HuksOptions | Yes | Tags required for generating the key.| -| encryptOptions | HuksOptions | Yes | Tags required for importing the key.| +**Table 2** Format of the wrapped key material -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +| Content| Public Key Length (Lpk2)| Public Key pk2| k2 AAD2 Length LAAD2| k2 Encryption Parameter AAD2| k2 Nonce2 Length LNonce2| k2 Encryption Parameter Nonce2| +| :--: |:----:|:----: |:----: | :----: | :----:|:----:| +|Length| 4 bytes|Lpk2 bytes| 4 bytes| LAAD2 bytes| 4 bytes| LNonce2 bytes| +| Content| k2 AEAD2 Length LAEAD2| k2 Encryption Parameter AEAD2| k3 Ciphertext Length Lk3_enc| k3 Ciphertext k3_enc| k3 AAD3 Length LAAD3| k3 Encryption Parameter AAD3| +|Length| 4 bytes|LAEAD2 bytes| 4 bytes| Lk3_enc bytes| 4 bytes| LAAD3 bytes| +| Content| k3 Nonce3 Length LNonce3| k3 Encryption Parameter Nonce3| k3 AEAD3 Length LAEAD3| k3 Encryption Parameter AEAD3| Length of **k1'_size** Lk1'_size| Key Plaintext Material Length k1'_size| +|Length| 4 bytes|LNonce3 bytes| 4 bytes| LAEAD3 bytes| 4 bytes| Lk1'_size bytes| +|Content|k1' Ciphertext Length Lk1'_enc| k1' ciphertext k1'_enc| | | | | +|Length| 4 bytes|Lk1'_enc bytes| | | | | -**Example** +**How to Develop** + +The following example provides the development involving HUKS APIs (using the ECDH key agreement suite). The operations performed by the service are not included. +1. Convert the key material to the HUKS format. +2. Generate a wrapping key (a key used for secure import). +3. Export the public key material. +4. Wrap the key material to be imported. +5. Import the wrapped key material. +6. Delete the wrapping key. + +**Sample code** ```ts -/* Export an RSA512 key and import DH2048, RSA512, x25519, and ECC256 keys.*/ +/* + * Import an SM2 key and return the result by a callback. + */ import huks from '@ohos.security.huks'; -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} +/* + * Determine the key alias. + */ +let importAlias = "importAlias"; +let wrapAlias = "wrappingKeyAlias"; +let exportKey; -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; -} +/* + * Convert the key material into a HUKS ECC-P-256 key pair for secure import. + */ +let inputEccPair = new Uint8Array([ + 0x02, 0x00, 0x00, 0x00, // key algorithm: huks.HuksKeyAlg.HUKS_ALG_ECC = 2 + 0x00, 0x01, 0x00, 0x00, // key size: 256 bits + 0x20, 0x00, 0x00, 0x00, // Coordinate x length: 32 bytes + 0x20, 0x00, 0x00, 0x00, // Coordinate y length: 32 bytes + 0x20, 0x00, 0x00, 0x00, // Coordinate z length: 32 bytes + // Coordinate x + 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, + 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, + // Coordinate y + 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, + 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35, + // Coordinate z + 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, + 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9 + ]); -function Uint32ToUint8(value) { - let arr = new Uint8Array(4 * value.length); - for (let i = 0, j = value.length; i < j; i++) { - arr[i * 4+3] = (value[i] >> 24) & 0xFF; - arr[i * 4+2] = (value[i] >> 16) & 0xFF; - arr[i * 4+1] = (value[i] >> 8) & 0xFF; - arr[i*4] = (value[i]) & 0xFF; - } - return arr; -} +/* + * Encapsulate the key attribute set. + */ +// Attribute set for the wrapping key. +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, + value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, +}; +let huksOptions = { + properties: properties, + inData: inputEccPair +}; -async function publicGenKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} +// Attribute set of the AES256 key to be imported. +let importProperties = new Array(); +importProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES +}; +importProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 +}; +importProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +importProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC +}; +importProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +importProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, + value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING // Use the ECDH+AES256GCM suite. +}; +let importOptions = { + properties: importProperties, + inData: new Uint8Array(new Array()) +}; -function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { +// Export the public key of the key pair. +function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -188,89 +365,111 @@ function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -async function publicExportKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { +async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback export`); + let throwObject = {isThrow: false}; try { - await exportKeyItem(keyAlias, huksOptions) - .then((data) => { + await exportKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportKey = data.outData; }) .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function exportKeyItem(keyAlias: string, huksOptions: huks.HuksOptions): Promise { +// Generate a wrapping key (the key is imported here). +function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { + huks.importKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); - } else { + } else { resolve(data); } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -async function publicImportKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { +async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter promise importKeyItem`); + let throwObject = {isThrow: false}; try { - await importKeyItem(keyAlias, huksOptions) - .then((data) => { + await importKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { +// Perform secure import. +async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback importWrappedKeyItem`); + var throwObject = {isThrow: false}; + try { + await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { + huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { - resolve(data); + resolve(data); } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -async function publicDeleteKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { +// Delete the wrapping key. +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -281,549 +480,314 @@ function deleteKeyItem(keyAlias: string, huksOptions: huks.HuksOptions) { } }); } catch (error) { - throw (error); + throwObject.isThrow = true; + throw(error); } }); } -// Export the RSA key. -async function testExportRsa() { - let exportKeyAlias = 'export_rsa_key'; - /* Configure the parameters for generating the key. */ - let exportProperties = new Array(); - exportProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - } - exportProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT - } - exportProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 - } - exportProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - } - exportProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PKCS1_V1_5 - } - exportProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: exportProperties, - inData: new Uint8Array(new Array()) +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } +} - /* Generate a key. */ - await publicGenKeyFunc(exportKeyAlias, huksOptions); +async function ImportWrappedKeyNormalTest() { + console.info(`enter ImportWrapKey test`); + /* + * Generate a wrapping key (the key is imported here). + */ + await publicImportKeyFunc(wrapAlias, huksOptions); - /* Export the key. */ - await publicExportKeyFunc(exportKeyAlias, huksOptions); - await publicDeleteKeyFunc(exportKeyAlias, huksOptions); -} - -// DH key -let g_dhPubData = new Uint8Array([ - 0x8a, 0xbf, 0x16, 0x67, 0x1b, 0x92, 0x4b, 0xf2, 0xe0, 0x02, 0xc5, 0x1f, 0x84, 0x00, 0xf8, 0x93, - 0x0f, 0x74, 0xe7, 0x0f, 0xba, 0x78, 0x30, 0xa8, 0x2d, 0x92, 0xef, 0x9b, 0x80, 0xeb, 0x76, 0xea, - 0x26, 0x74, 0x72, 0x63, 0x6a, 0x27, 0xc3, 0x8f, 0xcf, 0xbe, 0x82, 0xa2, 0x8b, 0xdc, 0x65, 0x58, - 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, - 0x48, 0xb3, 0x6b, 0x7a, 0xce, 0x2e, 0x81, 0x3d, 0x38, 0x35, 0x59, 0xdc, 0x39, 0x8a, 0x97, 0xfe, - 0x20, 0x86, 0x20, 0xdb, 0x55, 0x38, 0x23, 0xca, 0xb5, 0x5b, 0x61, 0x00, 0xdc, 0x45, 0xe2, 0xa1, - 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, - 0x4e, 0xaf, 0xee, 0xb0, 0xb0, 0x69, 0x0c, 0x13, 0xba, 0x76, 0xff, 0x2e, 0xb6, 0x16, 0xf9, 0xfc, - 0xd6, 0x09, 0x5b, 0xc7, 0x37, 0x65, 0x84, 0xd5, 0x82, 0x8a, 0xd7, 0x5b, 0x57, 0xe3, 0x0e, 0x89, - 0xbe, 0x05, 0x05, 0x55, 0x2e, 0x9f, 0x94, 0x8a, 0x53, 0xdc, 0xb7, 0x00, 0xb2, 0x6a, 0x7b, 0x8e, - 0xdf, 0x6e, 0xa4, 0x6d, 0x13, 0xb6, 0xbc, 0xaa, 0x8e, 0x44, 0x11, 0x50, 0x32, 0x91, 0x56, 0xa2, - 0x22, 0x3f, 0x2f, 0x08, 0xbb, 0x4d, 0xbb, 0x69, 0xe6, 0xb1, 0xc2, 0x70, 0x79, 0x15, 0x54, 0xad, - 0x4a, 0x29, 0xef, 0xa9, 0x3e, 0x64, 0x8d, 0xf1, 0x90, 0xf4, 0xa7, 0x93, 0x8c, 0x7a, 0x02, 0x4d, - 0x38, 0x1f, 0x58, 0xb8, 0xe4, 0x7c, 0xe1, 0x66, 0x1c, 0x72, 0x30, 0xf3, 0x4c, 0xf4, 0x24, 0xd1, - 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, - 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7]); -let g_dhPriData = new Uint8Array([ - 0x01, 0xbc, 0xa7, 0x42, 0x25, 0x79, 0xc5, 0xaf, 0x0f, 0x9c, 0xde, 0x00, 0x3b, 0x58, 0x5c, 0xd1, - 0x1d, 0x7b, 0xcf, 0x66, 0xcd, 0xa9, 0x10, 0xae, 0x92, 0x2d, 0x3c, 0xb7, 0xf3]); -let g_dhX509PubData = new Uint8Array([ - 0x30, 0x82, 0x02, 0x29, 0x30, 0x82, 0x01, 0x1b, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, - 0x01, 0x03, 0x01, 0x30, 0x82, 0x01, 0x0c, 0x02, 0x82, 0x01, 0x01, 0x00, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xad, 0xf8, 0x54, 0x58, 0xa2, 0xbb, 0x4a, 0x9a, 0xaf, 0xdc, 0x56, 0x20, - 0x27, 0x3d, 0x3c, 0xf1, 0xd8, 0xb9, 0xc5, 0x83, 0xce, 0x2d, 0x36, 0x95, 0xa9, 0xe1, 0x36, 0x41, - 0x14, 0x64, 0x33, 0xfb, 0xcc, 0x93, 0x9d, 0xce, 0x24, 0x9b, 0x3e, 0xf9, 0x7d, 0x2f, 0xe3, 0x63, - 0x63, 0x0c, 0x75, 0xd8, 0xf6, 0x81, 0xb2, 0x02, 0xae, 0xc4, 0x61, 0x7a, 0xd3, 0xdf, 0x1e, 0xd5, - 0xd5, 0xfd, 0x65, 0x61, 0x24, 0x33, 0xf5, 0x1f, 0x5f, 0x06, 0x6e, 0xd0, 0x85, 0x63, 0x65, 0x55, - 0x3d, 0xed, 0x1a, 0xf3, 0xb5, 0x57, 0x13, 0x5e, 0x7f, 0x57, 0xc9, 0x35, 0x98, 0x4f, 0x0c, 0x70, - 0xe0, 0xe6, 0x8b, 0x77, 0xe2, 0xa6, 0x89, 0xda, 0xf3, 0xef, 0xe8, 0x72, 0x1d, 0xf1, 0x58, 0xa1, - 0x36, 0xad, 0xe7, 0x35, 0x30, 0xac, 0xca, 0x4f, 0x48, 0x3a, 0x79, 0x7a, 0xbc, 0x0a, 0xb1, 0x82, - 0xb3, 0x24, 0xfb, 0x61, 0xd1, 0x08, 0xa9, 0x4b, 0xb2, 0xc8, 0xe3, 0xfb, 0xb9, 0x6a, 0xda, 0xb7, - 0x60, 0xd7, 0xf4, 0x68, 0x1d, 0x4f, 0x42, 0xa3, 0xde, 0x39, 0x4d, 0xf4, 0xae, 0x56, 0xed, 0xe7, - 0x63, 0x72, 0xbb, 0x19, 0x0b, 0x07, 0xa7, 0xc8, 0xee, 0x0a, 0x6d, 0x70, 0x9e, 0x02, 0xfc, 0xe1, - 0xcd, 0xf7, 0xe2, 0xec, 0xc0, 0x34, 0x04, 0xcd, 0x28, 0x34, 0x2f, 0x61, 0x91, 0x72, 0xfe, 0x9c, - 0xe9, 0x85, 0x83, 0xff, 0x8e, 0x4f, 0x12, 0x32, 0xee, 0xf2, 0x81, 0x83, 0xc3, 0xfe, 0x3b, 0x1b, - 0x4c, 0x6f, 0xad, 0x73, 0x3b, 0xb5, 0xfc, 0xbc, 0x2e, 0xc2, 0x20, 0x05, 0xc5, 0x8e, 0xf1, 0x83, - 0x7d, 0x16, 0x83, 0xb2, 0xc6, 0xf3, 0x4a, 0x26, 0xc1, 0xb2, 0xef, 0xfa, 0x88, 0x6b, 0x42, 0x38, - 0x61, 0x28, 0x5c, 0x97, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x01, 0x02, 0x02, - 0x02, 0x00, 0xe1, 0x03, 0x82, 0x01, 0x06, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0x8a, 0xbf, 0x16, - 0x67, 0x1b, 0x92, 0x4b, 0xf2, 0xe0, 0x02, 0xc5, 0x1f, 0x84, 0x00, 0xf8, 0x93, 0x0f, 0x74, 0xe7, - 0x0f, 0xba, 0x78, 0x30, 0xa8, 0x2d, 0x92, 0xef, 0x9b, 0x80, 0xeb, 0x76, 0xea, 0x26, 0x74, 0x72, - 0x63, 0x6a, 0x27, 0xc3, 0x8f, 0xcf, 0xbe, 0x82, 0xa2, 0x8b, 0xdc, 0x65, 0x58, 0xe3, 0xff, 0x29, - 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x48, 0xb3, 0x6b, - 0x7a, 0xce, 0x2e, 0x81, 0x3d, 0x38, 0x35, 0x59, 0xdc, 0x39, 0x8a, 0x97, 0xfe, 0x20, 0x86, 0x20, - 0xdb, 0x55, 0x38, 0x23, 0xca, 0xb5, 0x5b, 0x61, 0x00, 0xdc, 0x45, 0xe2, 0xa1, 0xf4, 0x1e, 0x7b, - 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, 0x4e, 0xaf, 0xee, - 0xb0, 0xb0, 0x69, 0x0c, 0x13, 0xba, 0x76, 0xff, 0x2e, 0xb6, 0x16, 0xf9, 0xfc, 0xd6, 0x09, 0x5b, - 0xc7, 0x37, 0x65, 0x84, 0xd5, 0x82, 0x8a, 0xd7, 0x5b, 0x57, 0xe3, 0x0e, 0x89, 0xbe, 0x05, 0x05, - 0x55, 0x2e, 0x9f, 0x94, 0x8a, 0x53, 0xdc, 0xb7, 0x00, 0xb2, 0x6a, 0x7b, 0x8e, 0xdf, 0x6e, 0xa4, - 0x6d, 0x13, 0xb6, 0xbc, 0xaa, 0x8e, 0x44, 0x11, 0x50, 0x32, 0x91, 0x56, 0xa2, 0x22, 0x3f, 0x2f, - 0x08, 0xbb, 0x4d, 0xbb, 0x69, 0xe6, 0xb1, 0xc2, 0x70, 0x79, 0x15, 0x54, 0xad, 0x4a, 0x29, 0xef, - 0xa9, 0x3e, 0x64, 0x8d, 0xf1, 0x90, 0xf4, 0xa7, 0x93, 0x8c, 0x7a, 0x02, 0x4d, 0x38, 0x1f, 0x58, - 0xb8, 0xe4, 0x7c, 0xe1, 0x66, 0x1c, 0x72, 0x30, 0xf3, 0x4c, 0xf4, 0x24, 0xd1, 0x2d, 0xb7, 0xf1, - 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0xbf, 0xf9, 0x69, - 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7]); - -// X25519 key -let g_x25519PubData = new Uint8Array([ - 0x9c, 0xf6, 0x7a, 0x8d, 0xce, 0xc2, 0x7f, 0xa7, 0xd9, 0xfd, 0xf1, 0xad, 0xac, 0xf0, 0xb3, 0x8c, - 0xe8, 0x16, 0xa2, 0x65, 0xcc, 0x18, 0x55, 0x60, 0xcd, 0x2f, 0xf5, 0xe5, 0x72, 0xc9, 0x3c, 0x54]); -// X25519 public key -let g_x25519PriData = new Uint8Array([ - 0x20, 0xd5, 0xbb, 0x54, 0x6f, 0x1f, 0x00, 0x30, 0x4e, 0x33, 0x38, 0xb9, 0x8e, 0x6a, 0xdf, 0xad, - 0x33, 0x6f, 0x51, 0x23, 0xff, 0x4d, 0x95, 0x26, 0xdc, 0xb0, 0x74, 0xb2, 0x5c, 0x7e, 0x85, 0x6c]); - -// RSA key -let g_nData = new Uint8Array([ - 0xb6, 0xd8, 0x9b, 0x33, 0x78, 0xa2, 0x63, 0x21, 0x84, 0x47, 0xa1, 0x72, 0 x3d, 0x73, 0x10, 0xbd, - 0xe9, 0x5d, 0x78, 0x44, 0x3d, 0x80, 0x18, 0x12, 0x60, 0xed, 0x29, 0x3e, 0xc7, 0x23, 0x0d, 0x3f, - 0x02, 0x59, 0x28, 0xe2, 0x8f, 0x83, 0xdf, 0x37, 0x4b, 0x77, 0xce, 0x5f, 0xb6, 0xcd, 0x61, 0x72, - 0xee, 0x01, 0xe2, 0x37, 0x4d, 0xfd, 0x4f, 0x39, 0xcf, 0xbd, 0xff, 0x84, 0x57, 0x44, 0xa5, 0x03]); -let g_eData = new Uint8Array([0x01, 0x00, 0x01]); -let g_dData = new Uint8Array([ - 0x35, 0x63, 0x89, 0xed, 0xbd, 0x8b, 0xac, 0xe6, 0x5c, 0x79, 0x8d, 0xea, 0x8d, 0x86, 0xcb, 0x9c, - 0xa8, 0x47, 0x62, 0x96, 0x8a, 0x5e, 0x9c, 0xa8, 0xc1, 0x24, 0x7e, 0xa6, 0x95, 0xfe, 0xe6, 0x1e, - 0xc0, 0xf3, 0x29, 0x76, 0xbb, 0x4d, 0xe4, 0xbc, 0x78, 0x64, 0xe1, 0x79, 0xcd, 0x8a, 0x45, 0xac, - 0x5c, 0x88, 0xea, 0xb4, 0x10, 0xd8, 0x90, 0x65, 0x7b, 0x94, 0xe8, 0x87, 0x30, 0x2a, 0x04, 0x01]); -let g_pubData = new Uint8Array([ - 0x30, 0x5c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, - 0x00, 0x03, 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0x9e, 0x93, 0x57, 0xc4, 0xab, 0xde, 0x30, - 0xc5, 0x3f, 0x3b, 0x33, 0xa6, 0xdc, 0x4a, 0xdb, 0xbf, 0x12, 0x9e, 0x5d, 0xc4, 0xba, 0x0e, 0x15, - 0x06, 0x41, 0xd8, 0x96, 0x43, 0xca, 0xc5, 0xea, 0x9f, 0xdd, 0xa0, 0x2a, 0xf1, 0x53, 0x46, 0x14, - 0x36, 0x7a, 0xab, 0xbc, 0x92, 0x1b, 0x07, 0xc6, 0x9a, 0x7d, 0x0c, 0xd0, 0xa0, 0x0f, 0x31, 0xd5, - 0x38, 0x84, 0x6c, 0x08, 0xcb, 0x9b, 0x10, 0xa6, 0x4d, 0x02, 0x03, 0x01, 0x00, 0x01]); - -// ECC key -let g_eccXData = new Uint8Array([ - 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, - 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13]); -let g_eccYData = new Uint8Array([ - 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, - 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35]); -let g_eccZData = new Uint8Array([ - 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, 0x7c, 0x86, 0xba, 0xca, - 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, 0x9e, 0x3c, 0xe5, 0xf9]); -let g_eccPubData = new Uint8Array([ - 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, - 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, - 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, - 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, - 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, - 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, 0xad, 0xee, 0x34, 0x35]); - -// Import the DH2048 key. -async function ImportDhTest(alg, keyType) { - let importKeyAlias = 'import_dh_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_DH - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - // Compare the key types. - if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* Concatenate the huksOptions.inData field with a non-public key in the following format: - * keyAlg type (4 bytes) + key_dh length (4 bytes) + - * g_dhPubData length (4 bytes) + g_dhPriData length (4 bytes) + - * Reserved size (4 bytes) + g_dhPubData + g_dhPriData - */ - // Key pair - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048, g_dhPubData.length, g_dhPriData.length, 0]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strXData = strMaterial.concat(Uint8ArrayToString(g_dhPubData)); - let strData = strXData.concat(Uint8ArrayToString(g_dhPriData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - // Private key - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksKeySize.HUKS_DH_KEY_SIZE_2048, 0, g_dhPriData.length, 0]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strData = strMaterial.concat(Uint8ArrayToString(g_dhPriData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - // Public key - huksOptions.inData = g_dhX509PubData; - } + /* + * Export the public key material of the wrapping key. + */ + await publicExportKeyFunc(wrapAlias, huksOptions); - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); -} + /*---------------------------------------------------------------------------------------------- + * The processes of generating an ECC key pair, performing ECDH key agreement, generating a k3, and encrypting k1' and k3 on the service side are omitted. + *----------------------------------------------------------------------------------------------*/ + + /* Encapsulate the key material to be imported. + * Create the importOptions.inData field in the following format: + * pk2 length (4 bytes) + pk2 data + AAD2 length (4 bytes) + AAD2 data + + * Nonce2 length (4 bytes) + Nonce2 data + AEAD2 length (4 bytes) + AEAD2 data + + * k3 ciphertext length (4 bytes) + k3 data + AAD3 length (4 bytes) + AAD3 data + + * Nonce3 length (4 bytes) +Nonce3 data + AEAD3 length (4 bytes) + AEAD3 data + + * k1'_size length (4 bytes) + k1'_size + k1'_enc length (4 bytes) + k1'_enc data + */ + let inputKey = new Uint8Array([ + 0x5b, 0x00, 0x00, 0x00, // ECC-P-256 public key length (DER format defined in X.509): 91 + // ECC-P-256 public key + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde, + 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, + 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8, + 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, + 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, + + 0x10, 0x00, 0x00, 0x00, // AAD2 length: 16 + // AAD2 + 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, 0x9c, 0xc8, 0xb7, + + 0x10, 0x00, 0x00, 0x00, // Nonce2 length: 16 + // Nonce2 + 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, + + 0x10, 0x00, 0x00, 0x00, // AEAD2 length: 16 + // AEAD2 + 0x43, 0x25, 0x1b, 0x2f, 0x5b, 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, + + 0x20, 0x00, 0x00, 0x00, // k3 ciphertext length: 32 + // k3 ciphertext + 0xf4, 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, + 0x2f, 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, + + 0x10, 0x00, 0x00, 0x00, // AAD3 length: 16 + // AAD3 + 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, 0x57, 0x66, 0x73, + + 0x10, 0x00, 0x00, 0x00, // Nonce3 length: 16 + // Nonce3 + 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, + + 0x10, 0x00, 0x00, 0x00, // AEAD3 length: 16 + // AEAD3 + 0x26, 0xae, 0xdc, 0x4e, 0xa5, 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, + + 0x04, 0x00, 0x00, 0x00, // Length of k1_size: 4 bytes + // k1_size: 32 bytes + 0x20, 0x00, 0x00, 0x00, + + 0x20, 0x00, 0x00, 0x00, // Ciphertext length of the key to be imported: 32 bytes + // Ciphertext of the key to be imported + 0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4, + 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44, 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a + ]); + importOptions.inData = inputKey; -// Import the ECC256 key. -async function ImportEccTest(alg, keyType) { - let importKeyAlias = 'import_ecc_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - // Compare the key types. - if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* Concatenate the huksOptions.inData field with a non-public key in the following format: - * keyAlg type (4 bytes) + key_ecc length (4 bytes) + - * g_eccXData length (4 bytes) + g_eccYData length (4 bytes) + - * g_eccZData length (4 bytes) + g_eccXData + - * g_eccYData + g_eccZData - */ - // Key pair - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256, g_eccXData.length, g_eccYData.length, g_eccZData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strXData = strMaterial.concat(Uint8ArrayToString(g_eccXData)); - let strYData = strXData.concat(Uint8ArrayToString(g_eccYData)); - let strData = strYData.concat(Uint8ArrayToString(g_eccZData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - // Private key - huksOptions.properties[3].value == huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256, 0, 0, g_eccZData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - - let strData = strMaterial.concat(Uint8ArrayToString(g_eccZData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - // Public key - huksOptions.inData = g_eccPubData; - } + /* + * Import the wrapped key material. + */ + await publicImportWrappedKey(importAlias, wrapAlias, importOptions); - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); + /* + * Delete the wrapping key. + */ + await publicDeleteKeyFunc(wrapAlias, huksOptions); } +``` -// Import the RSA512 key. -async function ImportRsaTest(alg, keyType) { - let importKeyAlias = 'import_rsa_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 - } - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - // Compare the key types. - if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* Concatenate the huksOptions.inData field with a non-public key in the following format: - * keyAlg type (4 bytes) + key_rsa length (4 bytes) + - * g_nData length (4 bytes) + g_eData length (4 bytes) + - * g_dData length (4 bytes) + g_nData + - * g_eData + g_dData - */ - // Key pair - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, g_nData.length, g_eData.length, g_dData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - let strNData = strMaterial.concat(Uint8ArrayToString(g_nData)); - let strEData = strNData.concat(Uint8ArrayToString(g_eData)); - let strData = strEData.concat(Uint8ArrayToString(g_dData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - // Private key - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512, g_nData.length, 0, g_dData.length]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - let strNData = strMaterial.concat(Uint8ArrayToString(g_nData)); - let strData = strNData.concat(Uint8ArrayToString(g_dData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[5].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - // Public key - huksOptions.inData = g_pubData; - } - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); -} +**Verification** -// Import the X25519 key. -async function ImportX25519Test(alg, keyType) { - let importKeyAlias = 'import_x25519_key'; - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_X25519 - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256 - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - huksOptions.properties[0].value = alg; - huksOptions.properties[3].value = keyType; - - // Compare the key types. - if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR) { - /* Concatenate the huksOptions.inData field with a non-public key in the following format: - * keyAlg type (4 bytes) + key_x25519 length (4 bytes) + - * g_x25519PubData length (4) + g_x25519PriData length (4) + - * Reserved size (4 bytes) + g_x25519PubData + - * g_x25519PriData - */ - // Key pair - let Material = new Uint32Array([huks.HuksKeyAlg.HUKS_ALG_X25519, huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, g_x25519PriData.length, g_x25519PubData.length, 0]); - let u8Material = Uint32ToUint8(Material); - let strMaterial = Uint8ArrayToString(u8Material); - let strXData = strMaterial.concat(Uint8ArrayToString(g_x25519PubData)); - let strData = strXData.concat(Uint8ArrayToString(g_x25519PriData)); - huksOptions.inData = StringToUint8Array(strData); - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY) { - // Private key - huksOptions.inData = g_x25519PriData; - } else if (huksOptions.properties[3].value === huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY) { - // Public key - huksOptions.inData = g_x25519PubData; - } - await publicImportKeyFunc(importKeyAlias, huksOptions); - await publicDeleteKeyFunc(importKeyAlias, huksOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testExportRsa') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - testExportRsa(); - }) +Check whether the key exists. If yes, the key is imported successfully. - Button() { - Text('testImportDh') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportDhTest(huks.HuksKeyAlg.HUKS_ALG_DH, huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY); - }) +**Sample code** - Button() { - Text('testImportRsa') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportRsaTest(huks.HuksKeyAlg.HUKS_ALG_RSA, huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR); - }) +```ts +import huks from '@ohos.security.huks'; - Button() { - Text('testImportX25519') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportX25519Test(huks.HuksKeyAlg.HUKS_ALG_X25519, huks.HuksImportKeyType.HUKS_KEY_TYPE_PRIVATE_KEY); - }) +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let keyAlias = 'importAlias'; +let isKeyExist; - Button() { - Text('testImportEcc') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(() => { - ImportEccTest(huks.HuksKeyAlg.HUKS_ALG_ECC, huks.HuksImportKeyType.HUKS_KEY_TYPE_PUBLIC_KEY); - }) +let keyProperties = new Array(); +keyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +let huksOptions = { + properties: keyProperties, // It cannot be empty. + inData: new Uint8Array(new Array()) // It cannot be empty. +} +try { + huks.isKeyItemExist(keyAlias, huksOptions, function (error, data) { + if (error) { + console.error(`callback: isKeyItemExist failed, code: ${error.code}, msg: ${error.message}`); + } else { + if (data !== null && data.valueOf() !== null) { + isKeyExist = data.valueOf(); + console.info(`callback: isKeyItemExist success, isKeyExist = ${isKeyExist}`); + } } - .width('100%') - .height('100%') - } + }); +} catch (error) { + console.error(`callback: isKeyItemExist input arg invalid, code: ${error.code}, msg: ${error.message}`); } ``` -### Secure Key Import -The service invoker and HUKS negotiate a shared symmetric key to encrypt and decrypt the intermediate key and the key to be imported. After the encrypted key is imported, it is decrypted and saved in HUKS. The keys in plaintext can be processed in HUKS only. +## Common Key Operations -The development procedure is as follows: +**When to Use** -1. Generate a key pair in HUKS. The key pair is used to encrypt the key to import. -2. Export the public key of the key pair and obtain a shared secret through key agreement. -3. Generate intermediate key materials to encrypt the key. -4. Import the key. +To ensure data confidentiality and integrity, you may need to encrypt or decrypt data, generate or verify a signature, perform key agreement, and derive a key. The following describes common key operations. The following examples do not involve secondary identity access control. If secondary identity access control is involved, see [Key Access Control](#key-access-control). -**Supported Key Types** +**General Development Process** -AES128, AES192, AES256, RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, HmacSHA512, ECC224, ECC256, ECC384, ECC521, Curve25519, DSA, SM2, SM3, SM4 +The HUKS operates data based on key sessions. The general process is as follows: +1. (Mandatory) Use [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9) to initialize a key session.
You need to pass in the key alias and key operation parameters to initialize a key session, and obtain the session handle. The key operation parameters must contain the parameters required by the cipher algorithm, including the cipher algorithm, key size, key purpose, working mode, padding mode, hash mode, IV, nonce, and AAD. If access control is set for the key, other parameters are required. For details, see [Key Access Control](#key-access-control). +2. (Optional) Use [huks.updateSession()](../reference/apis/js-apis-huks.md#huksupdatesession9) to pass in data by segment.
Perform this step only if the data exceeds 100 KB or the cipher algorithm requires operations by data segment. Otherwise, skip this step. +3. (Mandatory) Use [huks.finishSession()](../reference/apis/js-apis-huks.md#huksfinishsession9) to finalize the key session operation.
Pass in the last data segment and perform the key session operation. If an error occurs during the process or the data passed in is not required, use [huks.abortSession()](../reference/apis/js-apis-huks.md#huksabortsession9) to abort the session. -> **NOTICE** -> -> - When generating a public key, set **HUKS_TAG_PURPOSE = HUKS_KEY_PURPOSE_UNWRAP**. -> - Set **HUKS_TAG_IMPORT_KEY_TYPE = HUKS_KEY_TYPE_KEY_PAIR**. -> - When importing a key in secure mode, add **HUKS_TAG_UNWRAP_ALGORITHM_SUITE** with value set to **HUKS_UNWRAP_SUITE_X25519_AES_256_GCM_NOPADDING** or **HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING**. -> - The key alias cannot exceed 64 bytes. +### Encryption and Decryption +```ts +/* + * Encrypt and decrypt data using an SM4 128-bit key and return the result in a callback. + */ +import huks from '@ohos.security.huks'; + +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let srcKeyAlias = 'sm4_Key'; +let IV = '0000000000000000'; +let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; +let encryptUpdateResult = new Array(); +let handle; +let updateResult = new Array(); +let finishOutData; + +/* Configure the key generation parameter set and key encryption parameter set. */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} -Before you get started, understand the following variables: +let propertiesEncrypt = new Array(); +propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, +} +propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) +} -| Parameter | Type | Mandatory| Description | -| -------------- | ----------- | ---- | -------------------------------- | -| importAlias | string | Yes | Alias of the key to import. | -| wrapAlias | string | Yes | Alias of the key. | -| genWrapOptions | HuksOptions | Yes | Tags required for generating the key.| -| importOptions | HuksOptions | Yes | Tags required for importing the encrypted key. | +/* Modify the key encryption parameter set to the decryption parameter set. */ +propertiesEncrypt.splice(1, 1, { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +}); +let decryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) +} -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -**Example** +function Uint8ArrayToString(fileData) { + let dataString = ''; + for (let i = 0; i < fileData.length; i++) { + dataString += String.fromCharCode(fileData[i]); + } + return dataString; +} -```ts -import huks from '@ohos.security.huks'; +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback export`); +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await exportKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - if (data.outData !== null) { - exportKey = data.outData; - } + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -831,30 +795,37 @@ function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise< } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise importKeyItem`); +async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await importKeyItem(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; }) - .catch(error => { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { + huks.updateSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -862,30 +833,36 @@ function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicImportWrappedKey(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback importWrappedKeyItem`); +async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; try { - await importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions) + await updateSession(handle, huksOptions, throwObject) .then ((data) => { - console.info(`callback: importWrappedKeyItem success, data = ${JSON.stringify(data)}`); + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: importWrappedKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: importWrappedKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOptions:huks.HuksOptions) { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.importWrappedKeyItem(keyAlias, wrappingKeyAlias, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -893,27 +870,34 @@ function importWrappedKeyItem(keyAlias:string, wrappingKeyAlias:string, huksOpti } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; try { - await deleteKeyItem(keyAlias, huksOptions) + await finishSession(handle, huksOptions, throwObject) .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -924,206 +908,157 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -let importAlias = "importAlias"; -let wrapAlias = "wrappingKeyAlias"; -let exportKey; +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} -let inputEccPair = new Uint8Array([ - 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, - 0x20, 0x00, 0x00, 0x00, 0xa5, 0xb8, 0xa3, 0x78, 0x1d, 0x6d, 0x76, 0xe0, 0xb3, 0xf5, 0x6f, 0x43, - 0x9d, 0xcf, 0x60, 0xf6, 0x0b, 0x3f, 0x64, 0x45, 0xa8, 0x3f, 0x1a, 0x96, 0xf1, 0xa1, 0xa4, 0x5d, - 0x3e, 0x2c, 0x3f, 0x13, 0xd7, 0x81, 0xf7, 0x2a, 0xb5, 0x8d, 0x19, 0x3d, 0x9b, 0x96, 0xc7, 0x6a, - 0x10, 0xf0, 0xaa, 0xbc, 0x91, 0x6f, 0x4d, 0xa7, 0x09, 0xb3, 0x57, 0x88, 0x19, 0x6f, 0x00, 0x4b, - 0xad, 0xee, 0x34, 0x35, 0xfb, 0x8b, 0x9f, 0x12, 0xa0, 0x83, 0x19, 0xbe, 0x6a, 0x6f, 0x63, 0x2a, - 0x7c, 0x86, 0xba, 0xca, 0x64, 0x0b, 0x88, 0x96, 0xe2, 0xfa, 0x77, 0xbc, 0x71, 0xe3, 0x0f, 0x0f, - 0x9e, 0x3c, 0xe5, 0xf9]); +async function testSm4Cipher() { + /* Generate a key. */ + await publicGenKeyFunc(srcKeyAlias, huksOptions); -let properties = new Array(); -properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_ECC -}; -properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_256 -}; -properties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_UNWRAP -}; -properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 -}; -properties[4] = { - tag: huks.HuksTag.HUKS_TAG_IMPORT_KEY_TYPE, - value: huks.HuksImportKeyType.HUKS_KEY_TYPE_KEY_PAIR, -}; -let huksOptions = { - properties: properties, - inData: inputEccPair -}; - -let importProperties = new Array(); -importProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES -}; -importProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256 -}; -importProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT -}; -importProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC -}; -importProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE -}; -importProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_UNWRAP_ALGORITHM_SUITE, - value: huks.HuksUnwrapSuite.HUKS_UNWRAP_SUITE_ECDH_AES_256_GCM_NOPADDING -}; -let importOptions = { - properties: importProperties, - inData: new Uint8Array(new Array()) -}; - -async function importWrappedKeyItemTest() { + /* Encrypt the key. */ + await publicInitFunc(srcKeyAlias, encryptOptions); - console.info(`enter ImportWrapKey test`); - await publicImportKeyFunc(wrapAlias, huksOptions); + encryptOptions.inData = StringToUint8Array(cipherInData); + await publicUpdateFunc(handle, encryptOptions); + encryptUpdateResult = updateResult; - await publicExportKeyFunc(wrapAlias, huksOptions); + encryptOptions.inData = new Uint8Array(new Array()); + await publicFinishFunc(handle, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } - /* The following operation does not involve calling of HUKS APIs, and the specific implementation is not provided here. - * For example, import keyA. - * 1. Use ECC to generate a public and private key pair named keyB. The public key is keyB_pub, and the private key is keyB_pri. - * 2. Use keyB_pri and the public key obtained from wrappingAlias to negotiate the shared key share_key. - * 3. Randomly generate a key kek to encrypt keyA using AES-GCM. During the encryption, record nonce1, aad1, ciphertext keyA_enc, and encrypted tag1. - * 4. Use share_key to encrypt kek using AES-GCM. During the encryption, record nonce2, aad2, ciphertext kek_enc, and encrypted tag2. - * 5. Generate the **importOptions.inData** field in the following format: - * keyB_pub length (4 bytes) + keyB_pub + aad2 length (4 bytes) + aad2 + - * nonce2 length (4 bytes) + nonce2 + tag2 length (4 bytes) + tag2 + - * kek_enc length (4 bytes) + kek_enc + aad1 length (4 bytes) + aad1 + - * nonce1 length (4 bytes) + nonce1 + tag1 length (4 bytes) + tag1 + - * Memory occupied by the keyA length (4 bytes) + keyA length + keyA_enc length (4 bytes) + keyA_enc - */ - let inputKey = new Uint8Array([ - 0x5b, 0x00, 0x00, 0x00, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, - 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, - 0xfe, 0x1c, 0x67, 0xde, 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, - 0xaa, 0xc5, 0xd9, 0xd2, 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, - 0xac, 0x99, 0x3d, 0xe8, 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, - 0x7a, 0x41, 0xe5, 0x44, 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e, 0x10, - 0x00, 0x00, 0x00, 0xbf, 0xf9, 0x69, 0x41, 0xf5, 0x49, 0x85, 0x31, 0x35, 0x14, 0x69, 0x12, 0x57, - 0x9c, 0xc8, 0xb7, 0x10, 0x00, 0x00, 0x00, 0x2d, 0xb7, 0xf1, 0x5a, 0x0f, 0xb8, 0x20, 0xc5, 0x90, - 0xe5, 0xca, 0x45, 0x84, 0x5c, 0x08, 0x08, 0x10, 0x00, 0x00, 0x00, 0x43, 0x25, 0x1b, 0x2f, 0x5b, - 0x86, 0xd8, 0x87, 0x04, 0x4d, 0x38, 0xc2, 0x65, 0xcc, 0x9e, 0xb7, 0x20, 0x00, 0x00, 0x00, 0xf4, - 0xe8, 0x93, 0x28, 0x0c, 0xfa, 0x4e, 0x11, 0x6b, 0xe8, 0xbd, 0xa8, 0xe9, 0x3f, 0xa7, 0x8f, 0x2f, - 0xe3, 0xb3, 0xbf, 0xaf, 0xce, 0xe5, 0x06, 0x2d, 0xe6, 0x45, 0x5d, 0x19, 0x26, 0x09, 0xe7, 0x10, - 0x00, 0x00, 0x00, 0xf4, 0x1e, 0x7b, 0x01, 0x7a, 0x84, 0x36, 0xa4, 0xa8, 0x1c, 0x0d, 0x3d, 0xde, - 0x57, 0x66, 0x73, 0x10, 0x00, 0x00, 0x00, 0xe3, 0xff, 0x29, 0x97, 0xad, 0xb3, 0x4a, 0x2c, 0x50, - 0x08, 0xb5, 0x68, 0xe1, 0x90, 0x5a, 0xdc, 0x10, 0x00, 0x00, 0x00, 0x26, 0xae, 0xdc, 0x4e, 0xa5, - 0x6e, 0xb1, 0x38, 0x14, 0x24, 0x47, 0x1c, 0x41, 0x89, 0x63, 0x11, 0x04, 0x00, 0x00, 0x00, 0x20, - 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x0b, 0xcb, 0xa9, 0xa8, 0x5f, 0x5a, 0x9d, 0xbf, 0xa1, - 0xfc, 0x72, 0x74, 0x87, 0x79, 0xf2, 0xf4, 0x22, 0x0c, 0x8a, 0x4d, 0xd8, 0x7e, 0x10, 0xc8, 0x44, - 0x17, 0x95, 0xab, 0x3b, 0xd2, 0x8f, 0x0a - ]); + /* Decrypt the key. */ + await publicInitFunc(srcKeyAlias, decryptOptions); - importOptions.inData = inputKey; - await publicImportWrappedKey(importAlias, wrapAlias, importOptions); + decryptOptions.inData = new Uint8Array(encryptUpdateResult); + await publicUpdateFunc(handle, decryptOptions); - await publicDeleteKeyFunc(wrapAlias, huksOptions); - await publicDeleteKeyFunc(importAlias, importOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('importWrappedKeyItemTest') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - importWrappedKeyItemTest(); - }) - } - .width('100%') - .height('100%') + decryptOptions.inData = new Uint8Array(new Array()); + await publicFinishFunc(handle, decryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish decrypt success '); + } else { + console.info('test finish decrypt err'); } + + await publicDeleteKeyFunc(srcKeyAlias, huksOptions); } ``` -### Key Encryption and Decryption - -Use the symmetric or asymmetric key stored in HUKS to encrypt or decrypt data based on the specified alias. The keys in plaintext must be in a secure environment during the encryption and decryption process. - -The development procedure is as follows: - -1. Generate a key. -2. Encrypt the key. -3. Decrypt the key. - -**Supported key types**: - -| HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | -| ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- | -| HUKS_ALG_SM4 (supported key length: HUKS_SM4_KEY_SIZE_128)| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| Optional | HUKS_PADDING_NONE | HUKS_MODE_CTR HUKS_MODE_ECB HUKS_MODE_CBC | Mandatory | -| HUKS_ALG_SM4 (supported key length: HUKS_SM4_KEY_SIZE_128)| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| Optional | HUKS_PADDING_PKCS7 | HUKS_MODE_ECB HUKS_MODE_CBC | Mandatory | -| HUKS_ALG_RSA (supported lengths: HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096)| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE HUKS_PADDING_PKCS1_V1_5 HUKS_PADDING_OAEP | HUKS_MODE_ECB | Optional | - -| HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | HUKS_TAG_NONCE | HUKS_TAG_ASSOCIATED_DATA | HUKS_TAG_AE_TAG | -| ------------------------------------------------------------ | ------------------------ | ------------------------------------- | ---------------------------- | ----------- | -------------- | ------------------------ | --------------- | -| HUKS_ALG_AES (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| HUKS_MODE_CBC | Mandatory | Optional | Optional | Optional | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | Optional | Mandatory | Mandatory | Optional | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | Mandatory | Optional | Optional | Optional | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_ENCRYPT | HUKS_PADDING_PKCS7 HUKS_PADDING_NONE | HUKS_MODE_ECB | Mandatory | Optional | Optional | Optional | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| HUKS_MODE_CBC | Mandatory | Optional | Optional | Mandatory | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CCM HUKS_MODE_GCM | Optional | Mandatory | Mandatory | Optional | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE | HUKS_MODE_CTR | Mandatory | Optional | Optional | Optional | -| HUKS_ALG_AES | HUKS_KEY_PURPOSE_DECRYPT | HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| HUKS_MODE_ECB | Mandatory | Optional | Optional | Optional | - -> **NOTE**
-> -> The key alias cannot exceed 64 bytes. - -Before you get started, understand the following variables: +### Signing and Signature Verification +```ts +/* + * Generate and verify a signature using an SM2 key and return the result in a callback. + */ +import huks from '@ohos.security.huks'; -| Parameter | Type | Mandatory| Description | -| -------------- | ----------- | ---- | ------------------------ | -| srcKeyAlias | string | Yes | Alias of the key. | -| huksOptions | HuksOptions | Yes | Tags required for generating the key.| -| encryptOptions | HuksOptions | Yes | Tags required for encrypting the key.| -| decryptOptions | HuksOptions | Yes | Tags required for decrypting the key.| +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let generateKeyAlias = 'sm2_Key'; +let importKeyAlias = 'importKeyAlias'; +let signVerifyInData = 'signVerifyInDataForTest'; +let handle; +let exportKey; +let finishOutData; -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +/* Configure the parameter set used for generating the key. */ +let generateKeyProperties = new Array(); +generateKeyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM2, +} +generateKeyProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY, +} +generateKeyProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, +} +generateKeyProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, +} +let genrateKeyOptions = { + properties: generateKeyProperties, + inData: new Uint8Array(new Array()) +} -**Example 1:** +/* Configure the parameter set used for signing. */ +let signProperties = new Array(); +signProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM2, +} +signProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN +} +signProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, +} +signProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, +} +let signOptions = { + properties: signProperties, + inData: new Uint8Array(new Array()) +} -```ts -/* The cipher operation supports RSA, AES, and SM4 keys. - * - * The following uses the Promise() operation of an SM4 128-bit key as an example. - */ -import huks from '@ohos.security.huks'; +/* Configure the parameter set used for signature verification. */ +let verifyProperties = new Array(); +verifyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM2, +} +verifyProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +} +verifyProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, +} +verifyProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, +} +let verifyOptions = { + properties: verifyProperties, + inData: new Uint8Array(new Array()) +} function StringToUint8Array(str) { let arr = []; @@ -1133,33 +1068,47 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); } async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await generateKeyItem(keyAlias, huksOptions) + await generateKeyItem(keyAlias, huksOptions, throwObject) .then((data) => { console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1167,47 +1116,74 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise doInit`); + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await huks.initSession(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`promise: doInit success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); handle = data.handle; }) - .catch(error => { - console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; try { - await updateSession(handle, huksOptions) + await updateSession(handle, huksOptions, throwObject) .then ((data) => { console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - updateResult = Array.from(data.outData); }) .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.updateSession(handle, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1215,6 +1191,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - finishOutData = Uint8ArrayToString(new Uint8Array(updateResult)); + finishOutData = data.outData; console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.finishSession(handle, huksOptions, function (error, data) { + huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1247,30 +1229,37 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportKey = data.outData; }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { + huks.importKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1278,157 +1267,214 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -let IV = '0000000000000000'; -let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; -let srcKeyAlias = 'huksCipherSm4SrcKeyAlias'; -let encryptUpdateResult = new Array(); -let handle; -let updateResult = new Array(); -let finishOutData; - -async function testSm4Cipher() { - /* Integrate the key generation parameter set and key encryption parameter set. */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - - let propertiesEncrypt = new Array(); - propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM4, - } - propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, - } - propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, - } - propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_IV, - value: StringToUint8Array(IV), +async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter promise importKeyItem`); + let throwObject = {isThrow: false}; + try { + await importKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } - let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) +} + +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } +} +async function testSm2SignVerify() { /* Generate a key. */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); + await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions); - /* Encrypt the key. */ - await publicInitFunc(srcKeyAlias, encryptOptions); - - encryptOptions.inData = StringToUint8Array(cipherInData); - await publicUpdateFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; + /* Generate a signature. */ + let signHandle; + let signFinishOutData; + await publicInitFunc(generateKeyAlias, signOptions); - encryptOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, encryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } + signHandle = handle; + signOptions.inData = StringToUint8Array(signVerifyInData) + await publicUpdateFunc(signHandle, signOptions); - /* Modify the key encryption parameter set to the decryption parameter set. */ - propertiesEncrypt.splice(1, 1, { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - }); - let decryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } + signOptions.inData = new Uint8Array(new Array()); + await publicFinishFunc(signHandle, signOptions); + signFinishOutData = finishOutData; - /* Decrypt the key. */ - await publicInitFunc(srcKeyAlias, decryptOptions); + /* Export the key. */ + await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions); - decryptOptions.inData = new Uint8Array(encryptUpdateResult); - await publicUpdateFunc(handle, decryptOptions); + /* Import the key. */ + verifyOptions.inData = exportKey; + await publicImportKeyFunc(importKeyAlias, verifyOptions); - decryptOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, decryptOptions); - if (finishOutData === cipherInData) { - console.info('test finish decrypt success '); - } else { - console.info('test finish decrypt err'); - } + /* Verify the signature. */ + let verifyHandle; + await publicInitFunc(importKeyAlias, verifyOptions); - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} + verifyHandle = handle; -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testSm4Cipher') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testSm4Cipher(); - }) - } - .width('100%') - .height('100%') - } + verifyOptions.inData = StringToUint8Array(signVerifyInData) + await publicUpdateFunc(verifyHandle, verifyOptions); + + verifyOptions.inData = signFinishOutData; + await publicFinishFunc(verifyHandle, verifyOptions); + + await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions); + await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions); } ``` -**Example 2:** - +### Key Agreement ```ts -/* The cipher operation supports RSA, AES, and SM4 keys. - * - * The following uses the Promise() operation of an AES128 GCM key as an example. +/* + * Perform key agreement using an X25519 256-bit TEMP key and return the result in a callback. */ import huks from '@ohos.security.huks'; +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; +let srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; +let agreeX25519InData = 'AgreeX25519TestIndata'; +let finishOutData; +let handle; +let exportKey; +let exportKeyFrist; +let exportKeySecond; + +/* Configure the parameter set used for generating the key. */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_X25519, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +let HuksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} + +/* Configure parameters for the first key agreement. */ +let finishProperties = new Array(); +finishProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP, +} +finishProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, + value: true +} +finishProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +finishProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, +} +finishProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +finishProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, +} +finishProperties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, + value: StringToUint8Array(srcKeyAliasFirst+ 'final'), +} +finishProperties[7] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +finishProperties[8] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, +} +let finishOptionsFrist = { + properties: finishProperties, + inData: StringToUint8Array(agreeX25519InData) +} +/* Configure parameters for the second key agreement. */ +let finishOptionsSecond = { + properties: finishProperties, + inData: StringToUint8Array(agreeX25519InData) +} +finishOptionsSecond.properties.splice(6, 1, { + tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, + value: StringToUint8Array(srcKeyAliasSecond + 'final'), +}) + function StringToUint8Array(str) { let arr = []; for (let i = 0, j = str.length; i < j; ++i) { @@ -1437,33 +1483,47 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -function Uint8ArrayToString(fileData) { - let dataString = ''; - for (let i = 0; i < fileData.length; i++) { - dataString += String.fromCharCode(fileData[i]); - } - return dataString; +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); } async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await generateKeyItem(keyAlias, huksOptions) + await generateKeyItem(keyAlias, huksOptions, throwObject) .then((data) => { console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1471,47 +1531,74 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise doInit`); + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await huks.initSession(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`promise: doInit success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); handle = data.handle; }) - .catch(error => { - console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`); + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.updateSession(handle, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; try { - await updateSession(handle, huksOptions) + await updateSession(handle, huksOptions, throwObject) .then ((data) => { console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - updateResult = Array.from(data.outData); }) .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.updateSession(handle, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1519,6 +1606,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - updateResult = updateResult.concat(Array.from(data.outData)); + finishOutData = data.outData; console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.finishSession(handle, huksOptions, function (error, data) { + huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1551,27 +1644,34 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); + exportKey = data.outData; }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { @@ -1582,227 +1682,165 @@ function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -let AAD = '0000000000000000'; -let NONCE = '000000000000'; -let AEAD = '0000000000000000'; -let cipherInData = 'Hks_AES_Cipher_Test_00000000000000000000000000000000000000000000000000000_string'; -let srcKeyAlias = 'huksCipherSm4SrcKeyAlias'; -let updateResult = new Array(); -let encryptUpdateResult = new Array(); -let decryptUpdateResult = new Array(); -let handle; -let finishOutData; - -async function testAesCipher() { - /* Integrate the key generation parameter set and key encryption parameter set. */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_GCM, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) +async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback deleteKeyItem`); + let throwObject = {isThrow: false}; + try { + await deleteKeyItem(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } +} - let propertiesEncrypt = new Array(); - propertiesEncrypt[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - propertiesEncrypt[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, - } - propertiesEncrypt[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - } - propertiesEncrypt[3] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - propertiesEncrypt[4] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_GCM, - } - propertiesEncrypt[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - propertiesEncrypt[6] = { - tag: huks.HuksTag.HUKS_TAG_ASSOCIATED_DATA, - value: StringToUint8Array(AAD), - } - propertiesEncrypt[7] = { - tag: huks.HuksTag.HUKS_TAG_NONCE, - value: StringToUint8Array(NONCE), - } - propertiesEncrypt[8] = { - tag: huks.HuksTag.HUKS_TAG_AE_TAG, - value: StringToUint8Array(AEAD), - } - let encryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } +async function testAgree() { + /* 1. Generate two keys and export them. */ + await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions); + await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions); - /* Generate a key. */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); - - /* Encrypt the key. */ - await publicInitFunc(srcKeyAlias, encryptOptions); - - encryptOptions.inData = StringToUint8Array(cipherInData.slice(0,64)); - await publicUpdateFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; - - encryptOptions.inData = StringToUint8Array(cipherInData.slice(64,80)); - await publicFinishFunc(handle, encryptOptions); - encryptUpdateResult = updateResult; - finishOutData = Uint8ArrayToString(new Uint8Array(encryptUpdateResult)); - if (finishOutData === cipherInData) { - console.info('test finish encrypt err '); - } else { - console.info('test finish encrypt success'); - } - - /* Modify the key encryption parameter set to the decryption parameter set. */ - propertiesEncrypt.splice(1, 1, { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - }); - propertiesEncrypt.splice(8, 1, { - tag: huks.HuksTag.HUKS_TAG_AE_TAG, - value: new Uint8Array(encryptUpdateResult.splice(encryptUpdateResult.length - 16,encryptUpdateResult.length)) - }); - let decryptOptions = { - properties: propertiesEncrypt, - inData: new Uint8Array(new Array()) - } - - /* Decrypt the key. */ - await publicInitFunc(srcKeyAlias, decryptOptions); - - decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(0,64)); - await publicUpdateFunc(handle, decryptOptions); - decryptUpdateResult = updateResult; + await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); + exportKeyFrist = exportKey; + await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); + exportKeySecond = exportKey; - decryptOptions.inData = new Uint8Array(encryptUpdateResult.slice(64,encryptUpdateResult.length)); - await publicFinishFunc(handle, decryptOptions); - decryptUpdateResult = updateResult; - finishOutData = Uint8ArrayToString(new Uint8Array(decryptUpdateResult)); - if (finishOutData === cipherInData) { - console.info('test finish decrypt success '); - } else { - console.info('test finish decrypt err'); - } + /* Perform key agreement for the first. */ + await publicInitFunc(srcKeyAliasFirst, HuksOptions); + HuksOptions.inData = exportKeySecond; + await publicUpdateFunc(handle, HuksOptions); + await publicFinishFunc(handle, finishOptionsFrist); - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} + /* Perform key agreement for the second key. */ + await publicInitFunc(srcKeyAliasSecond, HuksOptions); + HuksOptions.inData = exportKeyFrist; + await publicUpdateFunc(handle, HuksOptions); + await publicFinishFunc(handle, finishOptionsSecond); -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAesCipher') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAesCipher(); - }) - } - .width('100%') - .height('100%') - } + await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions); + await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions); } ``` -### Signing and Signature Verification - -The data to be sent can be signed with a unique signature for security purposes. Then, the receiver needs to verify the signature when receiving the data. - -The development procedure is as follows: - -1. Generate a key. -2. Use the key to sign the data to be sent. -3. Export the signature key. -4. Import the signature key. -5. Verify the signature. - -**Supported key types**: - -Only **HksInit()** has requirements on parameters in **paramSet**. The other Init-Update-Finish APIs have no requirements on **paramSet**. - -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | HUKS_ALG_PADDING | HUKS_TAG_DIGEST | -| ------------------ | ------------------------------------------------------------ | ---------------------------------------------- | ----------------------- | ------------------------------------------------------------ | -| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PKCS1_V1_5 | HUKS_DIGEST_MD5, HUKS_DIGEST_NONE, HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| -| HUKS_ALG_RSA | HUKS_RSA_KEY_SIZE_512, HUKS_RSA_KEY_SIZE_768, HUKS_RSA_KEY_SIZE_1024, HUKS_RSA_KEY_SIZE_2048, HUKS_RSA_KEY_SIZE_3072, HUKS_RSA_KEY_SIZE_4096| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | HUKS_PADDING_PSS | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| -| HUKS_ALG_DSA | HUKS_RSA_KEY_SIZE_1024 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| -| HUKS_ALG_ECC | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | Optional | HUKS_DIGEST_NONE, HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| - -The signing and signature verification using Ed25519 involves a hash operation in the algorithm engine. Therefore, the Init-Update-Finish processing is special. - -In the **update()** process, **inData** is sent to HUKS Core and recorded in a .ctx file, without performing hash operation. The signing and signature verification calculations are performed on the combined **inData** in the **finish()** operation. - -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | -| ------------------ | ---------------------------- | ----------------------------------------------- | -| HUKS_ALG_ED25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_SIGN HUKS_KEY_PURPOSE_VERIFY | - -> **NOTE**
-> -> The key alias cannot exceed 64 bytes. - -Before you get started, understand the following variables: +### Key Derivation +```ts +/* + * The following uses the Promise() operation of an HKDF256 key as an example. + */ +import huks from '@ohos.security.huks'; -| Parameter | Type | Mandatory| Description | -| ----------------- | ----------- | ---- | ------------------------ | -| generateKeyAlias | string | Yes | Alias of the key to generate. | -| importKeyAlias | string | Yes | Alias of the key imported. | -| genrateKeyOptions | HuksOptions | Yes | Tags required for generating the key.| -| signOptions | HuksOptions | Yes | Tags required for signing.| -| verifyOptions | HuksOptions | Yes | Tags required for verifying the signature.| +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let srcKeyAlias = "hkdf_Key"; +let deriveHkdfInData = "deriveHkdfTestIndata"; +let handle; +let finishOutData; +let HuksKeyDeriveKeySize = 32; -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +/* Configure the parameter set used for generating the key. */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} -**Example** +/* Configure the parameter set used for init(). */ +let initProperties = new Array(); +initProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_HKDF, +} +initProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE, +} +initProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, +} +initProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE, + value: HuksKeyDeriveKeySize, +} +let initOptions = { + properties: initProperties, + inData: new Uint8Array(new Array()) +} -```ts -/*The Sign() and Verify() operations support RSA, ECC, SM2, ED25519, and DSA keys. - * - * The following uses an SM2 key in callback-based APIs as an example. - */ -import huks from '@ohos.security.huks'; +/* Configure the parameter set used for finish(). */ +let finishProperties = new Array(); +finishProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT, +} +finishProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, + value: true, +} +finishProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_AES, +} +finishProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, +} +finishProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | + huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +finishProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, +} +finishProperties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, + value: StringToUint8Array(srcKeyAlias), +} +finishProperties[7] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +finishProperties[8] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB, +} +let finishOptions = { + properties: finishProperties, + inData: new Uint8Array(new Array()) +} function StringToUint8Array(str) { let arr = []; @@ -1812,25 +1850,47 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { + try { + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await generateKeyItem(keyAlias, huksOptions) + await generateKeyItem(keyAlias, huksOptions, throwObject) .then((data) => { console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + huks.initSession(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1838,6 +1898,7 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); @@ -1845,24 +1906,29 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; try { - await initSession(keyAlias, huksOptions) + await initSession(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`); + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); handle = data.handle; }) .catch((error) => { - console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { +function updateSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.initSession(keyAlias, huksOptions, function (error, data) { + huks.updateSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1870,6 +1936,7 @@ function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function finishSession(handle:number, huksOptions:huks.HuksOptions, throwObject) : Promise { return new Promise((resolve, reject) => { try { - huks.updateSession(handle, huksOptions, function (error, data) { + huks.finishSession(handle, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1901,6 +1973,7 @@ function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - finishOutData = data.outData;; + finishOutData = data.outData; console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { +function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { - huks.finishSession(handle, huksOptions, function (error, data) { + huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { if (error) { reject(error); } else { @@ -1933,1541 +2011,587 @@ function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - exportKey = data.outData; + console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: deletKeeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +async function testDerive() { + /* Generate a key. */ + await publicGenKeyFunc(srcKeyAlias, huksOptions); + + /* Derive a key. */ + await publicInitFunc(srcKeyAlias, initOptions); + + initOptions.inData = StringToUint8Array(deriveHkdfInData); + await publicUpdateFunc(handle, initOptions); + await publicFinishFunc(handle, finishOptions); + + await publicDeleteKeyFunc(srcKeyAlias, huksOptions); } +``` -async function publicImportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise importKeyItem`); +## Key Access Control + +The HUKS provides comprehensive key access control to prevent unauthorized access. + +Services can access only their own keys, that is, the keys generated or imported through HUKS. +In addition, the HUKS supports user identity authentication for security-sensitive services. Users can use the service keys only after the authentication (PIN or biometric authentication) is successful. +The HUKS also restricts the key usage. For example, the AES keys can only be used for encryption and decryption, and the RSA keys can only be used for signing and signature verification. + +**User Identity Authentication** + +When generating or importing a key, you can enable user identity authentication for the key use. You can specify a subset of credentials (lock screen password, fingerprint, and face) for user identity authentication. After a key is generated or imported, unauthorized key access can be prevented even if the application process is attacked. Key access control applies to security-sensitive scenarios, such as password-free login, password-free payment, and automatic password filling. + +In addition to user identity authentication, the authorized key access type (key expiration condition) must be either of the following types: +- Invalidate the key when the screen lock password is cleared.
This type takes effect only when a screen lock password has been set. If the screen lock password is cleared, the key becomes invalid permanently. The key will not be invalidated if the screen lock password is modified. Use this type for user-related data protection or access based on screen lock passwords. +- Invalidate the key when new biometric enrollments are added.
This type takes effect only when at least one biometric feature (such as fingerprint) has been enrolled. The key becomes invalid permanently once a new biometric feature is enrolled. The key will not be invalidated if the biometric feature is deleted. You can use this type for scenarios, such as password-free login or payment. + +To ensure the validity of the user authentication result, the HUKS supports challenge value verification. Before user identity authentication, obtain the challenge (in the [HuksSessionHandle](../reference/apis/js-apis-huks.md#hukssessionhandle9) returned by [huks.initSession()](../reference/apis/js-apis-huks.md#huksinitsession9)) from the HUKS and pass in the challenge in [userIAM_userAuth.getAuthInstance](../reference/apis/js-apis-useriam-userauth.md#authinstance9). The challenge value of the authentication token is then verified during key operations. + +**How to Develop** + +If secondary user identity authentication is enabled for a key, initialize the key session and obtain the challenge value. Then, pass the challenge value to **userIAM_userAuth.getAuthInstance()** for user identity authentication. After the authentication is successful, an authentication token is obtained. The authentication token can be used to perform key operations. + +![huks_key_user_auth_work_flow](./figures/huks_key_user_auth_work_flow.png) + +**Available APIs** + +1. [HuksUserAuthType](../reference/apis/js-apis-huks.md#huksuserauthtype9), [HuksAuthAccessType](../reference/apis/js-apis-huks.md#huksauthaccesstype9), and [HuksChallengeType](../reference/apis/js-apis-huks.md#hukschallengetype9) in the key attribute set are mandatory for key generation/import. + + **Table 3** User authentication types + + | Name | Value | Description | + | ------------------------------- |---|------------------------ | + | HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication. | + | HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication.| + | HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication. | + + > **NOTE** + > + > You can specify any or a combination of the three authentication types. + + + **Table 4** Secure access types + + | Name | Value | Description | + | --------------------------------------- | ---- | ------------------------------------------------ | + | HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidates the key after the screen lock password is cleared. | + | HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidates the key after a biometric enrollment is added. The user authentication types must include the biometric authentication.| + + > **NOTE** + > + > **HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD** and **HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL** are mutually exclusive. + + **Table 5** Challenge types + + | Name | Value | Description | + | ------------------------------- | ---- | ------------------------------ | + | HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key.| + | HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys.| + | HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication.| + + > **NOTICE** + > + > The three challenge types are mutually exclusive. + > + > If the challenge type is **HUKS_CHALLENGE_TYPE_NONE**, no challenge is required. However, the key can be accessed only within a specified time period (set by **HUKS_TAG_AUTH_TIMEOUT**) after a successful authentication. The maximum value of **HUKS_TAG_AUTH_TIMEOUT** is 60 seconds. + + +2. To use a key, initialize the key session, and determine whether a challenge is required based on the challenge type specified when the key is generated or imported. + + **Table 6** APIs for using a key + + | API | Description | + |-------------- | ------------------------------------ | + | initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void |Initializes the key session and obtains the challenge value.| + | updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void| Operates data by segment and passes the authentication token.| + | finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void | Finalizes the key session.| + + + +**How to Develop** + + +1. Generate a key and specify user authentication attributes. + +```ts +import huks from '@ohos.security.huks'; + +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let keyAlias = 'dh_key_fingerprint_access'; +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +// Enable fingerprint authentication. +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_USER_AUTH_TYPE, + value: huks.HuksUserAuthType.HUKS_USER_AUTH_TYPE_FINGERPRINT +} +// Set the key expiration type. Invalidate the key when a new biometric feature (fingerprint) is enrolled. +properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_AUTH_ACCESS_TYPE, + value: huks.HuksAuthAccessType.HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL +} +// Use the default challenge type. +properties[7] = { + tag: huks.HuksTag.HUKS_TAG_CHALLENGE_TYPE, + value: huks.HuksChallengeType.HUKS_CHALLENGE_TYPE_NORMAL +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) +} + +/* + * Generate a key. + */ +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { + return new Promise((resolve, reject) => { try { - await importKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: importKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: importKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); + huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); } catch (error) { - console.error(`callback: importKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + throwObject.isThrow = true; + throw(error); } + }); } -function importKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.importKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; + try { + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -let signVerifyInData = 'signVerifyInDataForTest'; -let generateKeyAlias = 'generateKeyAliasForTest'; -let importKeyAlias = 'importKeyAliasForTest'; -let handle; -let exportKey; -let finishOutData; - -/* Configure the parameters for generating the key. */ -let generateKeyProperties = new Array(); -generateKeyProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -generateKeyProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY, -} -generateKeyProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -generateKeyProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -let genrateKeyOptions = { - properties: generateKeyProperties, - inData: new Uint8Array(new Array()) -} - -/* Configure the parameters for signing. */ -let signProperties = new Array(); -signProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -signProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_SIGN -} -signProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -signProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -let signOptions = { - properties: signProperties, - inData: new Uint8Array(new Array()) -} - -/* Configure the parameters for signature verification. */ -let verifyProperties = new Array(); -verifyProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM2, -} -verifyProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY -} -verifyProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, -} -verifyProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_SM2_KEY_SIZE_256, -} -let verifyOptions = { - properties: verifyProperties, - inData: new Uint8Array(new Array()) -} - -async function testSm2SignVerify() { - /* Generate a key. */ - await publicGenKeyFunc(generateKeyAlias, genrateKeyOptions); - - /* Generate a signature. */ - let signHandle; - let signFinishOutData; - await publicInitFunc(generateKeyAlias, signOptions); - - signHandle = handle; - signOptions.inData = StringToUint8Array(signVerifyInData) - await publicUpdateFunc(signHandle, signOptions); - - signOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(signHandle, signOptions); - signFinishOutData = finishOutData; - - /* Export the key. */ - await publicExportKeyFunc(generateKeyAlias, genrateKeyOptions); - - /* Import the key. */ - verifyOptions.inData = exportKey; - await publicImportKeyFunc(importKeyAlias, verifyOptions); - - /* Verify the signature. */ - let verifyHandle; - await publicInitFunc(importKeyAlias, verifyOptions); - - verifyHandle = handle; - - verifyOptions.inData = StringToUint8Array(signVerifyInData) - await publicUpdateFunc(verifyHandle, verifyOptions); - - verifyOptions.inData = signFinishOutData; - await publicFinishFunc(verifyHandle, verifyOptions); - - await publicDeleteKeyFunc(generateKeyAlias, genrateKeyOptions); - await publicDeleteKeyFunc(importKeyAlias, genrateKeyOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testSm2SignVerify') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testSm2SignVerify(); - }) - } - .width('100%') - .height('100%') - } -} -``` - -### Key Agreement - -Two or more objects communicate with each other based on the same session key. - -The development procedure is as follows: - -1. Generate two keys. -2. Export the keys separately. -3. Perform key agreement. - -**Supported key types**: - -The **HksInit()** and **HksFinish()** APIs have requirements on **paramSet**. The **HksUpdate()** API has no requirements on **paramSet**. - -Requirements of **HksInit()** for **paramSet**: - -| HUKS_ALG_ALGORITHM | HUKS_ALG_KEY_SIZE | HUKS_ALG_PURPOSE | -| ------------------ | ------------------------------------------------------------ | ---------------------- | -| HUKS_ALG_ECDH | HUKS_ECC_KEY_SIZE_224, HUKS_ECC_KEY_SIZE_256, HUKS_ECC_KEY_SIZE_384, HUKS_ECC_KEY_SIZE_521| HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_DH | HUKS_DH_KEY_SIZE_2048, HUKS_DH_KEY_SIZE_3072, HUKS_DH_KEY_SIZE_4096| HUKS_KEY_PURPOSE_AGREE | -| HUKS_ALG_X25519 | HUKS_CURVE25519_KEY_SIZE_256 | HUKS_KEY_PURPOSE_AGREE | - -Requirements of **HksFinish()** for **paramSet**: - -The derived key is used as a symmetric key. - -| HUKS_TAG_KEY_STORAGE_FLAG | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_DIGEST | HUKS_TAG_BLOCK_MODE | -| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------ | ------------------------------------------------------------ | ------------------------------------------- | -| **HUKS_STORAGE_TEMP** or not set| Not required | TRUE | Not required | Not required | Not required | Not required | Not required | Not required | -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_PKCS7 | Optional | HUKS_MODE_CCM HUKS_MODE_GCM HUKS_MODE_CTP | -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_DERIVE | Optional | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512 | Optional | -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_HMAC | Multiple of 8, in bits | HUKS_KEY_PURPOSE_MAC | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Optional | - -> **NOTE**
-> -> The length of the key after agreement (converted into bits) must be greater than or equal to the selected **HUKS_TAG_KEY_SIZE**. -> -> The key alias cannot exceed 64 bytes. - -Before you get started, understand the following variables: - -| Parameter | Type | Mandatory| Description | -| ------------------- | ----------- | ---- | -------------------------------------- | -| srcKeyAliasFirst | string | Yes | Alias of the key generated. | -| srcKeyAliasSecond | string | Yes | Alias of key 2 generated. | -| huksOptions | HuksOptions | Yes | Tags required for generating the key. | -| finishOptionsFrist | HuksOptions | Yes | Tags required for key agreement. | -| finishOptionsSecond | HuksOptions | Yes | Tags required for key agreement.| - -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). - -**Example** - -```ts -/* The agree() operation supports ECDH, DH, and X25519 keys. - * - * The following uses the Promise() operation of an X25519 256-bit TEMP key as an example. - */ -import huks from '@ohos.security.huks'; - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - try { - await initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - try { - await updateSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - try { - await finishSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicExportKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback export`); - try { - await exportKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: exportKeyItem success, data = ${JSON.stringify(data)}`); - exportKey = data.outData; - }) - .catch(error => { - console.error(`callback: exportKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: exportKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function exportKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.exportKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -let srcKeyAliasFirst = "AgreeX25519KeyFirstAlias"; -let srcKeyAliasSecond = "AgreeX25519KeySecondAlias"; -let agreeX25519InData = 'AgreeX25519TestIndata'; -let handle; -let exportKey; -let exportKeyFrist; -let exportKeySecond; - -async function testAgree() { - /* Configure the parameters for generating the key. */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_X25519, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_CURVE25519_KEY_SIZE_256, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_CBC, - } - let HuksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - - /* 1. Generate two keys and export them. */ - await publicGenKeyFunc(srcKeyAliasFirst, HuksOptions); - await publicGenKeyFunc(srcKeyAliasSecond, HuksOptions); - - await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); - exportKeyFrist = exportKey; - await publicExportKeyFunc(srcKeyAliasFirst, HuksOptions); - exportKeySecond = exportKey; - - /* Configure parameters for the first key agreement. */ - let finishProperties = new Array(); - finishProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_TEMP, - } - finishProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, - value: true - } - finishProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - finishProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - } - finishProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - finishProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - finishProperties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, - value: StringToUint8Array(srcKeyAliasFirst+ 'final'), - } - finishProperties[7] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - finishProperties[8] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB, - } - let finishOptionsFrist = { - properties: finishProperties, - inData: StringToUint8Array(agreeX25519InData) - } - - /* Obtain the first agreed key. */ - await publicInitFunc(srcKeyAliasFirst, HuksOptions); - HuksOptions.inData = exportKeySecond; - await publicUpdateFunc(handle, HuksOptions); - await publicFinishFunc(handle, finishOptionsFrist); - - /* Configure parameters for the second key agreement. */ - let finishOptionsSecond = { - properties: finishProperties, - inData: StringToUint8Array(agreeX25519InData) - } - finishOptionsSecond.properties.splice(6, 1, { - tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, - value: StringToUint8Array(srcKeyAliasSecond + 'final'), - }) - - /* Obtain the second agreed key. */ - await publicInitFunc(srcKeyAliasSecond, HuksOptions); - HuksOptions.inData = exportKeyFrist; - await publicUpdateFunc(handle, HuksOptions); - await publicFinishFunc(handle, finishOptionsSecond); - - - await publicDeleteKeyFunc(srcKeyAliasFirst, HuksOptions); - await publicDeleteKeyFunc(srcKeyAliasSecond, HuksOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAgree') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAgree(); - }) - } - .width('100%') - .height('100%') - } -} -``` - -### Key Derivation - -Derive one or more keys from a key. - -The development procedure is as follows: - -1. Generate a key. -2. Derive a key. - -**Supported key types**: - -The **HksInit()** and **HksFinish()** APIs have requirements on **paramSet**. The **HksUpdate()** API has no requirements on **paramSet**. - -Requirements of **HksInit()** for **paramSet**: - -| HUKS_TAG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_DERIVE_KEY_SIZE | -| ------------------------------------------------------------ | ----------------------- | ---------------------------------------------------------- | ------------------------ | -| HUKS_ALG_HKDF (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | Mandatory | -| HUKS_ALG_PBKDF2 (supported key lengths: HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256)| HUKS_KEY_PURPOSE_DERIVE | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Mandatory | - -Requirements of **HksFinish()** for **paramSet**: - -The derived key is used as a symmetric key. - -| HUKS_TAG_KEY_STORAGE_FLAG | HUKS_TAG_KEY_ALIAS | HUKS_TAG_IS_KEY_ALIAS | HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_DIGEST | HUKS_TAG_BLOCK_MODE | -| ------------------------------ | ------------------ | --------------------- | ------------------ | ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------ | ------------------------------------------- | -| **HUKS_STORAGE_TEMP** or not set| Not required | TRUE | Not required | Not required | Not required | Not required | Not required | Not required | -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_NONE, HUKS_PADDING_PKCS7| Optional | HUKS_MODE_CBC HUKS_MODE_ECB | -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_ENCRYPT or HUKS_KEY_PURPOSE_DECRYPT| HUKS_PADDING_NONE | Optional | HUKS_MODE_CCM, HUKS_MODE_GCM, HUKS_MODE_CTR| -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_AES | HUKS_AES_KEY_SIZE_128, HUKS_AES_KEY_SIZE_192, HUKS_AES_KEY_SIZE_256| HUKS_KEY_PURPOSE_DERIVE | Optional | HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512 | Optional | -| HUKS_STORAGE_PERSISTENT | (Mandatory) Maximum 64 bytes.| TRUE | HUKS_ALG_HMAC | Multiple of 8, in bits | HUKS_KEY_PURPOSE_MAC | Optional | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Optional | - -> **NOTE**
-> -> The length of the derived key (converted into bits) must be greater than or equal to the selected **HUKS_TAG_KEY_SIZE**. -> -> The key alias cannot exceed 64 bytes. - -Before you get started, understand the following variables: - -| Parameter | Type | Mandatory| Description | -| ------------- | ----------- | ---- | ---------------- | -| srcKeyAlias | string | Yes | Alias of the key generated. | -| huksOptions | HuksOptions | Yes | Parameters for generating the key.| -| finishOptions | HuksOptions | Yes | Parameters for deriving a key.| - -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). - -**Example** - -```ts -/*The derive() operation supports HKDF and pbdkf keys. - * - * The following uses the Promise() operation of an HKDF256 key as an example. - */ -import huks from '@ohos.security.huks'; - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter promise doInit`); - try { - await huks.initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`promise: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch(error => { - console.error(`promise: doInit key failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`promise: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - try { - await updateSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - try { - await finishSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -let deriveHkdfInData = "deriveHkdfTestIndata"; -let srcKeyAlias = "deriveHkdfKeyAlias"; -let handle; -let HuksKeyDeriveKeySize = 32; - -async function testDerive() { - /* Configure the parameters for generating the key. */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DERIVE, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - } - let huksOptions = { - properties: properties, - inData: new Uint8Array(new Array()) - } - - /* Generate a key. */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); - - /* Modify the parameter set for init(). */ - huksOptions.properties.splice(0, 1, { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_HKDF, - }); - huksOptions.properties.splice(3, 1, { - tag: huks.HuksTag.HUKS_TAG_DERIVE_KEY_SIZE, - value: HuksKeyDeriveKeySize, - }); - - let finishProperties = new Array(); - finishProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT, - } - finishProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_IS_KEY_ALIAS, - value: true, - } - finishProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - } - finishProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - } - finishProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | - huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, - } - finishProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_NONE, - } - finishProperties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_ALIAS, - value: StringToUint8Array(srcKeyAlias), - } - finishProperties[7] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_NONE, - } - finishProperties[8] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB, - } - let finishOptions = { - properties: finishProperties, - inData: new Uint8Array(new Array()) - } - - /* Derive a key. */ - await publicInitFunc(srcKeyAlias, huksOptions); - - huksOptions.inData = StringToUint8Array(deriveHkdfInData); - await publicUpdateFunc(handle, huksOptions); - await publicFinishFunc(handle, finishOptions); - - huksOptions.properties.splice(0, 1, { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_AES, - }); - huksOptions.properties.splice(3, 1, { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_128, - }); - - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testDerive') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testDerive(); - }) - } - .width('100%') - .height('100%') - } -} -``` - -### Key MAC - -A message authentication code (MAC) is a hash-based value used for authenticating a message. It is used to check whether the message comes from the stated sender and has not been changed. - -The development procedure is as follows: - -1. Generate a key. -2. Generate a MAC. - -**Supported key types**: - -Only **HksInit()** has requirements on parameters in **paramSet**. The other Init-Update-Finish APIs have no requirements on **paramSet**. - -| HUKS_TAG_ALGORITHM | HUKS_TAG_KEY_SIZE | HUKS_TAG_PURPOSE | HUKS_TAG_DIGEST | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | -| ------------ | ---------- | ------------------- | ------------------------------------------------------------ | ---------- | ---------- | -| HUKS_ALG_HMAC | Optional| HUKS_KEY_PURPOSE_MAC | HUKS_DIGEST_SHA1, HUKS_DIGEST_SHA224, HUKS_DIGEST_SHA256, HUKS_DIGEST_SHA384, HUKS_DIGEST_SHA512| Optional| Optional| -| HUKS_ALG_SM3 | Optional| HUKS_KEY_PURPOSE_MAC | HUKS_DIGEST_SM3 | Optional| Optional| - -> **NOTE**
-> -> The key alias cannot exceed 64 bytes. - -Before you get started, understand the following variables: - -| Parameter | Type | Mandatory| Description | -| ----------- | ----------- | ---- | -------------- | -| srcKeyAlias | string | Yes | Alias of the key generated.| -| huksOptions | HuksOptions | Yes | Key parameter set. | - -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). - -**Example** - -```ts -/*The mac() operation supports HMAC and SM3 keys. - * - * The following uses the Promise() operation of an SM3 256-bit key as an example. - */ -import huks from '@ohos.security.huks'; - -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} - -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback doInit`); - try { - await initSession(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback1: doInit success, data = ${JSON.stringify(data)}`); - handle = data.handle; - }) - .catch((error) => { - console.error(`callback1: doInit failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function initSession(keyAlias:string, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.initSession(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicUpdateFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doUpdate`); - try { - await updateSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function updateSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.updateSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicFinishFunc(handle:number, huksOptions:huks.HuksOptions) { - console.info(`enter callback doFinish`); - try { - await finishSession(handle, huksOptions) - .then ((data) => { - console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function finishSession(handle:number, huksOptions:huks.HuksOptions) : Promise { - return new Promise((resolve, reject) => { - try { - huks.finishSession(handle, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); - try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); -} - -let srcKeyAlias = "sm3KeyAlias"; -let hmacInData = 'sm3TestIndata'; -let handle; - -async function testMac() { - /* Configure the parameters for generating the key. */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_SM3, - } - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_MAC, - } - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SM3, - } - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - } - let huksOptions = { - properties:properties, - inData:new Uint8Array(new Array()) - } - - /* Generate a key. */ - await publicGenKeyFunc(srcKeyAlias, huksOptions); - - /* Modify the parameter set for init() and perform the mac operation. */ - huksOptions.properties.splice(3, 3); - await publicInitFunc(srcKeyAlias, huksOptions); - huksOptions.inData = StringToUint8Array(hmacInData); - await publicUpdateFunc(handle, huksOptions); - huksOptions.inData = new Uint8Array(new Array()); - await publicFinishFunc(handle, huksOptions); - - huksOptions.properties.splice(1, 0, { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256, - }); - await publicDeleteKeyFunc(srcKeyAlias, huksOptions); + }); + } catch (error) { + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testMac') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testMac(); - }) - } - .width('100%') - .height('100%') - } +async function TestGenKeyForFingerprintAccessControl() { + await publicGenKeyFunc(keyAlias, huksOptions); } ``` -### AttestID - -After an application generates an asymmetric key, the certificate chain can be obtained through ID attestation. ID attestation supports the following device: brand, device, product, serial number, IMEI, MEID, manufacturer, model, SOC ID, and UDID. - -The application can also obtain the certificate chain through key attestation. - -ID attestation and key attestation are available only for devices in a trusted execution Environment (TEE). - -The development procedure is as follows: - -1. Generate a certificate. -2. Obtain certificate information. - -**Supported key types**: - -RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, X25519 - -> **NOTE**
-> -> The key alias cannot exceed 64 bytes. - -Before you get started, understand the following variables: - -| Parameter | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| -| options | HuksOptions | Yes | Parameters and data required for obtaining the certificate. | - -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). - -**Example** +2. Initialize the key session to obtain a challenge, and initiate fingerprint authentication to obtain an authentication token. ```ts -/* The following is an example of ID attestation. */ import huks from '@ohos.security.huks'; +import userIAM_userAuth from '@ohos.userIAM.userAuth'; -function StringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let handle; +let challenge; +let fingerAuthToken; +let authType = userIAM_userAuth.UserAuthType.FINGERPRINT; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +/* Configure the key generation parameter set and key encryption parameter set. */ +let properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT, +} +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +let huksOptions = { + properties: properties, + inData: new Uint8Array(new Array()) } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); +function initSession(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise { + return new Promise((resolve, reject) => { try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); + huks.initSession(keyAlias, huksOptions, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + throwObject.isThrow = true; + throw(error); } + }); } -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); +async function publicInitFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback doInit`); + let throwObject = {isThrow: false}; + try { + await initSession(keyAlias, huksOptions, throwObject) + .then ((data) => { + console.info(`callback: doInit success, data = ${JSON.stringify(data)}`); + handle = data.handle; + challenge = data.challenge; + }) + .catch((error) => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doInit failed, code: ${error.code}, msg: ${error.message}`); } + }); + } catch (error) { + console.error(`callback: doInit input arg invalid, code: ${error.code}, msg: ${error.message}`); + } +} + +function userIAMAuthFinger(huksChallenge:Uint8Array) { + // Obtain an authentication object. + let auth; + try { + auth = userIAM_userAuth.getAuthInstance(huksChallenge, 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) => { + /* The authentication is successful, and the authentication token is obtained. */ + fingerAuthToken = result.token; + } }); + 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); + } +} + +async function testInitAndAuthFinger() { + /* Initialize the key session to obtain a challenge. */ + await publicInitFunc(srcKeyAlias, huksOptions); + /* Invoke userIAM to perform user identity authentication. */ + userIAMAuthFinger(challenge); } +``` -async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback attestKeyItem`); - try { - await attestKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } +3. Pass in the authentication token to perform data operations. +```ts +/* + * The following uses an SM4 128-bit key and callback-based APIs as an example. + */ +import huks from '@ohos.security.huks'; + +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let srcKeyAlias = 'sm4_key_fingerprint_access'; +let IV = '1234567890123456'; +let cipherInData = 'Hks_SM4_Cipher_Test_101010101010101010110_string'; +let handle; +let fingerAuthToken; +let updateResult = new Array(); +let finishOutData; + +/* Configure the key generation parameter set and key encryption parameter set. */ +let propertiesEncrypt = new Array(); +propertiesEncrypt[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_SM4, +} +propertiesEncrypt[1] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT, +} +propertiesEncrypt[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_SM4_KEY_SIZE_128, +} +propertiesEncrypt[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE, +} +propertiesEncrypt[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_CBC, +} +propertiesEncrypt[5] = { + tag: huks.HuksTag.HUKS_TAG_IV, + value: StringToUint8Array(IV), +} +let encryptOptions = { + properties: propertiesEncrypt, + inData: new Uint8Array(new Array()) } -function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise{ - return new Promise((resolve, reject) => { - try { - huks.attestKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +function StringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +function updateSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { try { - await deleteKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); + huks.updateSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); + } + }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicUpdateFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doUpdate`); + let throwObject = {isThrow: false}; + try { + await updateSession(handle, huksOptions, token, throwObject) + .then ((data) => { + console.info(`callback: doUpdate success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doUpdate failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doUpdate input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); +function finishSession(handle:number, huksOptions:huks.HuksOptions, token:Uint8Array, throwObject) : Promise { + return new Promise((resolve, reject) => { + try { + huks.finishSession(handle, huksOptions, token, function (error, data) { + if (error) { + reject(error); + } else { + resolve(data); } - }); + }); + } catch (error) { + throwObject.isThrow = true; + throw(error); + } + }); +} + +async function publicFinishFunc(handle:number, token:Uint8Array, huksOptions:huks.HuksOptions) { + console.info(`enter callback doFinish`); + let throwObject = {isThrow: false}; + try { + await finishSession(handle, huksOptions, token, throwObject) + .then ((data) => { + finishOutData = data.outData; + console.info(`callback: doFinish success, data = ${JSON.stringify(data)}`); + }) + .catch(error => { + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: doFinish failed, code: ${error.code}, msg: ${error.message}`); + } + }); + } catch (error) { + console.error(`callback: doFinish input arg invalid, code: ${error.code}, msg: ${error.message}`); + } } -let securityLevel = StringToUint8Array('sec_level'); -let challenge = StringToUint8Array('challenge_data'); -let versionInfo = StringToUint8Array('version_info'); -let udid = StringToUint8Array('udid'); -let serial = StringToUint8Array('serial'); -let deviceId = StringToUint8Array('device_id'); -let idAliasString = "id attest"; - -async function testAttestId() { - let aliasString = idAliasString; - let aliasUint8 = StringToUint8Array(aliasString); - - /* Configure parameters and generate a key. */ - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; - await publicGenKeyFunc(aliasString, options); - - /* Configure the certificate parameter set. */ - let attestProperties = new Array(); - attestProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - attestProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - attestProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - attestProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - attestProperties[4] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_UDID, - value: udid - }; - attestProperties[5] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SERIAL, - value: serial - }; - attestProperties[6] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_DEVICE, - value: deviceId - }; - let huksOptions = { - properties: attestProperties - }; - - await publicAttestKey(aliasString, huksOptions); - - await publicDeleteKeyFunc(aliasString, options); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAttestId') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAttestId(); - }) - } - .width('100%') - .height('100%') - } +async function testSm4Cipher() { + encryptOptions.inData = StringToUint8Array(cipherInData); + /* Pass in the authentication token. */ + await publicUpdateFunc(handle, fingerAuthToken, encryptOptions); + encryptUpdateResult = updateResult; + + encryptOptions.inData = new Uint8Array(new Array()); + /* Pass in the authentication token. */ + await publicFinishFunc(handle, fingerAuthToken, encryptOptions); + if (finishOutData === cipherInData) { + console.info('test finish encrypt err '); + } else { + console.info('test finish encrypt success'); + } } ``` -### AttestKey - -After an application generates an asymmetric key, the certificate chain can be obtained by key attestation. You can also use ID attestation to obtain the certificate chain. The public certificate contains information such as the device ID. - -ID attestation and key attestation are available only for devices in a trusted execution Environment (TEE). - -The development procedure is as follows: +## Key Attestation -1. Generate a certificate. -2. Obtain certificate information. +The HUKS provides attestation for the public keys of asymmetric key pairs. The HUKS can issue a certificate for the public key of an asymmetric key pair stored in the HUKS using the public key infrastructure (PKI) certificate chain technology. The certificate can prove the validity of the public key. The service can use the root CA certificate provided by the OpenHarmony to verify the key certificate issued by the HUKS level by level to ensure that the public key and private key in the certificate are from a trusted hardware device and stored in the HUKS. -**Supported key types**: +**How to Develop** +1. Pass in the key alias and the attribute tag of the key to be attested. +2. Call a HUKS API to generate an X.509 certificate chain, which consists of the root CA certificate, device CA certificate, device certificate, and key certificate in sequence, for the application. +3. Send the certificate chain to a trusted server. The server parses and verifies the validity of the certificate chain and whether a single certificate is revoked. -RSA512, RSA768, RSA1024, RSA2048, RSA3072, RSA4096, ECC224, ECC256, ECC384, ECC521, X25519 +**Available APIs** -> **NOTE**
-> -> The key alias cannot exceed 64 bytes. +**Table 7** APIs for key attestation +| API | Description | +| -------------------------------------- | ----------------------------| +|attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void| Attests a key.| -Before you get started, understand the following variables: +**How to Develop** -| Parameter | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------------ | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key.| -| options | HuksOptions | Yes | Parameters and data required for obtaining the certificate. | +```ts +/* + * Attest a key and return the result in a callback. + */ +import huks from '@ohos.security.huks'; -For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). +/* + * Determine the key alias and encapsulate the key attribute set. + */ +let keyAliasString = "key attest"; +let aliasString = keyAliasString; +let aliasUint8 = StringToUint8Array(keyAliasString); +let securityLevel = StringToUint8Array('sec_level'); +let challenge = StringToUint8Array('challenge_data'); +let versionInfo = StringToUint8Array('version_info'); +let attestCertChain; -**Example** +let genKeyProperties = new Array(); +genKeyProperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA +}; +genKeyProperties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT +}; +genKeyProperties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 +}; +genKeyProperties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +genKeyProperties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 +}; +genKeyProperties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS +}; +genKeyProperties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT +}; +genKeyProperties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +let genOptions = { + properties: genKeyProperties +}; -```ts -/* The following is an example of AttestKey. */ -import huks from '@ohos.security.huks'; +let attestKeyproperties = new Array(); +attestKeyproperties[0] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, + value: securityLevel +}; +attestKeyproperties[1] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, + value: challenge +}; +attestKeyproperties[2] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, + value: versionInfo +}; +attestKeyproperties[3] = { + tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, + value: aliasUint8 +}; +let huksOptions = { + properties: attestKeyproperties +}; function StringToUint8Array(str) { let arr = []; @@ -3477,22 +2601,7 @@ function StringToUint8Array(str) { return new Uint8Array(arr); } -async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback generateKeyItem`); - try { - await generateKeyItem(keyAlias, huksOptions) - .then((data) => { - console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); - }) - .catch(error => { - console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); - }); - } catch (error) { - console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); - } -} - -function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { +function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) { return new Promise((resolve, reject) => { try { huks.generateKeyItem(keyAlias, huksOptions, function (error, data) { @@ -3503,27 +2612,33 @@ function generateKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback attestKeyItem`); +async function publicGenKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback generateKeyItem`); + let throwObject = {isThrow: false}; try { - await attestKeyItem(keyAlias, huksOptions) - .then ((data) => { - console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`); + await generateKeyItem(keyAlias, huksOptions, throwObject) + .then((data) => { + console.info(`callback: generateKeyItem success, data = ${JSON.stringify(data)}`); }) .catch(error => { - console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: generateKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: generateKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise{ +function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions, throwObject) : Promise{ return new Promise((resolve, reject) => { try { huks.attestKeyItem(keyAlias, huksOptions, function (error, data) { @@ -3534,136 +2649,49 @@ function attestKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) : Promise< } }); } catch (error) { + throwObject.isThrow = true; throw(error); } }); } -async function publicDeleteKeyFunc(keyAlias:string, huksOptions:huks.HuksOptions) { - console.info(`enter callback deleteKeyItem`); +async function publicAttestKey(keyAlias:string, huksOptions:huks.HuksOptions) { + console.info(`enter callback attestKeyItem`); + let throwObject = {isThrow: false}; try { - await deleteKeyItem(keyAlias, huksOptions) + await attestKeyItem(keyAlias, huksOptions, throwObject) .then ((data) => { - console.info(`callback: deleteKeyItem key success, data = ${JSON.stringify(data)}`); + console.info(`callback: attestKeyItem success, data = ${JSON.stringify(data)}`); + if (data !== null && data.certChains !== null) { + attestCertChain = data.certChains; + } }) .catch(error => { - console.error(`callback: deleteKeyItem failed, code: ${error.code}, msg: ${error.message}`); + if (throwObject.isThrow) { + throw(error); + } else { + console.error(`callback: attestKeyItem failed, code: ${error.code}, msg: ${error.message}`); + } }); } catch (error) { - console.error(`callback: deleteKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); + console.error(`callback: attestKeyItem input arg invalid, code: ${error.code}, msg: ${error.message}`); } } -function deleteKeyItem(keyAlias:string, huksOptions:huks.HuksOptions) { - return new Promise((resolve, reject) => { - try { - huks.deleteKeyItem(keyAlias, huksOptions, function (error, data) { - if (error) { - reject(error); - } else { - resolve(data); - } - }); - } catch (error) { - throw(error); - } - }); +async function AttestKeyTest() { + await publicGenKeyFunc(aliasString, genOptions); + + await publicAttestKey(aliasString, huksOptions); + console.info('attest certChain data: ' + attestCertChain) } +``` -let securityLevel = StringToUint8Array('sec_level'); -let challenge = StringToUint8Array('challenge_data'); -let versionInfo = StringToUint8Array('version_info'); -let keyAliasString = "key attest"; +## FAQs -async function testAttestKey() { - let aliasString = keyAliasString; - let aliasUint8 = StringToUint8Array(aliasString); - - let properties = new Array(); - properties[0] = { - tag: huks.HuksTag.HUKS_TAG_ALGORITHM, - value: huks.HuksKeyAlg.HUKS_ALG_RSA - }; - properties[1] = { - tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, - value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT - }; - properties[2] = { - tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, - value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 - }; - properties[3] = { - tag: huks.HuksTag.HUKS_TAG_PURPOSE, - value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY - }; - properties[4] = { - tag: huks.HuksTag.HUKS_TAG_DIGEST, - value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 - }; - properties[5] = { - tag: huks.HuksTag.HUKS_TAG_PADDING, - value: huks.HuksKeyPadding.HUKS_PADDING_PSS - }; - properties[6] = { - tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, - value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT - }; - properties[7] = { - tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, - value: huks.HuksCipherMode.HUKS_MODE_ECB - }; - let options = { - properties: properties - }; - await publicGenKeyFunc(aliasString, options); - - /* Configure the certificate parameter set. */ - let attestProperties = new Array(); - attestProperties[0] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO, - value: securityLevel - }; - attestProperties[1] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE, - value: challenge - }; - attestProperties[2] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO, - value: versionInfo - }; - attestProperties[3] = { - tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS, - value: aliasUint8 - }; - let huksOptions = { - properties: attestProperties - }; +### Cannot find name 'huks'. - await publicAttestKey(aliasString, huksOptions); +**security.huks.d.ts** is not imported. To solve the problem, add **import huks from '@ohos.security.huks'**. - await publicDeleteKeyFunc(aliasString, options); -} - -@Entry -@Component -struct Index { - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button() { - Text('testAttestKey') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .backgroundColor('#0D9FFB') - .onClick(()=>{ - testAttestKey(); - }) - } - .width('100%') - .height('100%') - } -} -``` +### Property 'finishSession' does not exist on type 'typeof huks'. Did you mean 'finish'? + +**finishSession()** is supported from API version 9. Update the SDK version or use the latest **security.huks.d.ts** file. \ No newline at end of file diff --git a/en/application-dev/security/huks-overview.md b/en/application-dev/security/huks-overview.md index b9b0b7a8530e41b40d1ed8d8c1eacb5ab451a7ad..18a1a076bf7d33aa9f5178b9f9edded37cfc862b 100644 --- a/en/application-dev/security/huks-overview.md +++ b/en/application-dev/security/huks-overview.md @@ -2,26 +2,72 @@ ## Introduction -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. +OpenHarmony Universal KeyStore (HUKS) provides lifecycle key management capabilities, including key generation, storage, use, and destruction, and provides attestation for the keys stored in the HUKS. +The HUKS provides secure, lifecycle management of keys based on system security capabilities for services. With the HUKS, services do not need to implement key management. + + +The HUKS provides the following functions: + +- [Key Generation](huks-guidelines.md#key-generation) +- [Key Import](huks-guidelines.md#key-import) +- [Common Key Operations](huks-guidelines.md#common-key-operations) +- [Key Access Control](huks-guidelines.md#key-access-control) +- [Key Attestation](huks-guidelines.md#key-attestation) +- [Supported Algorithm Types and Parameter Combinations](huks-appendix.md#supported-algorithm-types-and-parameter-combinations) +- [Key Material Formats](huks-appendix.md#key-material-formats) + ## Basic Concepts -- HUKS provides key management functions, including encryption and decryption, signing and signature verification, key agreement and derivation, and Hash-based Message Authentication Code (HMAC) calculation. -- HUKS supports the following algorithms: AES and RSA in encryption and decryption, RSA, ECC, DSA, and ED25519 in signing and signature verification, PBKDF2 in key derivation, and DH, ECDH, and X25519 in key agreement. -- HUKS uses the OpenSSL and Mbed TLS algorithm libraries. +Before using the HUKS for development, you are advised to understand the following basic concepts: + +- HUKS Core + + HUKS Core is a core component that implements functions, including cryptographic calculation of keys, encryption and decryption of plaintext keys, and key access control. Generally, it runs in a secure environment (such as the TEE or security chip) of the device to ensure that the keys in plaintext are always in the HUKS Core. + +- Key session + + A key session holds information about the key operation date, key information, and access control attributes when a key is used. You need to pass in a key alias to create a session for the key. The HUKS generates a globally unique handle for each session. A general key operation involves creating a session, passing in data and parameters, and finalizing the session (or aborting the session). + ## Working Principles -HUKS manages keys through the following APIs in an Init-Update-Finish model: -- **InitSession**: reads the key, creates a session ID, and returns the session ID to the caller. +The security design of the HUKS includes the following: +- Always keep keys in a secure environment. -- **UpdateSession**: updates data by segment based on the session ID obtained by **InitSession()**. + In the lifecycle of a key, the plaintext will never be exposed outside the HUKS Core. For the devices with a Trusted Execution Environment (TEE) or secure chipset, the HUKS Core runs in the TEE or secure chipset. This prevents the key plaintext from being disclosed even if the Rich Execution Environment (REE) is cracked. +- Encrypt keys for storage. -- **FinishSession**: processes all the data transferred to HUKS and then releases resources. + The service keys are encrypted based on the device root key. Some keys can be protected by passwords if the devices support this feature. +- Apply strict access control over keys. -> **NOTICE**
-> **AbortSession()** must be called to terminate the use of the key when an error occurs in any of **InitSession()**, **UpdateSession()**, and **FinishSession()**. + Only authorized services can access keys. For security-sensitive services, user identity authentication can be enabled for key access. +- Provide key attestation. + + The HUKS provides attestation for hardware-backed key storage. It proves that the key has not been tampered with, is stored in the hardware-backed HUKS Core, and has correct key attributes. + + +A key session is the basis for key operations in the HUKS. It initializes key information and caches the service data. Cryptographic operations on data and encryption and decryption are performed in the HUKS Core for security purposes. + +**Figure 1** HUKS working mechanism + +![huks_architect](figures/huks_architect.png) ## Constraints -N/A + + - Alias-based access + + The key material stored in the HUKS can be accessed by alias only. The key alias must be unique for an application. Otherwise, the key with the same alias will be replaced. The length of the key alias cannot exceed 64 bytes. + + - Data segment size + + All data is transmitted to the HUKS through the IPC channel. Due to the limitation of the IPC buffer size, data greater than 100 KB must be sliced before transmission, and the data segment cannot exceed 100 KB. + + - Mandatory parameters + + The cipher algorithm, key size, and purpose must be specified when a key is generated or imported. Other parameters (such as the working mode, padding mode, and hash algorithm) are optional. When a key is used, all parameters related to the cipher algorithm must be specified. + + - Key material format + + When a key (key pair, public key, or private key) is imported or exported, the key material must be in the format required by the HUKS. For details, see [Key Material Formats](huks-appendix.md#key-material-format). diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 7f84d9cd058732ee490428034d90338bfaf7ea9c..ff90272d78f26b485b9e916e4ae91ac2ffd724c2 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1,165 +1,1625 @@ -# 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 the Ability Form. + +**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 the 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 attributes for the 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 an application 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.ENTERPRISE_RESET_DEVICE + +Allows the device administrator to restore factory settings of the device. + +**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 + +Allows 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 + +## ohos.permission.ACCESS_SCREEN_LOCK_INNER + +Allows an application to call the system API of the lock screen service. + +**Permission level**: system_core + +**Authorization mode**: system_grant + +**Enable ACL**: FALSE diff --git a/en/application-dev/security/permission-verify-guidelines.md b/en/application-dev/security/permission-verify-guidelines.md index cca11b49b4f02be2631b354adf47c83d4d57e2c1..e1726db925256093c4f56badf362f8bbfedf7c82 100644 --- a/en/application-dev/security/permission-verify-guidelines.md +++ b/en/application-dev/security/permission-verify-guidelines.md @@ -1,12 +1,12 @@ -# Permission Verification Guide +# API Access Permission Verification ## When to Use -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. +To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [Application Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. ## Available APIs -The table below lists only the API used in this guide. For more information, see [AbilityContext](../reference/apis/js-apis-ability-context.md). +The table below lists only the API used for access permission verification. For more information, see [AbilityContext](../reference/apis/js-apis-ability-context.md). | API | Description | | ------------------------------------------------------------ | --------------------------------------------------- | @@ -18,8 +18,11 @@ The table below lists only the API used in this guide. For more information, see The procedure is as follows: 1. Obtain the caller's identity (**tokenId**). + > **NOTE** + > + > You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md#getcallingtokenid8). 2. Determine the permission to verify, which is **ohos.permission.PERMISSION** in this example. -3. Call **verifyAccessToken()** to perform a permission verification of the caller. +3. Call **verifyAccessToken()** to perform a permission verification for the caller. 4. Proceed based on the permission verification result. ```js @@ -42,5 +45,3 @@ The procedure is as follows: } ``` -> **NOTE**
-> You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md#getcallingtokenid8). 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..d700e52854b7b58baf17d4d566468b1a0cd1688b 100644 --- a/en/application-dev/security/userauth-overview.md +++ b/en/application-dev/security/userauth-overview.md @@ -1,25 +1,26 @@ # User Authentication Overview -OpenHarmony provides biometric recognition that can be used for identity authentication in device unlocking, application login, and payment. +## UserAuth Module -OpenHarmony provides both 2D and 3D facial recognition. You can provide either or both of them on your device based on the hardware and technology applied on the device. 3D facial recognition is superior to 2D facial recognition in terms of recognition rate and anti-counterfeiting capability. However, you can use 3D facial recognition only if your device supports capabilities such as 3D structured light and 3D Time of Flight \(TOF\). +The **UserAuth** module provides user authentication capabilities. You can use the APIs provided by this module to authenticate users in scenarios, such as device unlocking, payment, and application logins. + +Currently, user authentication comes with facial recognition and fingerprint recognition capabilities. The specific capabilities supported by a device vary depending on the hardware and technology implementation. ## Basic Concepts -Biometric recognition \(also known as biometric authentication\) uses optical, acoustical, and biological sensors, as well as the biological statistics mechanism to identify individuals. +- Facial recognition is a biometric recognition technology that identifies individuals based on their facial characteristics. A camera is used to collect images or video streams that contain human faces, and automatically detect, track, and recognize the human faces. -Facial recognition is a biometric recognition technology that identifies individuals based on facial characteristics. A camera is used to collect images or video streams that contain human faces, and automatically detect, track, and recognize the human faces. +- Fingerprint recognition is a biometric recognition technology that identifies individuals based on fingerprint ridge patterns. When the user places their finger against the fingerprint sensor, the sensor captures the fingerprint image of the user, and transmits it to the fingerprint recognition module for processing, which then compares the fingerprint image with the fingerprint information pre-registered by the user to identify the user identity. ## Working Principles -Facial recognition establishes a secure channel between a camera and a trusted execution environment \(TEE\). Through this channel, face image data is transmitted to the TEE. This protects against any attack from the rich execution environment \(REE\) as the face image data cannot be obtained from the REE. The face image collection, characteristic extraction, alive human body detection, and characteristic comparison are all completed in the TEE. The TEE implements security isolation based on the trust zone. The external face framework only initiates face authentication and processes authentication results. It does not process the human face data. - -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. +During facial or fingerprint recognition, the feature collecting device transmits the collected biometrics information to the Trusted Execution Environment (TEE) directly through a secure channel. This security mechanism prevents malware from attacking the Rich Execution Environment (REE). Processing of the biometrics information, from alive human body detection to characteristic extraction, storage, and comparison, is all done in the TEE, where security isolation is implemented based on the trust zone. The service framework that provides APIs only deals with authentication requests and authentication results. It does not process the biometrics information. -## Limitations and Constraints +Biometrics information is stored in trust zones in a TEE, which uses strong cryptographic algorithms to encrypt and protect the integrity of the information. The collected and stored biometrics information will not be transferred out of the TEE without user authorization. That is, no application can obtain the biometrics information or send it to any external storage medium without user authorization. -- 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. -- The device must have a TEE, where encrypted facial characteristics are stored. -- Facial recognition may not work for people with similar looks and children whose facial features keep changing. If you are concerned about this, consider using other authentication modes. +## Constraints +- Only facial and fingerprint recognition is currently available and can only be executed on a local device. Moreover, no authentication UI is provided. +- To implement user authentication, a device must have a component for collecting the biometrics information, and the face image must be greater than 100 x 100 pixels. +- The device must have a TEE, where encrypted biometrics information is stored. +- Facial recognition may not work for people with similar looks and children whose facial characteristics keep changing. If you are concerned about this, consider using other authentication modes. 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