diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability-deprecated/Readme-EN.md similarity index 88% rename from en/application-dev/ability/Readme-EN.md rename to en/application-dev/ability-deprecated/Readme-EN.md index 6a11f497d375874b96bfed77a77dce033821d6e3..5c803a47558bbd52765090debe162dbecd996ae6 100644 --- a/en/application-dev/ability/Readme-EN.md +++ b/en/application-dev/ability-deprecated/Readme-EN.md @@ -1,5 +1,8 @@ # Ability Development +> **NOTE**
+> This folder is deprecated. Read [Application Models](../application-models/Readme-EN.md) instead. + - [Ability Framework Overview](ability-brief.md) - [Context Usage](context-userguide.md) - FA Model diff --git a/en/application-dev/ability/ability-assistant-guidelines.md b/en/application-dev/ability-deprecated/ability-assistant-guidelines.md similarity index 90% rename from en/application-dev/ability/ability-assistant-guidelines.md rename to en/application-dev/ability-deprecated/ability-assistant-guidelines.md index 4d7b0edb2b91ca07123ad7495f4d64fc2f525e1d..d2e45f5d5492c23bcce0ec48674427df2cb2b765 100644 --- a/en/application-dev/ability/ability-assistant-guidelines.md +++ b/en/application-dev/ability-deprecated/ability-assistant-guidelines.md @@ -73,10 +73,10 @@ The ability assistant enables you to start applications, atomic services, and te | -a/--all | - | Prints ability information in all missions. | | -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.
The following values are available for **type**:
- NORMAL
- DEFAULT_STANDARD
- DEFAULT_SINGLE
- LAUNCHER | | -e/--extension | elementName | Prints extended component information. | - | -u/--userId | UserId | Prints 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 | - | Prints Data ability information. | - | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | - | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters.
Example commands: **aa dump -a -c** and **aa dump -i 21 -c**. | + | -u/--userId | UserId | Prints 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 | - | Prints Data ability information. | + | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | + | -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters.
Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| **Method** diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability-deprecated/ability-brief.md similarity index 100% rename from en/application-dev/ability/ability-brief.md rename to en/application-dev/ability-deprecated/ability-brief.md diff --git a/en/application-dev/ability/ability-delegator.md b/en/application-dev/ability-deprecated/ability-delegator.md similarity index 96% rename from en/application-dev/ability/ability-delegator.md rename to en/application-dev/ability-deprecated/ability-delegator.md index 5fd0293efde6d6d264be28b6c30123e7697bee6b..b32d472176a5b6270fece94ae4bd8ae9a7bd73fa 100644 --- a/en/application-dev/ability/ability-delegator.md +++ b/en/application-dev/ability-deprecated/ability-delegator.md @@ -46,19 +46,19 @@ For details about how to use DevEco Studio to start the test framework, see [Ope ## Introduction to TestRunner -**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). +**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-application-testRunner.md). ## Introduction to AbilityDelegatorRegistry -**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-abilityDelegatorRegistry.md). +**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-application-abilityDelegatorRegistry.md). ## Introduction to AbilityDelegatorArgs -**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-application-abilityDelegatorArgs.md). +**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-inner-application-abilityDelegatorArgs.md). ## Introduction to AbilityMonitor -**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-application-abilityMonitor.md). +**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-inner-application-abilityMonitor.md). **Example** @@ -131,7 +131,7 @@ abilityDelegator.startAbility(want, (err, data) => { ### Scheduling the Ability Lifecycle -**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-application-abilityDelegator.md). +**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-inner-application-abilityDelegator.md). ### Running a Shell Command diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability-deprecated/context-userguide.md similarity index 94% rename from en/application-dev/ability/context-userguide.md rename to en/application-dev/ability-deprecated/context-userguide.md index 17fd6b5eb780f656ada33e94a6d1584ebbc55e5c..ac65d92cb9422d040ff16cab1640cd1f9bed5d5c 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability-deprecated/context-userguide.md @@ -4,12 +4,12 @@ **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. - -- 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. + 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 + +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 The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). @@ -239,7 +239,7 @@ export default class MainAbility extends Ability { ### application/FormExtensionContext -For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). +For details, see [FormExtensionContext](../reference/apis/js-apis-inner-application-formExtensionContext.md). ### Obtaining the Context on an ArkTS Page diff --git a/en/application-dev/ability/continuationmanager.md b/en/application-dev/ability-deprecated/continuationmanager.md similarity index 99% rename from en/application-dev/ability/continuationmanager.md rename to en/application-dev/ability-deprecated/continuationmanager.md index 20c272e75a16c2bcf14d567c1cbc7afa28a3a69a..0ba79f95acf165d604d8f854832703d7fc4af3f8 100644 --- a/en/application-dev/ability/continuationmanager.md +++ b/en/application-dev/ability-deprecated/continuationmanager.md @@ -188,7 +188,7 @@ As the entry of the ability continuation capability, **continuationManager** is } ``` - The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md). + The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](fa-pageability.md). You can also instruct the device selection module to update the device connection state. The sample code is as follows: diff --git a/en/application-dev/ability/fa-brief.md b/en/application-dev/ability-deprecated/fa-brief.md similarity index 96% rename from en/application-dev/ability/fa-brief.md rename to en/application-dev/ability-deprecated/fa-brief.md index 3788fe994f9f984449c28bdb6f15ff96adb29c21..5ad79cfe259f1fb9cf865b9d6f496c0f31c47ae0 100644 --- a/en/application-dev/ability/fa-brief.md +++ b/en/application-dev/ability-deprecated/fa-brief.md @@ -38,4 +38,6 @@ When an ability is started, an application process as well as a thread for this For details about the project directory structure of the FA model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section4154183910141). -For details about how to configure the application package structure of the FA model, see [Application Package Structure Configuration File](../quick-start/package-structure.md). +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/fa-dataability.md b/en/application-dev/ability-deprecated/fa-dataability.md similarity index 99% rename from en/application-dev/ability/fa-dataability.md rename to en/application-dev/ability-deprecated/fa-dataability.md index e3fd895c2a3530aa0f8aa85919657a62f3f72c06..8d94e8f225a3966d676e6c7631968c25f5634531 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability-deprecated/fa-dataability.md @@ -148,7 +148,7 @@ The basic dependency packages include: 1. Create a Data ability helper. - For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md). + For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-inner-ability-dataAbilityHelper.md). ```js // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). import featureAbility from '@ohos.ability.featureAbility' diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability-deprecated/fa-formability.md similarity index 99% rename from en/application-dev/ability/fa-formability.md rename to en/application-dev/ability-deprecated/fa-formability.md index 377d5e4b8faeda387f4eda5a6506d103c3d76395..a91ca4b9baf98f32bad7ea081024d74949baf726 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability-deprecated/fa-formability.md @@ -43,7 +43,7 @@ The table below describes the **LifecycleForm** APIs, which represent the lifecy | onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed. | | onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget. | -The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-formprovider.md). +The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). **Table 2** FormProvider APIs diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability-deprecated/fa-pageability.md similarity index 99% rename from en/application-dev/ability/fa-pageability.md rename to en/application-dev/ability-deprecated/fa-pageability.md index f6eb70595322d3f3308c00afcc9a5907ff87054f..2f4741b80ef771c9b478d32a7713b597fb65c2d4 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability-deprecated/fa-pageability.md @@ -61,7 +61,7 @@ By default, **singleton** is used. | API | Description | | --------------------------------------------------- | --------------- | -| void startAbility(parameter: StartAbilityParameter) | Starts an ability. | +| void startAbility(parameter: StartAbilityParameter) | Starts an ability. | | Context getContext(): | Obtains the application context.| | void terminateSelf() | Terminates the ability. | | bool hasWindowFocus() | Checks whether the ability has focus. | diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability-deprecated/fa-serviceability.md similarity index 99% rename from en/application-dev/ability/fa-serviceability.md rename to en/application-dev/ability-deprecated/fa-serviceability.md index 3cd2620cfdde502f879e1321e782f2d872e0a77d..cf766f35f72c76eb738d3b168d39cbcba0f21da3 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability-deprecated/fa-serviceability.md @@ -22,7 +22,9 @@ The differences between **onCommand()** and **onConnect()** are as follows: ### Creating and Registering a Service Ability -1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. +1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests. + + ```ts export default { @@ -45,7 +47,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**. diff --git a/en/application-dev/ability/figures/AbilityComponentInstanceMission.png b/en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png similarity index 100% rename from en/application-dev/ability/figures/AbilityComponentInstanceMission.png rename to en/application-dev/ability-deprecated/figures/AbilityComponentInstanceMission.png diff --git a/en/application-dev/ability/figures/ExtensionAbility.png b/en/application-dev/ability-deprecated/figures/ExtensionAbility.png similarity index 100% rename from en/application-dev/ability/figures/ExtensionAbility.png rename to en/application-dev/ability-deprecated/figures/ExtensionAbility.png diff --git a/en/application-dev/ability/figures/aa-dump-a.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-a.PNG similarity index 100% rename from en/application-dev/ability/figures/aa-dump-a.PNG rename to en/application-dev/ability-deprecated/figures/aa-dump-a.PNG diff --git a/en/application-dev/ability/figures/aa-dump-i.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-i.PNG similarity index 100% rename from en/application-dev/ability/figures/aa-dump-i.PNG rename to en/application-dev/ability-deprecated/figures/aa-dump-i.PNG diff --git a/en/application-dev/ability/figures/aa-dump-l.PNG b/en/application-dev/ability-deprecated/figures/aa-dump-l.PNG similarity index 100% rename from en/application-dev/ability/figures/aa-dump-l.PNG rename to en/application-dev/ability-deprecated/figures/aa-dump-l.PNG diff --git a/en/application-dev/ability/figures/contextIntroduction.png b/en/application-dev/ability-deprecated/figures/contextIntroduction.png similarity index 100% rename from en/application-dev/ability/figures/contextIntroduction.png rename to en/application-dev/ability-deprecated/figures/contextIntroduction.png diff --git a/en/application-dev/ability/figures/continuation-info.png b/en/application-dev/ability-deprecated/figures/continuation-info.png similarity index 100% rename from en/application-dev/ability/figures/continuation-info.png rename to en/application-dev/ability-deprecated/figures/continuation-info.png diff --git a/en/application-dev/ability/figures/continuationManager.png b/en/application-dev/ability-deprecated/figures/continuationManager.png similarity index 100% rename from en/application-dev/ability/figures/continuationManager.png rename to en/application-dev/ability-deprecated/figures/continuationManager.png diff --git a/en/application-dev/ability/figures/fa-dataability-uri.png b/en/application-dev/ability-deprecated/figures/fa-dataability-uri.png similarity index 100% rename from en/application-dev/ability/figures/fa-dataability-uri.png rename to en/application-dev/ability-deprecated/figures/fa-dataability-uri.png diff --git a/en/application-dev/ability/figures/fa-form-example.png b/en/application-dev/ability-deprecated/figures/fa-form-example.png similarity index 100% rename from en/application-dev/ability/figures/fa-form-example.png rename to en/application-dev/ability-deprecated/figures/fa-form-example.png diff --git a/en/application-dev/ability/figures/fa-pageAbility-lifecycle.png b/en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png similarity index 100% rename from en/application-dev/ability/figures/fa-pageAbility-lifecycle.png rename to en/application-dev/ability-deprecated/figures/fa-pageAbility-lifecycle.png diff --git a/en/application-dev/ability/figures/fa-threading-model.png b/en/application-dev/ability-deprecated/figures/fa-threading-model.png similarity index 100% rename from en/application-dev/ability/figures/fa-threading-model.png rename to en/application-dev/ability-deprecated/figures/fa-threading-model.png diff --git a/en/application-dev/ability/figures/favsstage.png b/en/application-dev/ability-deprecated/figures/favsstage.png similarity index 100% rename from en/application-dev/ability/figures/favsstage.png rename to en/application-dev/ability-deprecated/figures/favsstage.png diff --git a/en/application-dev/ability/figures/lifecycle.png b/en/application-dev/ability-deprecated/figures/lifecycle.png similarity index 100% rename from en/application-dev/ability/figures/lifecycle.png rename to en/application-dev/ability-deprecated/figures/lifecycle.png diff --git a/en/application-dev/ability/figures/page-ability-lifecycle.png b/en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png similarity index 100% rename from en/application-dev/ability/figures/page-ability-lifecycle.png rename to en/application-dev/ability-deprecated/figures/page-ability-lifecycle.png diff --git a/en/application-dev/ability/figures/stage-call.png b/en/application-dev/ability-deprecated/figures/stage-call.png similarity index 100% rename from en/application-dev/ability/figures/stage-call.png rename to en/application-dev/ability-deprecated/figures/stage-call.png diff --git a/en/application-dev/ability/figures/stageabilitylifecyclecallback.png b/en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png similarity index 100% rename from en/application-dev/ability/figures/stageabilitylifecyclecallback.png rename to en/application-dev/ability-deprecated/figures/stageabilitylifecyclecallback.png diff --git a/en/application-dev/ability/figures/stageconcept.png b/en/application-dev/ability-deprecated/figures/stageconcept.png similarity index 100% rename from en/application-dev/ability/figures/stageconcept.png rename to en/application-dev/ability-deprecated/figures/stageconcept.png diff --git a/en/application-dev/ability/figures/stagedesign.png b/en/application-dev/ability-deprecated/figures/stagedesign.png similarity index 100% rename from en/application-dev/ability/figures/stagedesign.png rename to en/application-dev/ability-deprecated/figures/stagedesign.png diff --git a/en/application-dev/ability/figures/stageprocessmodel.png b/en/application-dev/ability-deprecated/figures/stageprocessmodel.png similarity index 100% rename from en/application-dev/ability/figures/stageprocessmodel.png rename to en/application-dev/ability-deprecated/figures/stageprocessmodel.png diff --git a/en/application-dev/ability/public_sys-resources/icon-caution.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-caution.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-caution.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-danger.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-danger.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-danger.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-note.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-note.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-note.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-notice.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-notice.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-notice.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-tip.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-tip.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-tip.gif diff --git a/en/application-dev/ability/public_sys-resources/icon-warning.gif b/en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif similarity index 100% rename from en/application-dev/ability/public_sys-resources/icon-warning.gif rename to en/application-dev/ability-deprecated/public_sys-resources/icon-warning.gif diff --git a/en/application-dev/ability/stage-ability-continuation.md b/en/application-dev/ability-deprecated/stage-ability-continuation.md similarity index 98% rename from en/application-dev/ability/stage-ability-continuation.md rename to en/application-dev/ability-deprecated/stage-ability-continuation.md index 701b730a833a7b97f00398746cddae4d2856a248..7a11716f18f2c8b866e1fd11722ae0e07a32d4ce 100644 --- a/en/application-dev/ability/stage-ability-continuation.md +++ b/en/application-dev/ability-deprecated/stage-ability-continuation.md @@ -301,11 +301,13 @@ In the ability continuation scenario, the distributed data object is used to syn ### Restrictions -1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). +1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/module-configuration-file.md). 2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system. ### 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. +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/stage-ability.md b/en/application-dev/ability-deprecated/stage-ability.md similarity index 98% rename from en/application-dev/ability/stage-ability.md rename to en/application-dev/ability-deprecated/stage-ability.md index d09585b25531556cfbee2ab5cbd45c72191aa8a4..97ba5cff5cc083563f1d0f78c7b499bff2cd2050 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability-deprecated/stage-ability.md @@ -1,6 +1,6 @@ # Ability Development ## When to Use -Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: +Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the **module.json5** and **app.json5** files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/application-package-structure-stage.md). To develop an ability based on the stage model, implement the following logic: - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Call abilities. For details, see [Call Development](stage-call.md). @@ -30,7 +30,7 @@ By default, the singleton mode is used. The following is an example of the **mod ``` ## Creating an Ability ### Available APIs -The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). +The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md). **Table 1** AbilityStage APIs |API|Description| @@ -321,3 +321,5 @@ struct Index { } } ``` + + \ No newline at end of file diff --git a/en/application-dev/ability/stage-brief.md b/en/application-dev/ability-deprecated/stage-brief.md similarity index 85% rename from en/application-dev/ability/stage-brief.md rename to en/application-dev/ability-deprecated/stage-brief.md index 2cf186f82db342e02523ee4645521ea72fbd1f6f..2d5474e2c2f0e8328add287481b5ea47abcb2725 100644 --- a/en/application-dev/ability/stage-brief.md +++ b/en/application-dev/ability-deprecated/stage-brief.md @@ -12,15 +12,15 @@ The stage model is designed based on the following considerations: - Efficient management of application processes - As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience. +As the device memory becomes larger, the number of processes concurrently running in the system increases. If the number of concurrent processes reaches several hundreds, the overall power consumption and performance of the system will be adversely affected without effective management measures. To restrict the behavior of background processes, the stage model uses four measures: transient task, continuous task, agent task, and Work Scheduler task. With these measures, foreground processes will obtain guaranteed resources, thereby delivering a better user experience. - Native support for cross-device migration and multi-device collaboration - OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. +OpenHarmony is a native distributed OS. Its application framework must be designed for easier component migration and collaboration across devices. The stage model achieves this design objective by providing features such as separation between ability and UI as well as integration of UI display and service capabilities. - Different window forms for various device types - The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types. +The stage model redefines the ability lifecycle. In terms of architecture, the component manager and window manager are decoupled. This facilitates adaptation between window forms and device types. ## Basic Concepts @@ -103,8 +103,12 @@ The processes of an application can be classified into three types: ![stageprocessmodel](figures/stageprocessmodel.png) + + ## Application Package Structure For details about the project directory structure of the stage model, see [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section56487581904). -For details about how to configure the application package structure of the stage model, see [Application Package Structure Configuration File (Stage Model)](../quick-start/stage-structure.md). +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/stage-call.md b/en/application-dev/ability-deprecated/stage-call.md similarity index 99% rename from en/application-dev/ability/stage-call.md rename to en/application-dev/ability-deprecated/stage-call.md index 5c29001e5c62f4059121247e9a044474111527c3..e447dc4fd89f99948ebb379de7010c4db9486488 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability-deprecated/stage-call.md @@ -34,7 +34,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-service-extension-context.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](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.| |call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability.| diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability-deprecated/stage-formextension.md similarity index 98% rename from en/application-dev/ability/stage-formextension.md rename to en/application-dev/ability-deprecated/stage-formextension.md index fa90f267c13c0fa002233f585ca7c6b3c9904637..c45b33732a4f902391eb153c9f5304b071bc4f34 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability-deprecated/stage-formextension.md @@ -31,7 +31,7 @@ Stage widget development refers to the development conducted by the widget provi ## Available APIs -The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-formextension.md). +The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-app-form-formExtensionAbility.md). **Table 1** FormExtension APIs @@ -45,7 +45,7 @@ The **FormExtension** class has the following APIs. For details, see [FormExtens | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (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-formextensioncontext.md). +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). **Table 2** FormExtensionContext APIs @@ -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 about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). +For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md). **Table 3** FormProvider APIs @@ -412,4 +412,4 @@ The following is an example: } } } - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/ability/stage-serviceextension.md b/en/application-dev/ability-deprecated/stage-serviceextension.md similarity index 99% rename from en/application-dev/ability/stage-serviceextension.md rename to en/application-dev/ability-deprecated/stage-serviceextension.md index 0d634ebe67ef9e332f658a0efb0f7ffdb0e1f2b7..98cae5914f7afa34c916c53f6bb423b590cf5070 100644 --- a/en/application-dev/ability/stage-serviceextension.md +++ b/en/application-dev/ability-deprecated/stage-serviceextension.md @@ -71,4 +71,5 @@ OpenHarmony does not support creation of a Service Extension ability for third-p console.log('onDestroy'); } } - ``` \ No newline at end of file + ``` + diff --git a/en/application-dev/ability/wantagent.md b/en/application-dev/ability-deprecated/wantagent.md similarity index 99% rename from en/application-dev/ability/wantagent.md rename to en/application-dev/ability-deprecated/wantagent.md index 5a85bab15b8422aaabb0a173ad888126e08fc038..4b1854d1a54a36f864b3dd4215040eb24db2e5f3 100644 --- a/en/application-dev/ability/wantagent.md +++ b/en/application-dev/ability-deprecated/wantagent.md @@ -2,8 +2,6 @@ ## 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. - - ## Available APIs | API | Description| | ---------------------------------------------------------------------------------------------- | ----------- | diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..a9473b7f6c2d0fb75e160cafdd1fb94b43633fa7 --- /dev/null +++ b/en/application-dev/application-models/Readme-EN.md @@ -0,0 +1,2 @@ +# Application Models + diff --git a/en/application-dev/faqs/faqs-connectivity.md b/en/application-dev/faqs/faqs-connectivity.md index e3b02269e2de947fb4ab4069f1d7ba4812825ddc..31e1db2e15e82875427d52a92dd26bcfeb69c34e 100644 --- a/en/application-dev/faqs/faqs-connectivity.md +++ b/en/application-dev/faqs/faqs-connectivity.md @@ -21,7 +21,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. -Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) +Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) ## What does error code 6 mean for the response of \@ohos.net.http.d.ts? @@ -30,4 +30,4 @@ Applicable to: OpenHarmony SDK 3.2.3.5 Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible. -Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) +Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) diff --git a/en/application-dev/faqs/faqs-dfx.md b/en/application-dev/faqs/faqs-dfx.md index 6ab2948af18a4344fb8decc157e4ac1cb346f3ee..ec1c8dbfedd5fa3c087c96d54c9c2aab73d75e8a 100644 --- a/en/application-dev/faqs/faqs-dfx.md +++ b/en/application-dev/faqs/faqs-dfx.md @@ -19,7 +19,7 @@ Run **hdc\_std shell param get persist.ace.testmode.enabled**. If the value is **0**, run the **hdc\_std shell param set persist.ace.testmode.enabled 1** to enable the test mode. -## Why Is Private Displayed in Logs When the Format Parameter Type of hilog in C++ Code Is %d or %s? +## Why is private displayed in logs when the format parameter type of HiLog in C++ code is %d or %s? When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**. @@ -35,7 +35,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5 You are advised to use the [HiLog](../reference/apis/js-apis-hilog.md) for log printing. For details about how to set the **domain** parameter, see the [Development Guide](../reference/apis/js-apis-hilog.md#hilogisloggable). -## What is the maximum length of a log record when HiLog Is used? Is it configurable? +## What is the maximum length of a log record when HiLog is used? Is it configurable? Applicable to: OpenHarmony SDK 3.2.2.5 diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md index 47ede475575484d60317e9ed7e2afe586fb12524..420d09121f86b7a4612c2e7ad6fe5f29831be80b 100644 --- a/en/application-dev/napi/mindspore-lite-guidelines.md +++ b/en/application-dev/napi/mindspore-lite-guidelines.md @@ -24,7 +24,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API | ------------------ | ----------------- | |OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| -| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.| |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 3d7947be85a49718f2288d7c2d776853d7451bc9..76d12ed38f81bdf496fd228f9cbea11eb8422510 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -203,15 +203,16 @@ - [@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) - - data/rdb/[resultSet](js-apis-data-resultset.md) + - [@ohos.data.ValuesBucket](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.userfile_manager](js-apis-userfilemanager.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) @@ -240,10 +241,13 @@ - [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.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) - - tag/[nfctech](js-apis-nfctech.md) - - tag/[tagSession](js-apis-tagSession.md) + - tag + - [nfctech](js-apis-nfctech.md) + - [tagSession](js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.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 new file mode 100644 index 0000000000000000000000000000000000000000..34d4df8dd99bb528ae79d8d13de74f491f75f3db --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -0,0 +1,46 @@ +# @ohos.accessibility.GesturePath + + The **GesturePath** module provides APIs for creating gesture path information required for an accessibility application to 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. + +## Modules to Import + +```ts +import GesturePath from '@ohos.accessibility.GesturePath'; +``` + +## GesturePath + +Defines a gesture path. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ------------ | ---------------------------------------- | ---- | ---- | ------ | +| points | Array<[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)> | Yes | Yes | Gesture touch point. | +| durationTime | number | Yes | Yes | Total gesture duration, in milliseconds.| + +### constructor + +constructor(durationTime: number); + +Constructor used to create a **GesturePath** object. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| durationTime | number | Yes| Total gesture duration, in milliseconds.| + +**Example** + +```ts +let gesturePath = new GesturePath.GesturePath(20); +``` diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md new file mode 100644 index 0000000000000000000000000000000000000000..5792c44cd9fc89cf495e943a4e40463ce89281c4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -0,0 +1,47 @@ +# @ohos.accessibility.GesturePoint + + The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to 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. + +## Modules to Import + +```ts +import GesturePoint from '@ohos.accessibility.GesturePoint'; +``` + +## GesturePoint + +Defines a gesture touch point. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +### Attributes + +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| positionX | number | Yes | Yes | X coordinate of the touch point.| +| positionY | number | Yes | Yes | Y coordinate of the touch point.| + +### constructor + +constructor(positionX: number, positionY: number); + +Constructor used to create a **GesturePoint** object. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| positionX | number | Yes| X coordinate of the touch point.| +| positionY | number | Yes | Y coordinate of the touch point.| + +**Example** + +```ts +let gesturePoint = new GesturePoint.GesturePoint(1, 2); +``` 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 c33230f7181ce92a50cee6c1417eb5d71a124f68..33b6f586279309125be085e8a28d5423b271fae3 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -1,17 +1,16 @@ -# System Accessibility Configuration +# @ohos.accessibility.config -The **config** module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. +The System Accessibility Configuration module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. > **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 -```typescript -import config from "@ohos.accessibility.config"; +```ts +import config from '@ohos.accessibility.config'; ``` ## Attributes @@ -22,20 +21,20 @@ import config from "@ohos.accessibility.config"; | -------- | -------- | -------- | -------- | -------- | | highContrastText | [Config](#config)\| Yes| Yes| Whether to enable high-contrast text.| | invertColor | [Config](#config)\| Yes| Yes| Whether to enable color inversion.| -| daltonizationColorFilter | [Config](#config)\<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Daltonization filter. | +| daltonizationColorFilter | [Config](#config)<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Configuration of the daltonization filter.| | contentTimeout | [Config](#config)\| Yes| Yes| Recommended duration for content display. The value ranges from 0 to 5000, in milliseconds.| -| animationOff | [Config](#config)\| Yes| Yes| Whether to enable animation.| +| animationOff | [Config](#config)\| Yes| Yes| Whether to disable animation.| | brightnessDiscount | [Config](#config)\| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| | mouseKey | [Config](#config)\| Yes| Yes| Whether to enable the mouse button feature.| -| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for the automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| +| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| | shortkey | [Config](#config)\| Yes| Yes| Whether to enable the accessibility extension shortcut key.| -| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is bundleName/abilityName.| +| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is 'bundleName/abilityName'.| | captions | [Config](#config)\| Yes| Yes| Whether to enable captions.| -| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](./js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| +| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>): Promise<void>; +enableAbility(name: string, capability: Array<accessibility.Capability>): Promise<void>; Enables an accessibility extension ability. This API uses a promise to return the result. @@ -45,29 +44,44 @@ Enables an accessibility extension ability. This API uses a promise to return th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>) | Yes| Capability of the accessibility extension ability.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **Example** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve']) - .then(() => { - console.info('enable succeed'); - }).catch((error) => { - console.error('enable failed'); - }); - ``` +```ts +import accessibility from '@ohos.accessibility'; +let name = 'com.ohos.example/axExtension'; +let capability : accessibility.Capability[] = ['retrieve']; +try { + config.enableAbility(name, capability).then(() => { + console.info('enable ability succeed'); + }).catch((err) => { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>, callback: AsyncCallback<void>): void; +enableAbility(name: string, capability: Array<accessibility.Capability>, callback: AsyncCallback<void>): void; Enables an accessibility extension ability. This API uses an asynchronous callback to return the result. @@ -77,21 +91,37 @@ Enables an accessibility extension ability. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **Example** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve'], (err, data) => { - if (err) { - console.error('enable failed'); - return; - } - console.info('enable succeed'); - }) - ``` +```ts +import accessibility from '@ohos.accessibility'; +let name = 'com.ohos.example/axExtension'; +let capability : accessibility.Capability[] = ['retrieve']; +try { + config.enableAbility(name, capability, (err) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('enable ability succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility @@ -105,24 +135,36 @@ Disables an accessibility extension ability. This API uses a promise to return t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **Example** - ```typescript - config.disableAbility("com.ohos.example/axExtension") - .then(() => { - console.info('disable succeed'); - }).catch((error) => { - console.error('disable failed'); - }); - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name).then(() => { + console.info('disable ability succeed'); + }).catch((err) => { + console.error('failed to disable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to disable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility @@ -136,26 +178,39 @@ Disables an accessibility extension ability. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **Example** - ```typescript - config.disableAbility("com.ohos.example/axExtension", (err, data) => { - if (err) { - console.error('disable failed'); - return; - } - console.info('disable succeed'); - }) - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name, (err, data) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('disable succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` -## on('enableAbilityListsStateChanged') +## on('enabledAccessibilityExtensionListChange') -on(type: 'enableAbilityListsStateChanged', callback: Callback<void>): void; +on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void>): void; -Adds a listener for changes in the list of enabled accessibility extension abilities. +Adds a listener for changes in the list of enabled accessibility extension abilities. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -163,22 +218,27 @@ Adds a listener for changes in the list of enabled accessibility extension abili | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | +| type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| | callback | Callback<void> | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.on('enableAbilityListsStateChanged',() => { - console.info('ax extension ability enable list changed'); - }); - ``` +```ts +try { + config.on('enabledAccessibilityExtensionListChange', () => { + console.info('subscribe enabled accessibility extension list change state success'); + }); +} catch (exception) { + console.error('failed to subscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` -## off('enableAbilityListsStateChanged') +## off('enabledAccessibilityExtensionListChange') -off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): void; +off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void>): void; -Cancels the listener for changes in the list of enabled accessibility extension abilities. +Cancels the listener for changes in the list of enabled accessibility extension abilities. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -186,14 +246,21 @@ Cancels the listener for changes in the list of enabled accessibility extension | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | +| type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| | callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.off('enableAbilityListsStateChanged'); - ``` +```ts +try { + config.off('enabledAccessibilityExtensionListChange', () => { + console.info('Unsubscribe enabled accessibility extension list change state success'); + }); +} catch (exception) { + console.error('failed to Unsubscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` ## Config @@ -203,7 +270,7 @@ Implements configuration, acquisition, and listening for attributes. set(value: T): Promise<void>; -Sets this attribute. This API uses a promise to return the result. +Sets the attribute value. This API uses a promise to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -217,24 +284,28 @@ Sets this attribute. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| **Example** - ```typescript - config.highContrastText.set(true) - .then(() => { - console.info('highContrastText set succeed'); - }).catch((error) => { - console.error('highContrastText set failed'); - }); - ``` +```ts +let value = true; +try { + config.highContrastText.set(value).then(() => { + console.info('set highContrastText succeed'); + }).catch((err) => { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### set set(value: T, callback: AsyncCallback<void>): void; -Sets this attribute. This API uses an asynchronous callback to return the result. +Sets the attribute value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -243,25 +314,30 @@ Sets this attribute. This API uses an asynchronous callback to return the result | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Attribute value to set.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```typescript - config.highContrastText.set(true, (err, data) => { - if (err) { - console.error('highContrastText set failed'); - return; - } - console.info('highContrastText set succeed'); - }) - ``` +```ts +let value = true; +try { + config.highContrastText.set(value, (err, data) => { + if (err) { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + return; + } + console.info('set highContrastText succeed'); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### get get(): Promise<T>; -Obtains the value of this attribute. This API uses a promise to return the result. +Obtains the attribute value. This API uses a promise to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -269,24 +345,25 @@ Obtains the value of this attribute. This API uses a promise to return the resul | Type| Description| | -------- | -------- | -| Promise<T> | Promise used to return the attribute value.| +| Promise<T> | Promise used to return the value obtained.| **Example** - ```typescript - config.highContrastText.get() - .then((value) => { - console.info('highContrastText get succeed'); - }).catch((error) => { - console.error('highContrastText get failed'); - }); - ``` +```ts +let value; +config.highContrastText.get().then((data) => { + value = data; + console.info('get highContrastText success'); +}).catch((err) => { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); +}); +``` ### get get(callback: AsyncCallback<T>): void; -Obtains the value of this attribute. This API uses an asynchronous callback to return the result. +Obtains the attribute value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -294,25 +371,27 @@ Obtains the value of this attribute. This API uses an asynchronous callback to r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the attribute value.| +| callback | AsyncCallback<T> | Yes| Callback used to return the attribute value.| **Example** - ```typescript - config.highContrastText.get((err, data) => { - if (err) { - console.error('highContrastText get failed'); - return; - } - console.info('highContrastText get succeed'); - }) - ``` +```ts +let value; +config.highContrastText.get((err, data) => { + if (err) { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); + return; + } + value = data; + console.info('get highContrastText success'); +}); +``` ### on on(callback: Callback<T>): void; -Adds a listener for attribute changes. +Adds a listener for attribute changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -324,17 +403,21 @@ Adds a listener for attribute changes. **Example** - ```typescript - config.highContrastText.on(() => { - console.info('highContrastText changed'); - }); - ``` +```ts +try { + config.highContrastText.on((data) => { + console.info('subscribe highContrastText success, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed subscribe highContrastText, because ' + JSON.stringify(exception)); +} +``` ### off off(callback?: Callback<T>): void; -Cancels the listener for attribute changes. +Cancels the listener for attribute changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -342,13 +425,15 @@ Cancels the listener for attribute changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | Callback<T> | No| Callback invoked when the attribute changes.| +| callback | Callback<T> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.highContrastText.off(); - ``` +```ts +config.highContrastText.off((data) => { + console.info('Unsubscribe highContrastText success, result: ' + JSON.stringify(data)); +}); +``` ## DaltonizationColorFilter diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index 6d318b4ade570aea27b58ca93d37ef0a3992d3bc..cf4443c60f4b58a17986bdb7ae5160fd6a95347c 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 @@ -# Accessibility +# @ohos.accessibility The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration. @@ -8,7 +8,7 @@ The **Accessibility** module implements the accessibility functions, including o ## Modules to Import -```typescript +```ts import accessibility from '@ohos.accessibility'; ``` @@ -49,7 +49,7 @@ Provides information about an accessibility application. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| id | number | Yes| No| Ability ID.| +| id | string | Yes| No| Ability ID.| | name | string | Yes| No| Ability name.| | bundleName | string | Yes| No| Bundle name.| | targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.| @@ -85,7 +85,7 @@ Describes the target action supported by an accessibility application. ## Capability -Enumerates the capabilities of an auxiliary application. +Enumerates the capabilities of an accessibility application. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -145,7 +145,7 @@ Describes the style of captions. ## CaptionsManager8+ -Implements configuration management for captions. +Implements configuration management for captions. Before calling any API of **CaptionsManager**, you must use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **CaptionsManager** instance. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing @@ -156,87 +156,113 @@ Implements configuration management for captions. | enabled | boolean | Yes| No| Whether to enable captions configuration.| | style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.| -In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **captionsManager** instance, and then call the methods using the obtained instance. - ### on('enableChange') on(type: 'enableChange', callback: Callback<boolean>): void; -Enables listening for the enabled status changes of captions configuration. +Enables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| -- **Example** +**Example** - ```typescript - captionsManager.on('enableChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('enableChange', (data) => { + console.info('subscribe caption manager enable state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### on('styleChange') on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; -Enables listening for captions style changes. +Enables listening for captions style changes. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| -- **Example** +**Example** + +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('styleChange', (data) => { + captionStyle = data; + console.info('subscribe caption manager style state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` - ```typescript - captionsManager.on('styleChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` - ### off('enableChange') off(type: 'enableChange', callback?: Callback<boolean>): void; -Disables listening for the enabled status changes of captions configuration. +Disables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| -- **Example** +**Example** - ```typescript - captionsManager.off('enableChange') - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('enableChange', (data) => { + console.info('Unsubscribe caption manager enable state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### off('styleChange') off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; -Disables listening for captions style changes. +Disables listening for captions style changes. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| -- **Example** +**Example** - ```typescript - captionsManager.off('styleChange') - ``` +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('styleChange', (data) => { + captionStyle = data; + console.info('Unsubscribe caption manager style state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` ## EventInfo @@ -271,16 +297,20 @@ Implements a constructor. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | jsonObject | string | Yes| JSON string required for creating an object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| jsonObject | string | Yes| JSON string required for creating an object.| -- **Example** +**Example** - ```typescript - let eventInfo = new accessibility.EventInfo({"type":"click","bundleName":"com.example.MyApplication","triggerAction":"click"}) + ```ts + let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' + }); ``` ## EventType @@ -331,153 +361,319 @@ Enumerates window update types. | active | Window activity change.| | focus | Window focus change.| -## accessibility.getAbilityLists +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> Obtains the accessibility application list. 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[getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9). + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| - | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| - -- **Return value** - - | Type| Description| - | -------- | -------- | - | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| - -- **Example** - - ```typescript - accessibility.getAbilityLists("spoken", "enable") - .then((data) => { - console.info('success data:getAbilityList1 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.abilityTypes); - console.info(item.eventTypes); - console.info(item.capabilities); - console.info(item.packageName); - console.info(item.filterBundleNames); - console.info(item.bundleName); - } - }).catch((error) => { - console.error('failed to getAbilityList1 because ' + JSON.stringify(error)); - }) - ``` +**Parameters** -## accessibility.getAbilityLists +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| + +**Example** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void Obtains the accessibility application list. 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 [getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9-1). + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| - | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| - | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| - -- **Example** - - ```typescript - accessibility.getAbilityLists("visual", "enable", (err, data) => { - if (err) { - console.error('failed to getAbilityList2 because ' + JSON.stringify(err)); - return; - } - console.info('success data:getAbilityList2 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.abilityTypes); - console.info(item.eventTypes); - console.info(item.capabilities); - console.info(item.packageName); - console.info(item.filterBundleNames); - console.info(item.bundleName); - } - }) - ``` +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| + +**Example** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + abilityList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> + +Obtains the accessibility application list. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| + +**Example** + +```ts +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void + +Obtains the accessibility application list. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| + +**Example** + +```ts +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` ## accessibility.getCaptionsManager8+ getCaptionsManager(): CaptionsManager -Obtains the captions configuration. +Obtains a **CaptionsManager** instance. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | [CaptionsManager](#captionsmanager8) | Captions configuration.| +| Type| Description| +| -------- | -------- | +| [CaptionsManager](#captionsmanager8) | Captions configuration.| -- **Example** +**Example** - ```typescript - captionsManager = accessibility.getCaptionsManager() - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +``` -## accessibility.on('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('accessibilityStateChange') -on(type: 'accessibilityStateChange' | 'touchGuideStateChange', callback: Callback<boolean>): void +on(type: 'accessibilityStateChange', callback: Callback<boolean>): void -Enables listening for the enabled status changes of the accessibility application or touch guide mode. +Enables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for the enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for the enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback\ | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback used to return the result.| -- **Example** +**Example** - ```typescript - accessibility.on('accessibilityStateChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +try { + accessibility.on('accessibilityStateChange', (data) => { + console.info('subscribe accessibility state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(exception)); +} +``` -## accessibility.off('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('touchGuideStateChange') -off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void +on(type: 'touchGuideStateChange', callback: Callback<boolean>): void -Disables listening for the enabled status changes of the accessibility application or touch guide mode. +Enables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for the enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for the enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback<boolean> | No| Callback invoked when the enabled status changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback used to return the result.| -- **Example** +**Example** - ```typescript - accessibility.off('accessibilityStateChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +try { + accessibility.on('touchGuideStateChange', (data) => { + console.info('subscribe touch guide state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(exception)); +} +``` + +## accessibility.off('accessibilityStateChange') + +off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void + +Disables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. + + + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | No| Callback used to return the result.| + +**Example** + +```ts +try { + accessibility.off('accessibilityStateChange', (data) => { + console.info('Unsubscribe accessibility state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe accessibility state change, because ' + JSON.stringify(exception)); +} +``` + +## accessibility.off('touchGuideStateChange') + +off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void + +Disables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. + + + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | No| Callback used to return the result.| + +**Example** + +```ts +try { + accessibility.off('touchGuideStateChange', (data) => { + console.info('Unsubscribe touch guide state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe touch guide state change, because ' + JSON.stringify(exception)); +} +``` ## accessibility.isOpenAccessibility @@ -487,22 +683,21 @@ Checks whether accessibility is enabled. This API uses a promise to return the r **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenAccessibility() - .then((data) => { - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(error)); - }) - ``` +```ts +accessibility.isOpenAccessibility().then((data) => { + console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) +}).catch((err) => { + console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); +}); +``` ## accessibility.isOpenAccessibility @@ -512,23 +707,23 @@ Checks whether accessibility is enabled. This API uses an asynchronous callback **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenAccessibility((err, data) => { - if (err) { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); - return; - } - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }) - ``` +```ts +accessibility.isOpenAccessibility((err, data) => { + if (err) { + console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); + return; + } + console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) +}); +``` ## accessibility.isOpenTouchGuide @@ -538,22 +733,21 @@ Checks whether touch guide mode is enabled. This API uses a promise to return th **System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenTouchGuide() - .then((data) => { - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(error)); - }) - ``` +```ts +accessibility.isOpenTouchGuide().then((data) => { + console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) +}).catch((err) => { + console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); +}); +``` ## accessibility.isOpenTouchGuide @@ -563,78 +757,172 @@ Checks whether touch guide mode is enabled. This API uses an asynchronous callba **System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenTouchGuide((err, data) => { - if (err) { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); - return; - } - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }) - ``` +```ts +accessibility.isOpenTouchGuide((err, data) => { + if (err) { + console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); + return; + } + console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) +}); +``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo): Promise<void> Sends an accessibility event. This API uses a promise to return the result. -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -- **Parameters** +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. +> You are advised to use **[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9)**. - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +**System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| -- **Example** +**Return value** - ```typescript - accessibility.sendEvent(this.eventInfo) - .then((data) => { - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to sendEvent because ' + JSON.stringify(error)); - }) - ``` +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +accessibility.sendEvent(eventInfo).then(() => { + console.info('send event success'); +}).catch((err) => { + console.error('failed to sendEvent because ' + JSON.stringify(err)); +}); +``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo, callback: AsyncCallback<void>): void Sends an accessibility event. 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 **[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9-1)**. + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to sendEvent because ' + JSON.stringify(err)); + return; + } + console.info('sendEvent success'); +}); +``` - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| +## accessibility.sendAccessibilityEvent9+ -- **Example** +sendAccessibilityEvent(event: EventInfo): Promise<void> - ```typescript - accessibility.sendEvent(this.eventInfo,(err, data) => { - if (err) { - console.error('failed to sendEvent because ' + JSON.stringify(err)); - return; - } - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }) - ``` +Sends an accessibility event. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendAccessibilityEvent(eventInfo).then(() => { + console.info('send event success'); + }).catch((err) => { + console.error('failed to send event because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` + +## accessibility.sendAccessibilityEvent9+ + +sendAccessibilityEvent(event: EventInfo, callback: AsyncCallback<void>): void + +Sends an accessibility event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to send event because ' + JSON.stringify(err)); + return; + } + console.info('send event success'); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 5814fad2cff1b347469cc49c6a51196e9beb1e80..0d2aef3e25aa21eb724c8f74f977d901ea12b290 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 @@ -# App Account Management +# @ohos.account.appAccount The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. @@ -3173,7 +3173,7 @@ Set credentials for an app account. This API uses an asynchronous callback to re | Name | Type | Mandatory | Description | | -------------- | ------------------------- | ---- | ------------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete. | +| credentialType | string | Yes | Type of the credential to set. | | credential | string | Yes | Credential value. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| @@ -3203,7 +3203,7 @@ Set credentials for an app account. This API uses a promise to return the result | Name | Type | Mandatory | Description | | -------------- | ------ | ---- | ---------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete.| +| credentialType | string | Yes | Type of the credential to set.| | credential | string | Yes | Credential value.| **Return value** @@ -3576,7 +3576,7 @@ Obtains the credential of an app account. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | -------------- | --------------------------- | ---- | -------------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete.| +| credentialType | string | Yes | Type of the credential to obtain.| | callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| **Example** @@ -3606,7 +3606,7 @@ Obtains the credential of an app account. This API uses a promise to return the | Name | Type | Mandatory | Description | | -------------- | ------ | ---- | ---------- | | name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to delete.| +| credentialType | string | Yes | Type of the credential to obtain.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md index a78f8cc320a4d081f356145d8ed4c51907a025ba..a47e3e8908f69f5515beab95cea6f74351719a77 100644 --- a/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-accessibilityExtensionAbility.md @@ -1,12 +1,10 @@ -# Accessibility Extension Ability +# @ohos.application.AccessibilityExtensionAbility -The **AccessibilityExtensionAbility** module is based on the ExtensionAbility framework and provides the **AccessibilityExtensionAbility**. +The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework. ->**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. -> ->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. ## Modules to Import @@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Type | Readable | Writable | Description | +| Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------------------- | -| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. | +| context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes| No| Context of the accessibility extension ability.| ## AccessibilityEvent @@ -32,36 +30,10 @@ Defines an accessibility event. | Name | Type | Readable | Writable | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------- | -| eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | +| eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | | target | AccessibilityElement | Yes | No | Target component where the event occurs.| | timeStamp | number | Yes | No | Timestamp of the event. | -## GesturePath - -Defines a gesture path. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -### Attributes - -| Name | Type | Readable | Writable | Description | -| ------------ | ---------------------------------------- | ---- | ---- | ------ | -| points | Array<[GesturePoint](gesturepoint)> | Yes | Yes | An array of gesture touch points. | -| durationTime | number | Yes | Yes | Total time consumed by the gesture.| - -## GesturePoint - -Defines a gesture touch point. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -### Attributes - -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ------- | -| positionX | number | Yes | Yes | X-coordinate of the touch point.| -| positionY | number | Yes | Yes | Y-coordinate of the touch point.| - ## GestureType Enumerates gesture types. @@ -89,7 +61,7 @@ Enumerates gesture types. ## PageUpdateType -Enumerates the page refresh types. +Enumerates the page update types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -106,27 +78,25 @@ Enumerates the touch guide event types. | Name | Description | | ---------- | ------------ | -| touchBegin | A touch starts in touch guide mode.| -| touchEnd | A touch ends in touch guide mode.| +| touchBegin | Start of touch in touch guide mode. | +| touchEnd | End of touch in touch guide mode. | ## AccessibilityExtensionAbility.onConnect onConnect(): void; -Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can initialize service logic. This API can be overridden as required. +Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can have the service logic initialized. This API can be overridden as required. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - -None - **Example** ```ts -onConnect(): void { - console.log("AxExtensionAbility onConnect"); -} +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onConnect() { + console.log('AxExtensionAbility onConnect'); + } +}; ``` ## AccessibilityExtensionAbility.onDisconnect @@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - -None - **Example** ```ts -onDisconnect(): void { - console.log("AxExtensionAbility onDisconnect"); -} +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onDisconnect() { + console.log('AxExtensionAbility onDisconnect'); + } +}; ``` ## AccessibilityExtensionAbility.onAccessibilityEvent @@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In **Example** ```ts -onAccessibilityEvent(event: AccessibilityEvent): void { - console.log("AxExtensionAbility onAccessibilityEvent"); - if (event.eventType == 'click') { - console.log("AxExtensionAbility onAccessibilityEvent: click"); +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onAccessibilityEvent(event) { + console.log('AxExtensionAbility onAccessibilityEvent'); + if (event.eventType == 'click') { + console.log('AxExtensionAbility onAccessibilityEvent: click'); + } } -} +}; ``` ## AccessibilityExtensionAbility.onKeyEvent -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean; +onKeyEvent(keyEvent: KeyEvent): boolean; -Called when a physical key is pressed. In this API, you can determine whether to intercept the key event based on the service. +Called when a physical key is pressed. In this API, you can determine whether to intercept an event based on the service. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to **Example** ```ts -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { - console.log("AxExtensionAbility onKeyEvent"); - if (keyEvent.keyCode == 22) { - console.log("AxExtensionAbility onKeyEvent: intercept 22"); - return true; +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onKeyEvent(keyEvent) { + console.log('AxExtensionAbility onKeyEvent'); + if (keyEvent.keyCode == 22) { + console.log('AxExtensionAbility onKeyEvent: intercept 22'); + return true; + } + return false; } - return false; -} +}; ``` 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 2d7e9fab8a62e7d68dae92e66359a2704414bc01..197e25cfce48edc49798b438745adc13c35ab9d5 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 ->**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 Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. +> **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 @@ -13,67 +12,100 @@ The Battery Info module provides APIs for querying the charger type, battery hea import batteryInfo from '@ohos.batteryInfo'; ``` -## System Capabilities - -SystemCapability.PowerManager.BatteryManager - ## Attributes Describes battery information. -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ----------------------------------------- | -------- | -------- | ------------------------------------------------------------ | -| batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | -| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | -| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | -| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | -| voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | -| technology | string | Yes | No | Battery technology of the current device. | -| batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | -| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | - -**Example** - -```js -import batteryInfo from '@ohos.batteryInfo'; -var batterySoc = batteryInfo.batterySOC; -``` - +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------- | ---- | ---- | ---------------------| +| batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. | +| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. | +| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. | +| voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. | +| technology | string | Yes | No | Battery technology of the device. | +| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. | +| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | +| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. | +| estimatedRemainingChargeTime9+ | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. | +| totalEnergy9+ | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. | +| nowCurrent9+ | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. | +| remainingEnergy9+ | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.| ## BatteryPluggedType Enumerates charger types. -| Name | Default Value | Description | -| -------- | ------------- | ----------------- | -| NONE | 0 | Unknown type. | -| AC | 1 | AC charger. | -| USB | 2 | USB charger. | -| WIRELESS | 3 | Wireless charger. | +**System capability**: SystemCapability.PowerManager.BatteryManager.Core +| Name | Value | Description | +| -------- | ---- | ----------------- | +| NONE | 0 | Unknown type | +| AC | 1 | AC charger| +| USB | 2 | USB charger | +| WIRELESS | 3 | Wireless charger| ## BatteryChargeState Enumerates charging states. -| Name | Default Value | Description | -| ------- | ------------- | --------------------------------- | -| NONE | 0 | Unknown state. | -| ENABLE | 1 | The battery is being charged. | -| DISABLE | 2 | The battery is not being charged. | -| FULL | 3 | The battery is fully charged. | +**System capability**: SystemCapability.PowerManager.BatteryManager.Core +| Name | Value | Description | +| ------- | ---- | --------------- | +| NONE | 0 | Unknown state. | +| ENABLE | 1 | The battery is being charged. | +| DISABLE | 2 | The battery is not being charged. | +| FULL | 3 | The battery is fully charged.| ## BatteryHealthState Enumerates battery health states. -| Name | Default Value | Description | -| ----------- | ------------- | ------------------------------------ | -| UNKNOWN | 0 | Unknown state. | -| GOOD | 1 | The battery is in the healthy state. | -| OVERHEAT | 2 | The battery is overheated. | -| OVERVOLTAGE | 3 | The battery voltage is over high. | -| COLD | 4 | The battery temperature is low. | -| DEAD | 5 | The battery is dead. | - +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value | Description | +| ----------- | ---- | -------------- | +| UNKNOWN | 0 | Unknown state. | +| GOOD | 1 | The battery is in the healthy state. | +| OVERHEAT | 2 | The battery is overheated. | +| OVERVOLTAGE | 3 | The battery voltage is over high. | +| COLD | 4 | The battery temperature is low. | +| DEAD | 5 | The battery is dead.| + +## BatteryCapacityLevel9+ + +Enumerates battery levels. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value| Description | +| -------------- | ------ | ---------------------------- | +| LEVEL_NONE | 0 | Unknown battery level. | +| LEVEL_FULL | 1 | Full battery level. | +| LEVEL_HIGH | 2 | High battery level. | +| LEVEL_NORMAL | 3 | Normal battery level.| +| LEVEL_LOW | 4 | Low battery level. | +| LEVEL_CRITICAL | 5 | Ultra-low battery level.| + +## CommonEventBatteryChangedCode9+ + +Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value| Description | +| -------------------- | ------ | -------------------------------------------------- | +| EXTRA_SOC | 0 | Remaining battery level in percentage. | +| EXTRA_VOLTAGE | 1 | Battery voltage of the device. | +| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. | +| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. | +| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. | +| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. | +| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. | +| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. | +| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. | +| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.| +| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. | diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md new file mode 100644 index 0000000000000000000000000000000000000000..917bc81d2f3eecef3f25d609db686b0d9dae44a2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -0,0 +1,287 @@ +# Battery Statistics + +This module provides APIs for querying software and hardware power consumption statistics. + +> **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. + +## Modules to Import + +```js +import batteryStats from '@ohos.batteryStatistics'; +``` + +## batteryStats.getBatteryStats + +getBatteryStats(): Promise + +Obtains the power consumption information list, using a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Return value** + +| Type | Description | +| ----------------------------------------------------- | ------------------------------- | +| Promise> | Promise used to return the power consumption information list.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +batteryStats.getBatteryStats() +.then(data => { + console.info('battery statistics info: ' + data); +}) +.catch(err => { + console.error('get battery statisitics failed, err: ' + err); +}); +``` + +## batteryStats.getBatteryStats + +getBatteryStats(callback: AsyncCallback): void + +Obtains the power consumption information list. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +batteryStats.getBatteryStats((err, data) => { + if (typeof err === 'undefined') { + console.info('battery statistics info: ' + data); + } else { + console.error('get battery statisitics failed, err: ' + err); + } +}); +``` + +## batteryStats.getAppPowerValue + +getAppPowerValue(uid: number): number + +Obtains the power consumption of an application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------- | +| uid | number | Yes | Application UID.| + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| number | Power consumption of the application with this UID, in unit of mAh.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getAppPowerValue(10021); + console.info('battery statistics value of app is: ' + value); +} catch(err) { + console.error('get battery statisitics value of app failed, err: ' + err); +} +``` + +## batteryStats.getAppPowerPercent + +getAppPowerPercent(uid: number): number + +Obtains the proportion of the power consumption of an application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------- | +| uid | number | Yes | Application UID.| + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| number | Proportion of the power consumption of an application with this UID.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var percent = batteryStats.getAppPowerPercent(10021); + console.info('battery statistics percent of app is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of app failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerValue + +getHardwareUnitPowerValue(type: ConsumptionType): number + +Obtains the power consumption of a hardware unit according to the consumption type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------ | +| number | Power consumption of the hardware unit corresponding to the power consumption type, in unit of mAh.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerPercent + +getHardwareUnitPowerPercent(type: ConsumptionType): number + +Obtains the proportion of the power consumption of a hardware unit according to the power consumption type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------------- | +| number | Proportion of the power consumption of the hardware unit corresponding to the power consumption type.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## BatteryStatsInfo + +Describes the device power consumption information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +### Attributes + +| Name | Type | Readable| Writable| Description | +| ----- | ----------------------------------- | ---- | ---- | ---------------------- | +| uid | number | Yes | No | UID related to power consumption information. | +| type | [ConsumptionType](#consumptiontype) | Yes | No | Power consumption type. | +| power | number | Yes | No | Power consumption, in unit of mAh.| + +## ConsumptionType + +Enumerates power consumption types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +| Name | Value | Description | +| -------------------------- | ---- | ----------------------------- | +| CONSUMPTION_TYPE_INVALID | -17 | Unknown type. | +| CONSUMPTION_TYPE_APP | -16 | Power consumption of an application. | +| CONSUMPTION_TYPE_BLUETOOTH | -15 | Power consumption of Bluetooth. | +| CONSUMPTION_TYPE_IDLE | -14 | Power consumption when the CPU is idle.| +| CONSUMPTION_TYPE_PHONE | -13 | Power consumption of a phone call. | +| CONSUMPTION_TYPE_RADIO | -12 | Power consumption of wireless communication. | +| CONSUMPTION_TYPE_SCREEN | -11 | Power consumption of the screen. | +| CONSUMPTION_TYPE_USER | -10 | Power consumption of the user. | +| CONSUMPTION_TYPE_WIFI | -9 | Power consumption of Wi-Fi. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index b852a673ab6ca120497e1c40443d19990cfbd74b..aa9e1937cd66e83262211280f42f11f468e2d200 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,8 +1,9 @@ -# Bluetooth +# @ohos.bluetooth The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. -> **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. @@ -202,7 +203,7 @@ Obtains the connection state of a profile. | Name | Type | Mandatory | Description | | --------- | --------- | ---- | ------------------------------------- | -| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| +| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| **Return value** @@ -1280,10 +1281,6 @@ Obtains the connected devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - -No value is returned. - **Return value** | Type | Description | @@ -2695,8 +2692,6 @@ Obtains all services of the remote BLE device. This API uses a promise to return **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - **Return value** | Type | Description | @@ -2830,7 +2825,7 @@ Reads the descriptor contained in the specific characteristic of the remote BLE | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | -| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the descriptor read.| +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback invoked to return the descriptor read.| **Return value** @@ -3309,7 +3304,7 @@ Enumerates the scan modes. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ---- | --------------- | | SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | @@ -3324,7 +3319,7 @@ Enumerates the pairing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------ | ---- | ------ | | BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_BONDING | 1 | Pairing. | @@ -3350,7 +3345,7 @@ Enumerates the SPP link types. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------- | ---- | ------------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| @@ -3510,7 +3505,7 @@ Enumerates the profile connection states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ---- | -------------- | | STATE_DISCONNECTED | 0 | Disconnected. | | STATE_CONNECTING | 1 | Connecting.| @@ -3558,7 +3553,7 @@ Enumerates the scan duty options. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------ | | SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| | SCAN_MODE_BALANCED | 1 | Balanced mode. | @@ -3571,7 +3566,7 @@ Enumerates the hardware match modes of BLE scan filters. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ---------------------------------------- | | MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | @@ -3596,7 +3591,7 @@ Enumerates the Bluetooth states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------------ | | STATE_OFF | 0 | Bluetooth is turned off. | | STATE_TURNING_ON | 1 | Bluetooth is being turned on. | @@ -3641,7 +3636,7 @@ Defines the content of a BLE advertisement packet. | Name | Type | Readable | Writable | Description | | ---------------- | ------------------- | ---- | ---- | ------------------ | -| manufactureId | Array<string> | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| +| manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | @@ -3713,7 +3708,7 @@ Enumerates the major classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | MAJOR_MISC | 0x0000 | Miscellaneous device. | | MAJOR_COMPUTER | 0x0100 | Computer. | @@ -3734,7 +3729,7 @@ Enumerates the major and minor classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ------ | --------------- | | COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | | COMPUTER_DESKTOP | 0x0104 | Desktop computer. | @@ -3830,7 +3825,7 @@ Enumerates the A2DP playing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ------ | ------- | | STATE_NOT_PLAYING | 0x0000 | Not playing. | | STATE_PLAYING | 0x0001 | Playing.| @@ -3842,9 +3837,9 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | -------------------------------- | ------ | --------------- | -| PROFILE_A2DP_SOURCE | 0x0001 | A2DP profile.| -| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 0x0004 | HFP profile. | -| PROFILE_HID_HOST9+ | 0x0006 | Human Interface Device (HID) profile. | -| PROFILE_PAN_NETWORK9+ | 0x0007 | PAN profile. | +| PROFILE_A2DP_SOURCE | 1 | A2DP profile.| +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | +| PROFILE_HID_HOST9+ | 6 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK9+ | 7 | PAN profile. | diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index 6bbea8b08a752972bcc9354b63841831ae837a88..df783bbda132f5da29e152e146cc6cb56316f083 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,10 +1,12 @@ -# Brightness - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. +# Screen Brightness The Brightness module provides an API for setting the screen brightness. +> **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. ## Modules to Import @@ -18,18 +20,30 @@ setValue(value: number): void Sets the screen brightness. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. -**System capability:** SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------- | -| value | number | Yes | Brightness value, ranging from **0** to **255**.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------- | +| value | number | Yes | Brightness value. The value ranges from 0 to 255.| + +**Error codes** + +For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md). + +| Code | Error Message | +|---------|---------| +| 4700101 | Operation failed. Cannot connect to service.| **Example** ```js -brightness.setValue(128); +try { + brightness.setValue(128); +} catch(err) { + console.error('set brightness failed, err: ' + err); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index b4f3906b02b1dea7dabd558173010a37e65c2c19..329a2e6126de45fe401a748bd580a372cd1dc18e 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,11 +1,11 @@ -# Standard NFC Card Emulation +# @ohos.nfc.cardEmulation 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). -> **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 ``` @@ -18,7 +18,7 @@ Enumerates the NFC card emulation types. **System capability**: SystemCapability.Communication.NFC.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | HCE | 0 | HCE.| | UICC | 1 | Subscriber identity module (SIM) card emulation.| @@ -30,8 +30,6 @@ isSupported(feature: number): boolean Checks whether a certain type of card emulation is supported. -**Required permissions**: ohos.permission.NFC_CARD_EMULATION - **System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -42,9 +40,9 @@ Checks whether a certain type of card emulation is supported. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ diff --git a/en/application-dev/reference/apis/js-apis-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md index 57cf8eadb5a07bcd3038c67d4d582ab4359d2ea2..1bfb1231c3c4584fe4d608891bdf2be54458e425 100644 --- a/en/application-dev/reference/apis/js-apis-connectedTag.md +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -1,18 +1,17 @@ -# Active Tag +# @ohos.connectedTag -The **connectedTag** module provides methods for using active tags. You can use the APIs provided by this module to initialize the active tag chip and read and write 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. -> **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 connectedTag from '@ohos.connectedTag'; ``` - ## connectedTag.init init(): boolean @@ -23,11 +22,11 @@ Initializes the active tag chip. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the initialization is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.uninit @@ -39,125 +38,136 @@ Uninitializes the active tag resources. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.readNdefTag readNdefTag(): Promise<string> -Reads the content of this active tag. This method uses a promise to return the result. +Reads the content of this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<string> | Promise used to return the content of the active tag.| +**Return value** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; +| **Type**| **Description**| +| -------- | -------- | +| Promise<string> | Promise used to return the content of the active tag.| - connectedTag.readNdefTag().then(result => { - console.log("promise recv ndef response: " + result); - }); - ``` +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag().then((data) => { + console.log("connectedTag readNdefTag Promise data = " + data); +}).catch((err)=> { + console.log("connectedTag readNdefTag Promise err: " + err); +}); +``` ## connectedTag.readNdefTag readNdefTag(callback: AsyncCallback<string>): void -Reads the content of this active tag. This method uses an asynchronous callback to return the result. +Reads the content of this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| +**Parameters** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.readNdefTag(result => { - console.log("callback recv ndef response: " + result); - }); - ``` +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag((err, data)=> { + if (err) { + console.log("connectedTag readNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag readNdefTag AsyncCallback data: " + data); + } +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string): Promise<void> -Writes data to this active tag. This method uses a promise to return the result. +Writes data to this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result. This method returns no value.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - writeNdefTag.write("010203") - .then((value) => { - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData).then(() => { + console.log("connectedTag writeNdefTag Promise success."); +}).catch((err)=> { + console.log("connectedTag writeNdefTag Promise err: " + err); +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string, callback: AsyncCallback<void>): void -Writes data to this active tag. This method uses an asynchronous callback to return the result. +Writes data to this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.writeNdefTag("010203", (err, value) => { - if (err) { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - return; - } - - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData, (err)=> { + if (err) { + console.log("connectedTag writeNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag writeNdefTag AsyncCallback success."); + } +}); +``` ## connectedTag.on('notify') @@ -169,18 +179,12 @@ Registers the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | Yes| Callback invoked to return the field strength state.| - -- Enumerates the field strength states. - | **Value**| **Description**| - | -------- | -------- | - | 0 | Field off.| - | 1 | Field on.| +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | Yes| Callback used to return the [NfcRfType](#nfcrftype).| ## connectedTag.off('notify') @@ -192,36 +196,54 @@ Unregisters the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - var NFC_RF_NOTIFY = "notify"; - - var recvNfcRfNotifyFunc = result => { - console.info("nfc rf receive state: " + result); - } - - // Register event notification. - connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - - // Unregister event notification. - connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +// Register the event. +connectedTag.on("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag on Callback err: " + err); + } else { + console.log("connectedTag on Callback rfState: " + rfState); + } +}); + +var initStatus = connectedTag.init(); +console.log("connectedTag init status: " + initStatus); + +// Add nfc connecected tag business oprations here... +// connectedTag.writeNdefTag(rawData) +// connectedTag.readNdefTag() + +var uninitStatus = connectedTag.uninit(); +console.log("connectedTag uninit status: " + uninitStatus); + +// Unregister the event. +connectedTag.off("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag off Callback err: " + err); + } else { + console.log("connectedTag off Callback rfState: " + rfState); + } +}); +``` ## NfcRfType -Enumerates the NFC states. +Enumerates the NFC field strength states. **System capability**: SystemCapability.Communication.ConnectedTag -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| NFC_RF_LEAVE | 0 | Field on.| +| NFC_RF_LEAVE | 0 | Field off.| | NFC_RF_ENTER | 1 | Field on.| diff --git a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md similarity index 97% rename from en/application-dev/reference/apis/js-apis-data-ValuesBucket.md rename to en/application-dev/reference/apis/js-apis-data-valuesBucket.md index 22ae3fc33e27b1dc0b859848fdb8e0ea6c6f2122..846f3f15481d700da9d738857bc217c64cbe6ac9 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 @@ -# Value Bucket +# @ohos.data.ValuesBucket The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 935211cb5ead58fd8823c87358bafc9eebafc449..f9a998f37ca17b4d4c70342bc648ed519fbe1652 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# Device Usage Statistics +# @ohos.deviceUsageStatistics (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -487,7 +487,7 @@ Enumerates the interval types for querying the application usage duration. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name | Default Value | Description | +| Name | Value | Description | | ------------ | ---- | ---------------------------------------- | | BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| | BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis. | 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 505587d21e4cd4b792ff97282b10ae1bc4662359..5a4a93c46fbe2492cecf4569f8e4e7db63469371 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,8 +1,8 @@ -# Distributed Account Management +# @ohos.account.distributedAccount -The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login status. +The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states. -> **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. @@ -49,7 +49,7 @@ Obtains distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and data is the distributed account information obtained. Otherwise, **err** is an error object.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -124,7 +124,7 @@ Obtains distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and data is the distributed account information obtained. Otherwise, **err** is an error object.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Example** ```js @@ -181,7 +181,7 @@ Sets the distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -219,7 +219,7 @@ Sets the distributed account information. This API uses a promise to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| **Return value** @@ -322,7 +322,7 @@ Defines distributed OS account information. | -------- | -------- | -------- | -------- | | name | string | Yes| Name of the distributed account. It must be a non-null string.| | id | string | Yes| UID of the distributed account. It must be a non-null string.| -| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| event | string | Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | | nickname9+ | string | No| Nickname of the distributed account. It must be a non-null string.| | avatar9+ | string | No| Avatar of the distributed account. It must be a non-null string.| -| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in query and update methods.| +| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in the setters and getters.| diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..9c09d174723ca769e8b712a2e874c9b3c6f4f3a8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -0,0 +1,2208 @@ +# Geolocation Manager + +The Geolocation Manager module provides location service management functions. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Applying for Permissions + +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. + +| API Version| 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 in the background, it must be configured to be able to run in 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). + + +## Modules to Import + +```ts +import geoLocationManager from '@ohos.geoLocationManager'; +``` + + +## geoLocationManager.on('locationChange') + +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void + +Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | request | [LocationRequest](#locationrequest) | Yes| Location request.| + | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + try { + geoLocationManager.on('locationChange', requestInfo, locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + + ``` + + +## geoLocationManager.off('locationChange') + +off(type: 'locationChange', callback?: Callback<Location>): void + +Unregisters the listener for location changes with the corresponding location request deleted. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + try { + geoLocationManager.on('locationChange', requestInfo, locationChange); + geoLocationManager.off('locationChange', locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('locationEnabledChange') + +on(type: 'locationEnabledChange', callback: Callback<boolean>): void + +Registers a listener for location service status change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.| + | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationEnabledChange = (state) => { + console.log('locationEnabledChange: ' + JSON.stringify(state)); + } + try { + geoLocationManager.on('locationEnabledChange', locationEnabledChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('locationEnabledChange') + +off(type: 'locationEnabledChange', callback?: Callback<boolean>): void; + +Unregisters the listener for location service status change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationEnabledChange = (state) => { + console.log('locationEnabledChange: state: ' + JSON.stringify(state)); + } + try { + geoLocationManager.on('locationEnabledChange', locationEnabledChange); + geoLocationManager.off('locationEnabledChange', locationEnabledChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('cachedGnssLocationsChange') + +on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; + +Registers a listener for cached GNSS location reports. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.| + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| + | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var cachedLocationsCb = (locations) => { + console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); + } + var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + try { + geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('cachedGnssLocationsChange') + +off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location>>): void; + +Unregisters the listener for cached GNSS location reports. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var cachedLocationsCb = (locations) => { + console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); + } + var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + try { + geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); + geoLocationManager.off('cachedGnssLocationsChange'); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('satelliteStatusChange') + +on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>): void; + +Registers a listener for GNSS satellite status change events. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var gnssStatusCb = (satelliteStatusInfo) => { + console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); + } + + try { + geoLocationManager.on('satelliteStatusChange', gnssStatusCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('satelliteStatusChange') + +off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo>): void; + +Unregisters the listener for GNSS satellite status change events. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var gnssStatusCb = (satelliteStatusInfo) => { + console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); + } + try { + geoLocationManager.on('satelliteStatusChange', gnssStatusCb); + geoLocationManager.off('satelliteStatusChange', gnssStatusCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('nmeaMessage') + +on(type: 'nmeaMessage', callback: Callback<string>): void; + +Registers a listener for GNSS NMEA message change events. + +**Permission required**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.| + | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var nmeaCb = (str) => { + console.log('nmeaMessage: ' + JSON.stringify(str)); + } + + try { + geoLocationManager.on('nmeaMessage', nmeaCb ); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('nmeaMessage') + +off(type: 'nmeaMessage', callback?: Callback<string>): void; + +Unregisters the listener for GNSS NMEA message change events. + +**Permission required**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.| + | callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var nmeaCb = (str) => { + console.log('nmeaMessage: ' + JSON.stringify(str)); + } + + try { + geoLocationManager.on('nmeaMessage', nmeaCb); + geoLocationManager.off('nmeaMessage', nmeaCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('gnssFenceStatusChange') + +on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; + +Registers a listener for status change events of the specified geofence. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301600 | Failed to operate the geofence. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + action: "action1", + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + + +## geoLocationManager.off('gnssFenceStatusChange') + +off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; + +Unregisters the listener for status change events of the specified geofence. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301600 | Failed to operate the geofence. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + action: "action1", + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + + +## geoLocationManager.on('countryCodeChange') + +on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; + +Registers a listener for country code change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.| + | callback | Callback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + + try { + geoLocationManager.on('countryCodeChange', callback); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('countryCodeChange') + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; + +Unregisters the listener for country code change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.| + | callback | Callback<[CountryCode](#countrycode)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + + try { + geoLocationManager.on('countryCodeChange', callback); + geoLocationManager.off('countryCodeChange', callback); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void + +Obtains the current location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; + + try { + geoLocationManager.getCurrentLocation(requestInfo, locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(callback: AsyncCallback<Location>): void; + +Obtains the current location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; + + try { + geoLocationManager.getCurrentLocation(locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> + +Obtains the current location. This API uses a promise to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> | [Location](#location) | NA | Promise used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + try { + geoLocationManager.getCurrentLocation(requestInfo).then((result) => { + console.log('current location: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCurrentLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getLastLocation + +getLastLocation(): Location + +Obtains the last location. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Location | [Location](#location) | NA | Location information.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 |Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var location = geoLocationManager.getLastLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.isLocationEnabled + +isLocationEnabled(): boolean + +Checks whether the location service is enabled. + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the location service is enabled.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var locationEnabled = geoLocationManager.isLocationEnabled(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.requestEnableLocation + +requestEnableLocation(callback: AsyncCallback<boolean>): void + +Requests to enable the location service. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301700 | No response to the request. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.requestEnableLocation((err, data) => { + if (err) { + console.log('requestEnableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('requestEnableLocation: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.requestEnableLocation + +requestEnableLocation(): Promise<boolean> + +Requests to enable the location service. This API uses a promise to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> | boolean | NA | Promise used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301700 | No response to the request. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.requestEnableLocation().then((result) => { + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, requestEnableLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocation + +enableLocation(callback: AsyncCallback<void>): void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocation((err, data) => { + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocation + +enableLocation(): Promise<void> + +Enables the location service. This API uses a promise to return the result. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocation().then((result) => { + console.log('promise, enableLocation succeed'); + }) + .catch((error) => { + console.log('promise, enableLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.disableLocation + +disableLocation(): void; + +Disables the location service. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + + +## geoLocationManager.getAddressesFromLocation + +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. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301300 | Reverse geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocation: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocation + +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; + +Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)> | NA | Promise used to return the reverse geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301300 | Reverse geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { + console.log('getAddressesFromLocation: ' + JSON.stringify(data)); + }) + .catch((error) => { + console.log('promise, getAddressesFromLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocationName + +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. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301400 | Geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocationName: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocationName + +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> + +Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)> | NA | Promise used to return the geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301400 | Geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => { + console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getAddressesFromLocationName: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.isGeocoderAvailable + +isGeocoderAvailable(): boolean; + +Obtains the (reverse) geocoding service status. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the (reverse) geocoding service is available.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isAvailable = geoLocationManager.isGeocoderAvailable(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCachedGnssLocationsSize + +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; + +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCachedGnssLocationsSize((err, size) => { + if (err) { + console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); + } + if (size) { + console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCachedGnssLocationsSize + +getCachedGnssLocationsSize(): Promise<number>; + +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<number> | number | NA | Promise used to return the number of cached GNSS locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCachedGnssLocationsSize().then((result) => { + console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCachedGnssLocationsSize: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.flushCachedGnssLocations + +flushCachedGnssLocations(callback: AsyncCallback<void>): void; + +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.flushCachedGnssLocations((err, result) => { + if (err) { + console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.flushCachedGnssLocations + +flushCachedGnssLocations(): Promise<void>; + +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.flushCachedGnssLocations().then((result) => { + console.log('promise, flushCachedGnssLocations success'); + }) + .catch((error) => { + console.log('promise, flushCachedGnssLocations: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.sendCommand + +sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void; + +Sends an extended command to the location subsystem. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| + | callback | AsyncCallback<void> | Yes| Callback used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + try { + geoLocationManager.sendCommand(requestInfo, (err, result) => { + if (err) { + console.log('sendCommand: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.sendCommand + +sendCommand(command: LocationCommand): Promise<void>; + +Sends an extended command to the location subsystem. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + try { + geoLocationManager.sendCommand(requestInfo).then((result) => { + console.log('promise, sendCommand success'); + }) + .catch((error) => { + console.log('promise, sendCommand: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(callback: AsyncCallback<CountryCode>): void; + +Obtains the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(): Promise<CountryCode>; + +Obtains the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[CountryCode](#countrycode)> | [CountryCode](#countrycode) | NA | Promise used to return the country code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocationMock + +enableLocationMock(): void; + +Enables the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocationMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(): void; + +Disables the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableLocationMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig): void; + +Sets the mock location information. The mock locations will be reported at the interval specified in this API. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [LocationMockConfig](#locationmockconfig) | Yes| Mock location information, including the interval for reporting the mock locations and the array of the mock locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locations = [ + {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, + {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} + ]; + var config = {"timeInterval": 5, "locations": locations}; + try { + geoLocationManager.setMockedLocations(config); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(): void; + +Enables the mock reverse geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableReverseGeocodingMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(): void; + +Disables the mock geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableReverseGeocodingMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): void; + +Sets information of the mock reverse geocoding function, including the mapping between a location and geographical name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographical name will be returned. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | mockInfos | Array<[ReverseGeocodingMockInfo](#reversegeocodingmockinfo)> | Yes| Array of information of the mock reverse geocoding function, including a location and a geographical name.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var mockInfos = [ + {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, + {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, + ]; + try { + geoLocationManager.setReverseGeocodingMockInfo(mockInfos); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean; + +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype)| Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean): void; + +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| + | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.setLocationPrivacyConfirmStatus(1, true); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## LocationRequestPriority + +Sets the priority of the location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| + + +## LocationRequestScenario + + Sets the scenario of the location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. 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.| + + +## ReverseGeoCodeRequest + +Defines a reverse geocoding request. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| + + +## GeoCodeRequest + +Defines a geocoding request. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| +| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| +| minLongitude | number | Yes| Yes| Minimum longitude.| +| maxLatitude | number | Yes| Yes| Maximum latitude.| +| maxLongitude | number | Yes| Yes| Maximum longitude.| + + +## GeoAddress + +Defines a geographic location. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| No | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName | string | Yes| No | Landmark of the location.| +| countryCode | string | Yes| No | Country code.| +| countryName | string| Yes| No| Country name.| +| administrativeArea | string | Yes| No| Administrative region name.| +| subAdministrativeArea | string | Yes| No| Sub-administrative region name.| +| locality | string | Yes| No| Locality information.| +| subLocality | string | Yes| No| Sub-locality information.| +| roadName | string | Yes| No|Road name.| +| subRoadName | string | Yes| No| Auxiliary road information.| +| premises | string| Yes| No|House information.| +| postalCode | string | Yes| No| Postal code.| +| phoneNumber | string | Yes| No| Phone number.| +| addressUrl | string | Yes| No| Website URL.| +| descriptions | Array<string> | Yes| No| Additional descriptions.| +| descriptionsSize | number | Yes| No| Total number of additional descriptions.| +| isFromMock | Boolean | Yes| No| Whether the geographical name is from the mock reverse geocoding function.| + + +## LocationRequest + +Defines a location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| +| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| +| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| + + +## CurrentLocationRequest + +Defines the current location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| +| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| + + +## SatelliteStatusInfo + +Defines the satellite status information. + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| No| Number of satellites.| +| satelliteIds | Array<number> | Yes| No| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| No| Altitude information.| +| azimuths | Array<number> | Yes| No| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| No| Carrier frequency.| + + +## CachedGnssLocationsRequest + +Represents a request for reporting cached GNSS locations. + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| + + +## Geofence + +Defines a GNSS geofence. Currently, only circular geofences are supported. + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| Yes|Latitude information.| +| longitude | number | Yes|Yes| Longitude information.| +| radius | number | Yes|Yes| Radius of a circular geofence.| +| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds.| + + +## GeofenceRequest + +Represents a GNSS geofencing request. + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| + + +## LocationPrivacyType + +Defines the privacy statement type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| OTHERS | 0 | Other scenarios.| +| STARTUP | 1 | Privacy statement displayed in the startup wizard.| +| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| + + +## LocationCommand + +Defines an extended command. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| command | string | Yes| Yes | Extended command, in the string format.| + + +## Location + +Defines a location. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number| Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude | number | Yes| No| Location altitude, in meters.| +| accuracy | number | Yes| No| Location accuracy, in meters.| +| speed | number | Yes| No|Speed, in m/s.| +| timeStamp | number | Yes| No| Location timestamp in the UTC format.| +| direction | number | Yes| No| Direction information.| +| timeSinceBoot | number | Yes| No| Location timestamp since boot.| +| additions | Array<string> | Yes| No| Additional description.| +| additionSize | number | Yes| No| Number of additional descriptions.| +| isFromMock | Boolean | Yes| No| Whether the location information is from the mock location function.| + + +## ReverseGeocodingMockInfo + +Represents information of the mock reverse geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.| +| geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographical name.| + + +## LocationMockConfig + +Represents the information of the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| timeInterval | number | Yes| Yes| Interval at which mock locations are reported, in seconds.| +| locations | Array<Location> | Yes| Yes| Array of mocked locations.| + + +## CountryCode + +Represents country code information. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| country | string | Yes| No| Country code.| +| type | [CountryCodeType](#countrycodetype) | Yes| No| Country code source.| + + +## CountryCodeType + +Represents the country code source type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | Country code obtained from the language configuration of the globalization module.| +| COUNTRY_CODE_FROM_SIM | 2 | Country code obtained from the SIM card.| +| COUNTRY_CODE_FROM_LOCATION | 3 | Country code obtained using the reverse geocoding function based on the user's location information.| +| COUNTRY_CODE_FROM_NETWORK | 4 | Country code obtained from the cellular network registration information.| diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 92118167ad603189eac98eae73e156a794542f99..8bc027058b6d9bbda89636757219f83827029317 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,24 +1,56 @@ # Geolocation -Location services provide basic functions 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. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 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 + +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. + +| API Version| 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 in the background, it must be configured to be able to run in 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). ## Modules to Import -```js +```ts import geolocation from '@ohos.geolocation'; ``` -## geolocation.on('locationChange') +## geolocation.on('locationChange')(deprecated) on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -Registers a listener for location changes with a location request initiated. +Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). + +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -27,13 +59,14 @@ Registers a listener for location changes with a location request initiated. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| - | request | LocationRequest | Yes| Location request.| + | request | [LocationRequest](#locationrequest) | Yes| Location request.| | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { @@ -43,13 +76,16 @@ Registers a listener for location changes with a location request initiated. ``` -## geolocation.off('locationChange') +## geolocation.off('locationChange')(deprecated) off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -58,12 +94,12 @@ Unregisters the listener for location changes with the corresponding location re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| - | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| + | callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { @@ -74,13 +110,16 @@ Unregisters the listener for location changes with the corresponding location re ``` -## geolocation.on('locationServiceState') +## geolocation.on('locationServiceState')(deprecated) on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -93,8 +132,8 @@ Registers a listener for location service status change events. **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); @@ -103,13 +142,16 @@ Registers a listener for location service status change events. ``` -## geolocation.off('locationServiceState') +## geolocation.off('locationServiceState')(deprecated) off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -118,12 +160,12 @@ Unregisters the listener for location service status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| - | callback | Callback<boolean> | No| Callback used to return the location service status change event.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); @@ -133,13 +175,17 @@ Unregisters the listener for location service status change events. ``` -## geolocation.on('cachedGnssLocationsReporting')8+ +## geolocation.on('cachedGnssLocationsReporting')(deprecated) on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -148,13 +194,13 @@ Registers a listener for cached GNSS location reports. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| - | request | CachedGnssLocationsRequest | Yes| Request for reporting cached GNSS location.| - | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| + | callback | Callback<Array<[Location](#location)>> | Yes| Callback used to return cached GNSS locations.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); @@ -164,13 +210,17 @@ Registers a listener for cached GNSS location reports. ``` -## geolocation.off('cachedGnssLocationsReporting')8+ +## geolocation.off('cachedGnssLocationsReporting')(deprecated) off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -179,12 +229,12 @@ Unregisters the listener for cached GNSS location reports. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| - | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| + | callback | Callback<Array<[Location](#location)>> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); @@ -195,13 +245,17 @@ Unregisters the listener for cached GNSS location reports. ``` -## geolocation.on('gnssStatusChange')8+ +## geolocation.on('gnssStatusChange')(deprecated) on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -210,12 +264,12 @@ Registers a listener for GNSS satellite status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| - | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); @@ -224,13 +278,17 @@ Registers a listener for GNSS satellite status change events. ``` -## geolocation.off('gnssStatusChange')8+ +## geolocation.off('gnssStatusChange')(deprecated) off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -239,11 +297,11 @@ Unregisters the listener for GNSS satellite status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| - | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); @@ -253,13 +311,17 @@ Unregisters the listener for GNSS satellite status change events. ``` -## geolocation.on('nmeaMessageChange')8+ +## geolocation.on('nmeaMessageChange')(deprecated) on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -272,8 +334,8 @@ Registers a listener for GNSS NMEA message change events. **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); @@ -282,13 +344,17 @@ Registers a listener for GNSS NMEA message change events. ``` -## geolocation.off('nmeaMessageChange')8+ +## geolocation.off('nmeaMessageChange')(deprecated) off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -297,12 +363,12 @@ Unregisters the listener for GNSS NMEA message change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| - | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| + | callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); @@ -312,13 +378,17 @@ Unregisters the listener for GNSS NMEA message change events. ``` -## geolocation.on('fenceStatusChange')8+ +## geolocation.on('fenceStatusChange')(deprecated) on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence @@ -327,13 +397,13 @@ Registers a listener for status change events of the specified geofence. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| - | request | GeofenceRequest | Yes| Geofencing request.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -357,13 +427,17 @@ Registers a listener for status change events of the specified geofence. ``` -## geolocation.off('fenceStatusChange')8+ +## geolocation.off('fenceStatusChange')(deprecated) off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence @@ -372,12 +446,12 @@ Unregisters the listener for status change events of the specified geofence. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| - | request | GeofenceRequest | Yes| Geofencing request.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -402,14 +476,16 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.getCurrentLocation +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void - Obtains the current location. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -417,12 +493,12 @@ Obtains the current location. This API uses an asynchronous callback to return t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + | request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { @@ -434,18 +510,55 @@ Obtains the current location. This API uses an asynchronous callback to return t } }; geolocation.getCurrentLocation(requestInfo, locationChange); + ``` + + +## geolocation.getCurrentLocation(deprecated) + +getCurrentLocation(callback: AsyncCallback<Location>): void + + +Obtains the current location. This API uses an asynchronous callback to return the result. + +> **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 + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Example** + + ```ts + import geolocation from '@ohos.geolocation'; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; geolocation.getCurrentLocation(locationChange); ``` -## geolocation.getCurrentLocation +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> - Obtains the current location. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -457,14 +570,14 @@ Obtains the current location. This API uses a promise to return the result. **Return value** - | Name| Description| - | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the current location.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> |[Location](#location)|NA| Promise used to return the current location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { @@ -473,13 +586,16 @@ Obtains the current location. This API uses a promise to return the result. ``` -## geolocation.getLastLocation +## geolocation.getLastLocation(deprecated) getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -491,8 +607,8 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { @@ -505,26 +621,29 @@ Obtains the previous location. This API uses an asynchronous callback to return ``` -## geolocation.getLastLocation +## geolocation.getLastLocation(deprecated) getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the previous location.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> | [Location](#location)|NA|Promise used to return the previous location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); @@ -532,14 +651,16 @@ Obtains the previous location. This API uses a promise to return the result. ``` -## geolocation.isLocationEnabled +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(callback: AsyncCallback<boolean>): void - Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -550,8 +671,8 @@ Checks whether the location service is enabled. This API uses an asynchronous ca | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { @@ -564,25 +685,28 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ``` -## geolocation.isLocationEnabled +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> | boolean|NA|Promise used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); @@ -590,14 +714,16 @@ Checks whether the location service is enabled. This API uses a promise to retur ``` -## geolocation.requestEnableLocation +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(callback: AsyncCallback<boolean>): void - Requests to enable the location service. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core @@ -608,8 +734,8 @@ Requests to enable the location service. This API uses an asynchronous callback | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { @@ -622,159 +748,45 @@ Requests to enable the location service. This API uses an asynchronous callback ``` -## geolocation.requestEnableLocation +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1). -**System capability**: SystemCapability.Location.Location.Core - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.requestEnableLocation().then((result) => { - console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); - }); - ``` - - -## geolocation.enableLocation - -enableLocation(callback: AsyncCallback<boolean>): void; - -Enables the location service. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.enableLocation((err, data) => { - if (err) { - console.log('enableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableLocation: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableLocation - -enableLocation(): Promise<boolean> - -Enables the location service. This API uses a promise to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.enableLocation().then((result) => { - console.log('promise, enableLocation: ' + JSON.stringify(result)); - }); - ``` - -## geolocation.disableLocation - -disableLocation(callback: AsyncCallback<boolean>): void; - -Disables the location service. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + | Promise<boolean> | boolean|NA|Promise used to return the location service status.| **Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.disableLocation((err, data) => { - if (err) { - console.log('disableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('disableLocation: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.disableLocation - -disableLocation(): Promise<boolean> - -Disables the location service. This API uses a promise to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js + ```ts import geolocation from '@ohos.geolocation'; - geolocation.disableLocation().then((result) => { - console.log('promise, disableLocation: ' + JSON.stringify(result)); + geolocation.requestEnableLocation().then((result) => { + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); ``` -## geolocation.isGeoServiceAvailable + +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder @@ -785,8 +797,8 @@ Checks whether the (reverse) geocoding service is available. This API uses an as | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { @@ -799,25 +811,28 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ``` -## geolocation.isGeoServiceAvailable +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Promise used to return the (reverse) geocoding service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); @@ -825,13 +840,16 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ``` -## geolocation.getAddressesFromLocation +## geolocation.getAddressesFromLocation(deprecated) 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. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder @@ -843,8 +861,8 @@ Converts coordinates into geographic description through reverse geocoding. This | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { @@ -858,13 +876,16 @@ Converts coordinates into geographic description through reverse geocoding. This ``` -## geolocation.getAddressesFromLocation +## geolocation.getAddressesFromLocation(deprecated) getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder @@ -876,13 +897,13 @@ Converts coordinates into geographic description through reverse geocoding. This **Return value** - | Name| Description| - | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|Promise used to return the reverse geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { @@ -891,13 +912,16 @@ Converts coordinates into geographic description through reverse geocoding. This ``` -## geolocation.getAddressesFromLocationName +## geolocation.getAddressesFromLocationName(deprecated) 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. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder @@ -909,8 +933,8 @@ Converts geographic description into coordinates through geocoding. This API use | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { @@ -924,13 +948,16 @@ Converts geographic description into coordinates through geocoding. This API use ``` -## geolocation.getAddressesFromLocationName +## geolocation.getAddressesFromLocationName(deprecated) getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder @@ -942,13 +969,13 @@ Converts geographic description into coordinates through geocoding. This API use **Return value** - | Name| Description| - | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|Callback used to return the geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { @@ -957,13 +984,17 @@ Converts geographic description into coordinates through geocoding. This API use ``` -## geolocation.getCachedGnssLocationsSize8+ +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -974,8 +1005,8 @@ Obtains the number of cached GNSS locations. | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { @@ -988,25 +1019,29 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.getCachedGnssLocationsSize8+ +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss **Return value** - | Name| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of cached GNSS locations.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<number> | number|NA|Promise used to return the number of cached GNSS locations.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); @@ -1014,13 +1049,17 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.flushCachedGnssLocations8+ +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -1031,8 +1070,8 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { @@ -1045,25 +1084,29 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.flushCachedGnssLocations8+ +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Promise used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); @@ -1071,13 +1114,17 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.sendCommand8+ +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; -Sends an extended command to the location subsystem. This API can only be called by system applications. +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). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -1085,12 +1132,12 @@ Sends an extended command to the location subsystem. This API can only be called | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes| Extended command (string) to be sent.| + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { @@ -1104,13 +1151,17 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.sendCommand8+ +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand): Promise<boolean>; -Sends an extended command to the location subsystem. This API can only be called by system applications. +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). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -1118,17 +1169,17 @@ Sends an extended command to the location subsystem. This API can only be called | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes| Extended command (string) to be sent.| + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { @@ -1137,15 +1188,18 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## LocationRequestPriority +## LocationRequestPriority(deprecated) Sets the priority of the location request. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | UNSET | 0x200 | Priority unspecified.| | ACCURACY | 0x201 | Location accuracy.| @@ -1153,15 +1207,18 @@ Sets the priority of the location request. | FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| -## LocationRequestScenario +## LocationRequestScenario(deprecated) Sets the scenario of the location request. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | UNSET | 0x300 | Scenario unspecified.| | NAVIGATION | 0x301 | Navigation.| @@ -1171,15 +1228,18 @@ Sets the priority of the location request. | NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. 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.| -## GeoLocationErrorCode +## GeoLocationErrorCode(deprecated) Enumerates error codes of the location service. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| | REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| @@ -1190,213 +1250,255 @@ Enumerates error codes of the location service. | LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -## ReverseGeoCodeRequest +## ReverseGeoCodeRequest(deprecated) Defines a reverse geocoding request. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| maxItems | number | No| Maximum number of location records to be returned.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| -## GeoCodeRequest +## GeoCodeRequest(deprecated) Defines a geocoding request. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| -| maxItems | number | No| Maximum number of location records to be returned.| -| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| -| minLongitude | number | No| Minimum longitude.| -| maxLatitude | number | No| Maximum latitude.| -| maxLongitude | number | No| Maximum longitude.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| +| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| +| minLongitude | number | Yes| Yes| Minimum longitude.| +| maxLatitude | number | Yes| Yes| Maximum latitude.| +| maxLongitude | number | Yes| Yes| Maximum longitude.| -## GeoAddress +## GeoAddress(deprecated) Defines a geographic location. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Geocoder -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName7+ | string | No| Landmark of the location.| -| countryCode7+ | string | No| Country code.| -| countryName7+ | string | No| Country name.| -| administrativeArea7+ | string | No| Administrative region name.| -| subAdministrativeArea7+ | string | No| Sub-administrative region name.| -| locality7+ | string | No| Locality information. | -| subLocality7+ | string | No| Sub-locality information. | -| roadName7+ | string | No| Road name.| -| subRoadName7+ | string | No| Auxiliary road information.| -| premises7+ | string | No| House information.| -| postalCode7+ | string | No| Postal code.| -| phoneNumber7+ | string | No| Phone number.| -| addressUrl7+ | string | No| Website URL.| -| descriptions7+ | Array<string> | No| Additional description.| -| descriptionsSize7+ | number | No| Total number of additional descriptions.| - - -## LocationRequest +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude7+ | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | Yes| No| Landmark of the location.| +| countryCode7+ | string | Yes| No| Country code.| +| countryName7+ | string | Yes| No| Country name.| +| administrativeArea7+ | string | Yes| No| Administrative region name.| +| subAdministrativeArea7+ | string | Yes| No| Sub-administrative region name.| +| locality7+ | string | Yes| No| Locality information.| +| subLocality7+ | string | Yes| No| Sub-locality information.| +| roadName7+ | string | Yes| No| Road name.| +| subRoadName7+ | string | Yes| No| Auxiliary road information.| +| premises7+ | string | Yes| No| House information.| +| postalCode7+ | string | Yes| No| Postal code.| +| phoneNumber7+ | string | Yes| No| Phone number.| +| addressUrl7+ | string | Yes| No| Website URL.| +| descriptions7+ | Array<string> | Yes| No| Additional descriptions.| +| descriptionsSize7+ | number | Yes| No| Total number of additional descriptions.| + + +## LocationRequest(deprecated) Defines a location request. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| -| timeInterval | number | No| Time interval at which location information is reported.| -| distanceInterval | number | No| Distance interval at which location information is reported.| -| maxAccuracy | number | No| Location accuracy.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| +| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| +| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| -## CurrentLocationRequest +## CurrentLocationRequest(deprecated) Defines the current location request. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| -| maxAccuracy | number | No| Location accuracy, in meters.| -| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| +| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| -## SatelliteStatusInfo8+ +## SatelliteStatusInfo(deprecated) Defines the satellite status information. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes| Number of satellites.| -| satelliteIds | Array<number> | Yes| Array of satellite IDs.| -| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| -| altitudes | Array<number> | Yes| Altitude information.| -| azimuths | Array<number> | Yes| Azimuth information.| -| carrierFrequencies | Array<number> | Yes| Carrier frequency.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| No| Number of satellites.| +| satelliteIds | Array<number> | Yes| No| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| No| Altitude information.| +| azimuths | Array<number> | Yes| No| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| No| Carrier frequency.| -## CachedGnssLocationsRequest8+ +## CachedGnssLocationsRequest(deprecated) Represents a request for reporting cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | Yes| Interval for reporting the cached GNSS locations, in milliseconds.| -| wakeUpCacheQueueFull | boolean | Yes| **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| -## Geofence8+ +## Geofence(deprecated) Defines a GNSS geofence. Currently, only circular geofences are supported. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude | number | Yes| Latitude information.| -| longitude | number | Yes| Longitude information.| -| radius | number | Yes| Radius of a circular geofence.| -| expiration | number | Yes| Expiration period of a geofence, in milliseconds.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| Yes | Latitude information.| +| longitude | number | Yes| Yes | Longitude information.| +| radius | number | Yes| Yes | Radius of a circular geofence.| +| expiration | number | Yes| Yes | Expiration period of a geofence, in milliseconds.| -## GeofenceRequest8+ +## GeofenceRequest(deprecated) Represents a GNSS geofencing request. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | Yes| Priority of the location information.| -| scenario | LocationRequestScenario | Yes| Location scenario.| -| geofence | Geofence | Yes| Geofence information.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes | Priority of the location information.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| -## LocationPrivacyType8+ +## LocationPrivacyType(deprecated) Defines the privacy statement type. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | OTHERS | 0 | Other scenarios.| | STARTUP | 1 | Privacy statement displayed in the startup wizard.| | CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| -## LocationCommand8+ +## LocationCommand(deprecated) Defines an extended command. -**Permission required**: ohos.permission.LOCATION +> **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). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | Yes| Location scenario.| -| command | string | Yes| Extended command, in the string format.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| command | string | Yes| Yes | Extended command, in the string format.| -## Location +## Location(deprecated) Defines a location. -**Permission required**: ohos.permission.LOCATION +> **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 **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| altitude7+ | number | Yes| Location altitude, in meters.| -| accuracy7+ | number | Yes| Location accuracy, in meters.| -| speed7+ | number | Yes| Speed, in m/s.| -| timeStamp7+ | number | Yes| Location timestamp in the UTC format.| -| direction7+ | number | Yes| Direction information.| -| timeSinceBoot7+ | number | Yes| Location timestamp since boot.| -| additions7+ | Array<string> | No| Additional information.| -| additionSize7+ | number | No| Number of additional descriptions.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude7+ | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude7+ | number | Yes| No| Location altitude, in meters.| +| accuracy7+ | number | Yes| No| Location accuracy, in meters.| +| speed7+ | number | Yes| No| Speed, in m/s.| +| timeStamp7+ | number | Yes| No| Location timestamp in the UTC format.| +| direction7+ | number | Yes| No| Direction information.| +| timeSinceBoot7+ | number | Yes| No| Location timestamp since boot.| +| additions7+ | Array<string> | Yes| No| Additional description.| +| additionSize7+ | number | Yes| No| Number of additional descriptions.| diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 1bf548153ad9837dc60e7a655852a33987b22871..16b144f78ec85198dfc570336fcf021a9bc86028 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1,4 +1,4 @@ -# Image Processing +# @ohos.multimedia.image (Image Processing) The **Image** module provides APIs for image processing. You can use the APIs to create a **PixelMap** object with specified properties or read image pixel data (even in an area). @@ -22,7 +22,7 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | | colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| @@ -57,7 +57,7 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------------- | | colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties. | @@ -907,7 +907,7 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1077,9 +1077,9 @@ const data = new ArrayBuffer(112); const imageSourceApi = image.createImageSource(data); ``` -## image.createIncrementalSource9+ +## image.CreateIncrementalSource9+ -createIncrementalSource(buf: ArrayBuffer): ImageSource +CreateIncrementalSource(buf: ArrayBuffer): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1101,12 +1101,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); // 96 is the size of the pixel map buffer to create. The value is calculated as follows: height x width x 4. -const imageSourceIncrementalSApi = image.createIncrementalSource(buf); +const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); ``` -## image.createIncrementalSource9+ +## image.CreateIncrementalSource9+ -createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource +CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1129,7 +1129,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); // 96 is the size of the pixel map buffer to create. The value is calculated as follows: height x width x 4. -const imageSourceIncrementalSApi = image.createIncrementalSource(buf); +const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); ``` ## ImageSource @@ -1181,7 +1181,7 @@ Obtains information about this image. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ---------------------------------------- | | callback | AsyncCallback<[ImageInfo](#imageinfo)> | Yes | Callback used to return the image information.| @@ -1203,7 +1203,7 @@ Obtains information about an image with the specified index. This API uses a pro **Parameters** -| Name | Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ----- | ------ | ---- | ------------------------------------- | | index | number | No | Index of the image. If this parameter is not set, the default value **0** is used.| @@ -1234,7 +1234,7 @@ Obtains the value of a property with the specified index in this image. This API **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ---------------------------------------------------- | ---- | ------------------------------------ | | key | string | Yes | Name of the property. | | options | [GetImagePropertyOptions](#getimagepropertyoptions7) | No | Image properties, including the image index and default property value.| @@ -1372,12 +1372,12 @@ Updates incremental data. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ----------- | ---- | ------------ | | buf | ArrayBuffer | Yes | Incremental data. | | isFinished | boolean | Yes | Whether the update is complete.| -| value | number | No | Offset for data reading. | -| length | number | No | Array length. | +| value | number | Yes | Offset for data reading. | +| length | number | Yes | Array length. | **Return value** @@ -1405,12 +1405,12 @@ Updates incremental data. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | -------------------- | | buf | ArrayBuffer | Yes | Incremental data. | | isFinished | boolean | Yes | Whether the update is complete. | -| value | number | No | Offset for data reading. | -| length | number | No | Array length. | +| value | number | Yes | Offset for data reading. | +| length | number | Yes | Array length. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1434,7 +1434,7 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------ | ---- | ---------- | | options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters.| @@ -1486,7 +1486,7 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------------- | | options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | | callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| @@ -1518,7 +1518,7 @@ Releases this **ImageSource** instance. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked for instance release. If the operation fails, an error message is returned.| @@ -1768,11 +1768,11 @@ Creates an **ImageReceiver** instance by specifying the image width, height, for **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). (Currently, the value of this parameter is agreed between the user and camera. In the future, there may be other application scenarios. The receiver is used only for transfer. Currently, only **ImageFormat:JPEG** is supported.) | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). (Only ImageFormat:JPEG and 4 are supported.) | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1813,7 +1813,7 @@ Obtains a surface ID for the camera or other components. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the surface ID.| @@ -1913,7 +1913,7 @@ Reads the next image from the **ImageReceiver** instance. This API uses an async **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | -------------------------- | | callback | AsyncCallback<[Image](#image9)> | Yes | Callback used to return the next image.| @@ -1963,7 +1963,7 @@ Listens for image arrival events. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------------------------------ | | type | string | Yes | Type of event to listen for. The value is fixed at **imageArrival**, which is triggered when an image is received.| | callback | AsyncCallback\ | Yes | Callback invoked for the event. | @@ -1984,7 +1984,7 @@ Releases this **ImageReceiver** instance. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2028,7 +2028,7 @@ Creates an **ImageCreator** instance by specifying the image width, height, form **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | @@ -2071,7 +2071,7 @@ Obtains an image buffer from the idle queue and writes image data into it. This **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | ---------------------------------------| ---- | -------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| @@ -2080,9 +2080,9 @@ Obtains an image buffer from the idle queue and writes image data into it. This ```js creator.dequeueImage((err, img) => { if (err) { - console.info('dequeueImage succeeded.'); + console.info('dequeueImage failed.'); } - console.info('dequeueImage failed.'); + console.info('dequeueImage succeeded.'); }); ``` @@ -2120,7 +2120,7 @@ Places the drawn image in the dirty queue. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------| ---- | -------------------- | | interface | Image | Yes | Drawn image.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| @@ -2128,12 +2128,25 @@ Places the drawn image in the dirty queue. This API uses an asynchronous callbac **Example** ```js -creator.queueImage(img, (err) => { - if (err) { - console.info('dequeueImage failed: ' + err); - } - console.info('dequeueImage succeeded'); +creator.dequeueImage().then(img => { + // Draw the image. + img.getComponent(4).then(component => { + var bufferArr = new Uint8Array(component.byteBuffer); + for (var i = 0; i < bufferArr.length; i += 4) { + bufferArr[i] = 0; //B + bufferArr[i + 1] = 0; //G + bufferArr[i + 2] = 255; //R + bufferArr[i + 3] = 255; //A + } + }) + creator.queueImage(img, (err) => { + if (err) { + console.info('queueImage failed: ' + err); + } + console.info('queueImage succeeded'); + }) }) + ``` ### queueImage9+ @@ -2159,11 +2172,24 @@ Places the drawn image in the dirty queue. This API uses a promise to return the **Example** ```js -creator.queueImage(img).then(() => { - console.info('dequeueImage succeeded.'); -}).catch(error => { - console.info('dequeueImage failed: ' + error); +creator.dequeueImage().then(img => { + // Draw the image. + img.getComponent(4).then(component => { + var bufferArr = new Uint8Array(component.byteBuffer); + for (var i = 0; i < bufferArr.length; i += 4) { + bufferArr[i] = 0; //B + bufferArr[i + 1] = 0; //G + bufferArr[i + 2] = 255; //R + bufferArr[i + 3] = 255; //A + } + }) + creator.queueImage(img).then(() => { + console.info('queueImage succeeded.'); + }).catch(error => { + console.info('queueImage failed: ' + error); + }) }) + ``` ### on9+ @@ -2176,7 +2202,7 @@ Listens for image release events. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------| ---- | -------------------- | | type | string | Yes | Type of event, which is **'imageRelease'**.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| @@ -2264,7 +2290,7 @@ Obtains the component buffer from the **Image** instance based on the color comp **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | --------------------------------------- | ---- | -------------------- | | componentType | [ComponentType](#componenttype9) | Yes | Color component type of the image. | | callback | AsyncCallback<[Component](#component9)> | Yes | Callback used to return the component buffer.| @@ -2291,7 +2317,7 @@ Obtains the component buffer from the **Image** instance based on the color comp **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------------- | ---- | ---------------- | | componentType | [ComponentType](#componenttype9) | Yes | Color component type of the image.| @@ -2319,7 +2345,7 @@ The corresponding resources must be released before another image arrives. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2398,7 +2424,7 @@ Enumerates the pixel formats of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | @@ -2416,7 +2442,7 @@ Enumerates the alpha types of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| @@ -2429,7 +2455,7 @@ Enumerates the scale modes of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------- | ------ | -------------------------------------------------- | | CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.| | FIT_TARGET_SIZE | 0 | Reduces the image size to the dimensions of the target. | @@ -2519,7 +2545,7 @@ Describes the exchangeable image file format (EXIF) information of an image. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ----------------------- | ------------------------ | | BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. | | ORIENTATION | "Orientation" | Image orientation. | @@ -2542,7 +2568,7 @@ Enumerates the image formats. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------ | ------ | -------------------- | | YCBCR_422_SP | 1000 | YCBCR422 semi-planar format.| | JPEG | 2000 | JPEG encoding format. | @@ -2553,7 +2579,7 @@ Enumerates the color component types of images. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver -| Name | Default Value| Description | +| Name | Value | Description | | ----- | ------ | ----------- | | YUV_Y | 1 | Luminance component. | | YUV_U | 2 | Chrominance component. | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..ada115441c19e1a39cad20d3989ad581943a0d7d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -0,0 +1,1159 @@ +# 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**. + +```ts +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' +let axContext; +class MainAbility extends AccessibilityExtensionAbility { + onConnect(): void { + console.log('AxExtensionAbility onConnect'); + 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. This API uses a promise to return the result. + +**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<void> | Promise that returns no value.| + +**Example** + +```ts +let targetNames = ['com.ohos.xyz']; +try { + axContext.setTargetBundleName(targetNames).then(() => { + console.info('set target bundle names success'); + }).catch((err) => { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; +``` + +## AccessibilityExtensionContext.setTargetBundleName + +setTargetBundleName(targetNames: Array\, callback: AsyncCallback\): void; + +Sets the concerned target bundle. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | ---- | -------- | +| targetNames | Array<string> | Yes | Name of the target bundle.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation fails, **error** that contains data is returned.| + +**Example** + +```ts +let targetNames = ['com.ohos.xyz']; +try { + axContext.setTargetBundleName(targetNames, (err, data) => { + if (err) { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + return; + } + console.info('set target bundle names success'); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus?: boolean): Promise\; + +Obtains the focus element. This API uses a promise to return the result. + +**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.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let focusElement; +try { + axContext.getFocusElement().then((data) => { + focusElement = data; + console.log('get focus element success'); + }).catch((err) => { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(callback: AsyncCallback\): void; + +Obtains the focus element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let focusElement; +try { + axContext.getFocusElement((err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus: boolean, callback: AsyncCallback\): void; + +Obtains the focus element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| + +**Example** + +```ts +let focusElement; +let isAccessibilityFocus = true; +try { + axContext.getFocusElement(isAccessibilityFocus, (err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); +}); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId?: number): Promise\; + +Obtains the root element of a window. This API uses a promise to return the result. + +**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.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +try { + axContext.getWindowRootElement().then((data) => { + rootElement = data; + console.log('get root element of the window success'); + }).catch((err) => { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get root element of the window, ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(callback: AsyncCallback\): void; + +Obtains the root element of a window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +try { + axContext.getWindowRootElement((err, data) => { + if (err) { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + return; + } + rootElement = data; + console.info('get root element of the window success'); +}); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId: number, callback: AsyncCallback\): void; + +Obtains the root element of a window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | Yes | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +let windowId = 10; +try { + axContext.getWindowRootElement(windowId, (err, data) => { + if (err) { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + return; + } + rootElement = data; + console.info('get root element of the window success'); +}); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId?: number): Promise\>; + +Obtains the list of windows on a display. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | No | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<Array<AccessibilityElement>> | Promise used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +try { + axContext.getWindows().then((data) => { + windows = data; + console.log('get windows success'); + }).catch((err) => { + console.error('failed to get windows, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(callback: AsyncCallback\>): void; + +Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +try { + axContext.getWindows((err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId: number, callback: AsyncCallback\>): void; + +Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | Yes | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +let displayId = 10; +try { + axContext.getWindows(displayId, (err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.injectGesture + +injectGesture(gesturePath: GesturePath): Promise\; + +Inject a gesture. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; +let gesturePath = new GesturePath.GesturePath(100); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint.GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath).then(() => { + console.info('inject gesture success'); + }).catch((err) => { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityExtensionContext.injectGesture + +injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void + +Inject a gesture. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; +let gesturePath = new GesturePath.GesturePath(100); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint.GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath, (err, data) => { + if (err) { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + return; + } + console.info('inject gesture success'); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityElement9+ + +Defines the accessibilityelement. Before calling APIs of **AccessibilityElement**, you must call [AccessibilityExtensionContext.getFocusElement()](#accessibilityextensioncontextgetfocuselement) or [AccessibilityExtensionContext.getWindowRootElement()](#accessibilityextensioncontextgetwindowrootelement) to obtain an **AccessibilityElement** instance. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +## attributeNames + +attributeNames\(): Promise\>; + +Obtains all attribute names of this element. This API uses a promise to return the result. + +**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 rootElement; +let attributeNames; +rootElement.attributeNames().then((data) => { + console.log('get attribute names success'); + attributeNames = data; +}).catch((err) => { + console.log('failed to get attribute names, because ' + JSON.stringify(err)); +}); +``` +## attributeNames + +attributeNames\(callback: AsyncCallback\>): void; + +Obtains all attribute names of this element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<T>> | Yes | Callback used to return all attribute names of the element.| + +**Example** + +```ts +let rootElement; +let attributeNames; +rootElement.attributeNames((err, data) => { + if (err) { + console.error('failed to get attribute names, because ' + JSON.stringify(err)); + return; + } + attributeNames = data; + console.info('get attribute names success'); +}); +``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T): Promise\; + +Obtains the attribute value based on an attribute name. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<ElementAttributeValues[T]> | Promise used to return the attribute value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + +**Example** + +```ts +let attributeName = 'name'; +let attributeValue; +let rootElement; +try { + rootElement.attributeValue(attributeName).then((data) => { + console.log('get attribute value by name success'); + attributeValue = data; + }).catch((err) => { + console.log('failed to get attribute value, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T, + callback: AsyncCallback\): void; + +Obtains the attribute value based on an attribute name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | +| callback | AsyncCallback<ElementAttributeValues[T]> | Yes | Callback used to return the attribute value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + +**Example** + +```ts +let rootElement; +let attributeValue; +let attributeName = 'name'; +try { + rootElement.attributeValue(attributeName, (err, data) => { + if (err) { + console.error('failed to get attribute value, because ' + JSON.stringify(err)); + return; + } + attributeValue = data; + console.info('get attribute value success'); + }); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); +} +``` +## actionNames + +actionNames(): Promise\>; + +Obtains the names of all actions supported by this element. This API uses a promise to return the result. + +**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 rootElement; +let actionNames; +rootElement.actionNames().then((data) => { + console.log('get action names success'); + actionNames = data; +}).catch((err) => { + console.log('failed to get action names because ' + JSON.stringify(err)); +}); +``` +## actionNames + +actionNames(callback: AsyncCallback\>): void; + +Obtains the names of all actions supported by this element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the names of all actions supported by the element.| + +**Example** + +```ts +let rootElement; +let actionNames; +rootElement.actionNames((err, data) => { + if (err) { + console.error('failed to get action names, because ' + JSON.stringify(err)); + return; + } + actionNames = data; + console.info('get action names success'); +}); +``` +## performAction + +performAction(actionName: string, parameters?: object): Promise\; + +Performs an action based on the specified action name. This API uses a promise to return the result. + +**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<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +try { + rootElement.performAction('action').then((data) => { + console.info('perform action success'); + }).catch((err) => { + console.log('failed to perform action, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## performAction + +performAction(actionName: string, callback: AsyncCallback\): void; + +Performs an action based on the specified action name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Attribute name. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +try { + rootElement.performAction('action', (err, data) => { + if (err) { + console.error('failed to perform action, because ' + JSON.stringify(err)); + return; + } + console.info('perform action success'); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## performAction + +performAction(actionName: string, parameters: object, callback: AsyncCallback\): void; + +Performs an action based on the specified action name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Action name. | +| parameters | object | Yes | Parameter required for performing the target action. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +let actionName = 'action'; +let parameters = { + 'setText': 'test text' +}; +try { + rootElement.performAction(actionName, parameters, (err, data) => { + if (err) { + console.error('failed to perform action, because ' + JSON.stringify(err)); + return; + } + console.info('perform action success'); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string): Promise\>; + +Queries the element information of the **content** type. This API uses a promise to return the result. + +**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<AccessibilityElement>> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + rootElement.findElement(type, condition).then((data) => { + elements = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string, callback: AsyncCallback\>): void; + +Queries the element information of the **content** type. This API uses an asynchronous callback to return the result. + +**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. | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType): Promise\; + +Queries the element information of the **focusType** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**. | +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusType'; +let condition = 'normal'; +let element; +try { + rootElement.findElement(type, condition).then((data) => { + element = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; + +Queries the element information of the **focusType** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**. | +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusType'; +let condition = 'normal'; +let element; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + element = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection): Promise\; + +Queries the element information of the **focusDirection** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | +| condition | [FocusDirection](#focusdirection) | Yes | Enumerates the focus directions. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusDirection'; +let condition = 'up'; +let element; +try { + rootElement.findElement(type, condition).then((data) => { + element = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; + +Queries the element information of the **focusDirection** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | +| condition | [FocusDirection](#focusdirection) | Yes | Direction of the next focus element. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusDirection'; +let condition = 'up'; +let elements; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 2f3a208fe1f95b2c4f936709d047fa4c9581f8b6..91ef73c07db34721d0cc0f964bb992ce37669ae3 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,8 +1,9 @@ -# NFC Tags +# @ohos.nfc.tag The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. -> **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. ## **Declaration** @@ -47,12 +48,10 @@ Before developing applications related to tag read and write, you must declare N } ``` > **CAUTION**
-> -> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. -> - The **name** field of **metadata** is mandatory. It must be **tag-tech** and cannot be changed. -> - The **value** field of **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or their combinations. Incorrect setting of this field will cause a parsing failure. -> - The **name** field of **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. - +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. ## **Modules to Import** @@ -61,34 +60,63 @@ import tag from '@ohos.nfc.tag'; ``` ## **tag.TagInfo** -Before reading or writing data to a card with tags, the application must obtain **TagInfo** to determine the tag technologies supported by the card. Then, the application can invoke the correct API to communicate with the card. + +Before a card with tags is read or written, **TagInfo** must be obtained to determine the tag technologies supported by the card. In this way, the application can invoke the correct API to communicate with the card. ```js import tag from '@ohos.nfc.tag'; onCreate(want, launchParam) { // Add other code here. - // want is initialized by the NFC service and contains taginfo. - var tagInfo = tag.getTagInfo(want); - if (tagInfo == undefined) { + // want is initialized by the NFC service and contains tagInfo. + var tagInfo; + try { + tagInfo = tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); return; } + + // get the supported technologies for this found tag. var isNfcATag = false; + var isIsoDepTag = false; for (var i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.NFC_A) { isNfcATag = true; - break; + } + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; } // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. } + + // use NfcA APIs to access the found tag. if (isNfcATag) { - var nfcA = tag.getNfcATag(taginfo); + var nfcA; + try { + nfcA = tag.getNfcATag(taginfo); + } catch (error) { + console.log("tag.getNfcATag catched error: " + error); + } + // Other code to read or write this tag. + } + + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(taginfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } // Other code to read or write this tag. } - // use the same code to handle "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as, - // var isoDep = tag.getIsoDepTag(taginfo); + // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -156,78 +184,122 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| -## tag.getIsoDepTag9+ +## tag.getIsoDep9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) +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. -**Required permissions**: ohos.permission.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** | **Type**| **Description** | | ---------- | ------------------| | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.| -## tag.getNdefTag9+ +**Error codes** -getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +## tag.getNdef9+ -**Required permissions**: ohos.permission.NFC_TAG +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 +**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** | | ---------| -------------- | | [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.| -## tag.getMifareClassicTag9+ +**Error codes** -getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareClassic9+ + +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) + +Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. **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** | **Type**| **Description** | | ----------------- | ------------------------| | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| -## tag.getMifareUltralightTag9+ +**Error codes** -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareUltralight9+ + +getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) + +Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. **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** | **Type**| **Description** | | -------------------- | ---------------------------| | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.| -## tag.getNdefFormatableTag9+ +**Error codes** -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getNdefFormatable9+ + +getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) + +Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. **System capability**: SystemCapability.Communication.NFC.Core @@ -237,89 +309,376 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar | ------------------ | --------------------------| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** 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.getTagInfo9+ -getTagInfo(want: Want): [TagInfo](#taginfo) +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**. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched. | + **Return value** | **Type**| **Description** | | ------------------ | --------------------------| | [TagInfo](#taginfo) | **TagInfo** object obtained.| -## TagInfo -Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. +## tag.ndef.makeUriRecord9+ -**Required permissions**: ohos.permission.NFC_TAG +makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified URI. **System capability**: SystemCapability.Communication.NFC.Core -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| uid9+ | number[] | Tag unique identifier (UID). Each number of the UID is a hexadecimal number ranging from **0x00** to **0xFF**.| -| technology9+ | number[] | Supported technologies. Each number is a constant indicating the supported technology.| -| supportedProfiles | number[] | Supported technologies. This parameter is not supported since API version 9 and is replaced by **technology**.| +**Parameters** -## NdefRecord9+ -Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | Yes| Data to write to the NDEF record.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let uri = "https://gitee.com/openharmony"; // change it to be correct. + let ndefRecord = tag.ndef.makeUriRecord(uri); + if (ndefRecord != undefined) { + console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeUriRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.makeTextRecord9+ + +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| text | string | Yes | Text to write to the NDEF record.| +| locale | string | Yes | Encoding mode of the text.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let text = "Hello World"; // change it to be correct. + let locale = "en"; // change it to be correct. + let ndefRecord = tag.ndef.makeTextRecord(text, locale); + if (ndefRecord != undefined) { + console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeTextRecord catched busiError: " + busiError); +} +``` + + +## tag.ndef.makeMimeRecord9+ + +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.| +| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let mimeType = "text/plain"; // change it to be correct. + let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeMimeRecord(mimeType, mimeData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); +} +``` +## tag.ndef.makeExternalRecord9+ + +makeExternalRecord(domainName: string, type: string, externalData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on application-specific data. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications.| +| type | string | Yes | Type of the application data.| +| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let domainName = "ohos.nfc.application"; // change it to be correct. + let type = "test"; // change it to be correct. + let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeExternalRecord(domainName, type, externalData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.messageToBytes9+ + +messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): number[]; + +Converts an NDEF message to bytes. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} + +try { + let rawData2 = tag.ndef.messageToBytes(ndefMessage); + console.log("ndefMessage messageToBytes rawData2: " + rawData2); +} catch (busiError) { + console.log("ndefMessage messageToBytes catched busiError: " + busiError); +} +``` +## tag.ndef.createNdefMessage9+ + +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 + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | number[] | Yes| Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## tag.ndef.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from the NDEF records list. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let uriRecord = tag.ndef.makeUriRecord("https://gitee.com/openharmony"); +let textRecord = tag.ndef.makeTextRecord("Hello World", "en"); +let ndefRecords = [uriRecord, textRecord]; +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(ndefRecords); + console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## TagInfo + +Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. + +**System capability**: SystemCapability.Communication.NFC.Core **Required permissions**: ohos.permission.NFC_TAG +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| 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.| +| 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 -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| tnf | number | Type name field (TNF) of an NDEF record.| -| rtdType| number[] | Record type definition (RTD) of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| -| id | number[] | ID of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| -| payload | number[] | Payload of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| tnf | number | Yes| No| Type name field (TNF) of the NDEF record.| +| rtdType| number[] | Yes| No| Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| id | number[] | Yes| No| NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| payload | number[] | Yes| No| NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| ## Technology Type Definition Enumerates the tag technology types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | NFC_A | 1 | NFC-A (ISO 14443-3A).| -| NFC_B | 2 | NFC-A (ISO 14443-3B).| +| NFC_B | 2 | NFC-B (ISO 14443-3B).| | ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| | NFC_F | 4 | NFC-F (JIS 6319-4).| | NFC_V | 5 | NFC-V (ISO 15693).| | NDEF | 6 | NDEF.| +| NDEF_FORMATABLE9+ | 7 | NDEF formattable.| | MIFARE_CLASSIC | 8 | MIFARE Classic.| | MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.| -| NDEF_FORMATABLE9+ | 10 | NDEF formattable.| ## TnfType9+ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | TNF_EMPTY | 0x0 | Empty.| -| TNF_WELL_KNOWN | 0x01 | NFC Forum Well Known Type [NFC RTD].| -| TNF_MEDIA | 0x02 | Media-type as defined in RFC 2046 [RFC 2046].| -| TNF_ABSOLUTE_URI | 0x03 | Absolute URI as defined in RFC 3986 [RFC 3986].| -| TNF_EXT_APP | 0x04 | NFC Forum external type [NFC RTD].| -| TNF_UNKNOWN | 0x05 | Unknown.| -| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3).| +| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD].| +| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].| +| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD].| +| TNF_UNKNOWN | 0x5 | Unknown.| +| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*).| ## NDEF Record RTD Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | RTD_TEXT9+ | [0x54] | NDEF record of the text type.| @@ -328,36 +687,33 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ## NfcForumType9+ Enumerates the NFC Forum tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.| | NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.| | NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.| | NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.| -| MIFARE_CLASSIC | 101 | MIFARE Classic type.| +| MIFARE_CLASSIC | 101 | MIFARE Classic.| ## MifareClassicType9+ Enumerates the MIFARE Classic tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | Unknown type.| -| TYPE_CLASSIC | 0 | MIFARE Classic.| -| TYPE_PLUS | 1 | MIFARE Plus.| -| TYPE_PRO | 2 | MIFARE Pro.| +| TYPE_UNKNOWN | 0 | Unknown type.| +| TYPE_CLASSIC | 1 | MIFARE Classic.| +| TYPE_PLUS | 2 | MIFARE Plus.| +| TYPE_PRO | 3 | MIFARE Pro.| ## MifareClassicSize9+ -Enumerates the storage sizes of MIFARE Classic tags. - -**Required permissions**: ohos.permission.NFC_TAG +Enumerates the sizes of MIFARE Classic tags. **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| @@ -365,15 +721,14 @@ Enumerates the storage sizes of MIFARE Classic tags. | MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| | MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| -### MifareUltralightType9+ +## MifareUltralightType9+ Enumerates the MIFARE Ultralight tag types. -**Required permissions**: ohos.permission.NFC_TAG - **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | Unknown type.| +| 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 9817e5fd5c1f2a7f797f2c20fa7b6eff18dc25a5..e28864fc7bd2002838b7ae982bcb7b5269e2c086 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1,11 +1,12 @@ -# NFC Tag Technologies +# nfctech The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. > **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** +## Modules to Import ```js import tag from '@ohos.nfc.tag'; @@ -13,11 +14,11 @@ import tag from '@ohos.nfc.tag'; ## NfcATag -Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-A (ISO 14443-3A) properties and perform I/O operations on a tag. This class inherits from **[TagSession](js-apis-tagSession.md)**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcATag**. +The following describes the unique APIs of **NfcATag**. ### NfcATag.getSak @@ -40,8 +41,7 @@ Obtains the SAK value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. - +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let sak = nfcA.getSak(); console.log("nfcA sak: " + sak); ``` @@ -67,18 +67,18 @@ Obtains the ATQA value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let atqa = nfcA.getAtqa(); console.log("nfcA atqa: " + atqa); ``` ## NfcBTag -Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-B (ISO 14443-3B) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcBTag**. +The following describes the unique APIs of **NfcBTag**. ### NfcBTag.getRespAppData @@ -94,14 +94,14 @@ Obtains the application data of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Application data obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respAppData = nfcB.getRespAppData(); console.log("nfcB respAppData: " + respAppData); ``` @@ -120,25 +120,25 @@ Obtains the protocol information of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Protocol information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respProtocol = nfcB.getRespProtocol(); console.log("nfcB respProtocol: " + respProtocol); ``` ## NfcFTag -Provides access to NFC-F (JIS 6319-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-F (JIS 6319-4) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcFTag**. +The following describes the unique APIs of **NfcFTag**. ### NfcFTag.getSystemCode @@ -154,14 +154,14 @@ Obtains the system code from this NFC-F tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | System code obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let systemCode = nfcF.getSystemCode(); console.log("nfcF systemCode: " + systemCode); ``` @@ -174,31 +174,31 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | PMm information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let pmm = nfcF.getPmm(); console.log("nfcF pmm: " + pmm); ``` ## NfcVTag -Provides access to NFC-V (ISO 15693) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-V (ISO 15693) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcVTag**. +The following describes the unique APIs of **NfcVTag**. ### NfcvTag.getResponseFlags @@ -208,20 +208,20 @@ Obtains the response flags from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | Response flags obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let responseFlags = nfcV.getResponseFlags(); console.log("nfcV responseFlags: " + responseFlags); ``` @@ -234,54 +234,52 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | DSFID obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let dsfId = nfcV.getDsfId(); console.log("nfcV dsfId: " + dsfId); ``` ## IsoDepTag9+ -Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access ISO-DEP (ISO 14443-4) properties and I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **IsoDepTag**. +The following describes the unique APIs of **IsoDepTag**. ### IsoDepTag.getHistoricalBytes9+ getHistoricalBytes(): number[] -Obtains the historical bytes of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +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 +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Historical bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-B technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let historicalBytes = isoDep.getHistoricalBytes(); console.log("isoDep historicalBytes: " + historicalBytes); ``` @@ -290,24 +288,22 @@ console.log("isoDep historicalBytes: " + historicalBytes); getHiLayerResponse(): number[] -Obtains the HiLayer response of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +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 +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Higher-layer response bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-A technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let hiLayerResponse = isoDep.getHiLayerResponse(); console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` @@ -320,7 +316,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -328,18 +324,39 @@ Checks whether an extended application protocol data unit (APDU) is supported. T | ------------------ | --------------------------| | Promise<boolean> | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported() - .then((data) => { - console.log("isoDep isExtendedApduSupported data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported().then((response) => { + console.log("isoDep isExtendedApduSupported Promise response: " + response); }).catch((err)=> { - console.log("isoDep isExtendedApduSupported err: " + err); + console.log("isoDep isExtendedApduSupported Promise err: " + err); }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError); +} + ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -350,7 +367,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 +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -358,251 +375,159 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| -```js -import tag from '@ohos.nfc.tag'; - -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported((err, data)=> { - if (err) { - console.log("isoDep isExtendedApduSupported err: " + err); - } else { - console.log("isoDep isExtendedApduSupported data: " + data); - } -}); -``` - -## NdefTag9+ - -Provides access to the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. - -**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - -The following describes the unique interfaces of **NdefTag**. - -### NdefTag.createNdefMessage9+ - -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) +**Error codes** -Creates an NDEF message using raw bytes. +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| data | number[] | Yes| Raw bytes used to create the message. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| - -**Return value** - -| **Type**| **Description** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. -let ndefMessage = ndef.createNdefMessage(rawData); -console.log("ndef ndefMessage: " + ndefMessage); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported((err, response)=> { + if (err) { + console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err); + } else { + console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError); +} ``` ## NdefMessage9+ ### NdefMessage.getNdefRecords9+ -getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] +getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] Obtains all NDEF records. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = ndef.getNdefRecords(); +// Obtain ndefMessage from tag.ndef.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = tag.ndef.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +let ndefRecords = ndefMessage.getNdefRecords(); console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -### NdefTag.createNdefMessage9+ - -createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) - -Creates an NDEF message using the NDEF records. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF records used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Return value** - -| **Type**| **Description** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Example** +## NdefTag9+ -```js -import tag from '@ohos.nfc.tag'; +Provides APIs to access the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = [ - // record format: tnf, rtdType, id, payload - // 1st record: - {tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]}, +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - // 2nd record: - {tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]}, - - // other record if has one ... -]; -let ndefMessage = ndef.createNdefMessage(ndefRecords); -console.log("ndef ndefMessage: " + ndefMessage); -``` +The following describes the unique APIs of **NdefTag**. ### NdefTag.getNdefTagType9+ -getNdefTagType(): NfcForumType +getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) -Obtains the type of this NDEF tag. +Obtains the NDEF tag type. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| +| [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTagType = ndef.getNdefTagType(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefTagType = ndefTag.getNdefTagType(); console.log("ndef ndefTagType: " + ndefTagType); ``` ### NdefTag.getNdefMessage9+ -getNdefMessage(): NdefMessage +getNdefMessage(): [NdefMessage](#ndefmessage9) -Obtains the NDEF message. +Obtains the NDEF message from this NDEF tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** - ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.getNdefMessage(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefMessage = ndefTag.getNdefMessage(); console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ -isNdefWritable(): Promise<boolean> - -Checks whether the NDEF tag is writable. This API uses a promise to return the result. +isNdefWritable(): boolean; -**Required permissions**: ohos.permission.NFC_TAG +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 +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise<boolean> | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| - -**Example** - -```js -import tag from '@ohos.nfc.tag'; - -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.isNdefWritable() - .then((data) => { - console.log("ndef isNdefWritable data: " + data); - }).catch((err)=> { - console.log("ndef isNdefWritable err: " + err); - }); -``` - -### NdefTag.isNdefWritable9+ - -isNdefWritable(callback: AsyncCallback<boolean>): void; - -Checks whether the NDEF tag is writable. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| +| boolean | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.isNdefWritable((err, data)=> { - if (err) { - console.log("ndef isNdefWritable err: " + err); - } else { - console.log("ndef isNdefWritable data: " + data); - } -}); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var isWritable = ndefTag.isNdefWritable(); +console.log("ndef isNdefWritable: " + isWritable); ``` ### NdefTag.readNdef9+ -readNdef(): Promise\ +readNdef(): Promise\<[NdefMessage](#ndefmessage9)> Reads the NDEF message from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -610,18 +535,38 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | ------------------ | --------------------------| | Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef() - .then((data) => { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.readNdef().then((ndefmessage) => { + console.log("ndef readNdef Promise ndefmessage: " + ndefmessage); }).catch((err)=> { - console.log("ndef readNdef err: " + err); + console.log("ndef readNdef Promise err: " + err); }); +} catch (busiError) { + console.log("ndef readNdef Promise catched busiError: " + busiError); +} ``` ### NdefTag.readNdef9+ @@ -632,38 +577,59 @@ 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 +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the NDEF message read.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef((err, data)=> { - if (err) { - console.log("ndef readNdef err: " + err); - } else { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.readNdef((err, ndefmessage)=> { + if (err) { + console.log("ndef readNdef AsyncCallback err: " + err); + } else { + console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage); + } + }); +} catch (busiError) { + console.log("ndef readNdef AsyncCallback catched busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage): Promise\; +writeNdef(msg: NdefMessage): Promise\; 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 +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -671,59 +637,97 @@ Writes an NDEF message to this tag. This API uses a promise to return the result | -------- | ----------------------- | ---- | -------------------------------------- | | msg | NdefMessage | Yes | NDEF message to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) -ndef.writeNdef(ndefMessage) - .then((data) => { - console.log("ndef writeNdef data: " + data); +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.writeNdef(ndefMessage).then(() => { + console.log("ndef writeNdef Promise success."); }).catch((err)=> { console.log("ndef writeNdef err: " + err); }); +} catch (busiError) { + console.log("ndef writeNdef Promise catch busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage, callback: AsyncCallback\): void +writeNdef(msg: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | Yes | NDEF message to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| msg | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. -ndef.writeNdef(ndefMessage, (err, data)=> { - if (err) { - console.log("ndef writeNdef err: " + err); - } else { - console.log("ndef writeNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.writeNdef(ndefMessage, (err)=> { + if (err) { + console.log("ndef writeNdef AsyncCallback err: " + err); + } else { + console.log("ndef writeNdef AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.canSetReadOnly9+ @@ -734,7 +738,7 @@ Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -742,92 +746,133 @@ Checks whether this NDEF tag can be set to read-only. | ------------------ | --------------------------| | boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -var canSetReadOnly = ndef.canSetReadOnly(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var canSetReadOnly = ndefTag.canSetReadOnly(); console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ -setReadOnly(): Promise\ +setReadOnly(): Promise\ 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 +**System capability**: SystemCapability.Communication.NFC.Core -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly() - .then((data) => { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.setReadOnly().then(() => { + console.log("ndef setReadOnly Promise success."); }).catch((err)=> { - console.log("ndef setReadOnly err: " + err); + console.log("ndef setReadOnly Promise err: " + err); }); +} catch (busiError) { + console.log("ndef setReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback\): void +setReadOnly(callback: AsyncCallback\): void Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly((err, data)=> { - if (err) { - console.log("ndef setReadOnly err: " + err); - } else { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.setReadOnly((err)=> { + if (err) { + console.log("ndef setReadOnly AsyncCallback err: " + err); + } else { + console.log("ndef setReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.getNdefTagTypeString9+ -getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string - -Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. +getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -**Required permissions**: ohos.permission.NFC_TAG +Converts an NFC Forum Type tag to a string defined in the NFC Forum. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| +| type | [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| **Return value** @@ -840,110 +885,149 @@ Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); -console.log("ndef ndefTypeString: " + ndefTypeString); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +try { + let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); + console.log("ndef ndefTypeString: " + ndefTypeString); +} catch (busiError) { + console.log("ndef getNdefTagTypeString catch busiError: " + busiError); +} ``` ## MifareClassicTag9+ -Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Classic properties and perform I/O operations on a tag. This class inherits from [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareClassicTag**. +The following describes the unique APIs of **MifareClassicTag**. ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true); - .then((data) => { - console.log("mifareClassic authenticateSector data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true).then(() => { + console.log("mifareClassic authenticateSector Promise success."); }).catch((err)=> { - console.log("mifareClassic authenticateSector err: " + err); + console.log("mifareClassic authenticateSector Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| -**Example** +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let key = [0x04, 0x05, ....]; // change it to be correct key. -mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { - if (err) { - console.log("mifareClassic authenticateSector err: " + err); - } else { - console.log("mifareClassic authenticateSector data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> { + if (err) { + console.log("mifareClassic authenticateSector AsyncCallback err: " + err); + } else { + console.log("mifareClassic authenticateSector AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number): Promise\ -Reads a block (16 bytes) on the tag. This API uses a promise to return the result. +Reads a block (16 bytes) on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| **Return value** @@ -951,421 +1035,632 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul | ------------------ | --------------------------| | Promise\ | Promise used to return the block data read.| +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex).then((data) => { + console.log("mifareClassic readSingleBlock Promise data: " + data); + }).catch((err)=> { + console.log("mifareClassic readSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. +Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| 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.| +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.readSingleBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic readSingleBlock err: " + err); - } else { - console.log("mifareClassic readSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic readSingleBlock AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[]): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ -Writes data to a block on the tag. This API uses a promise to return the result. +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 +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => { + console.log("mifareClassic writeSingleBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic writeSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void -Writes data to a block on the tag. This API uses an asynchronous callback to return the result. +Writes data to a block on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let rawData = [0x0a, 0x14, ...]; // change it to be correct data. -mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { - if (err) { - console.log("mifareClassic writeSingleBlock err: " + err); - } else { - console.log("mifareClassic writeSingleBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> { + if (err) { + console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic writeSingleBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number): Promise\ +incrementBlock(blockIndex: number, value: number): Promise\ 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 +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic incrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic incrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void Increments a block with data. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic incrementBlock err: " + err); - } else { - console.log("mifareClassic incrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic incrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic incrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number): Promise\ +decrementBlock(blockIndex: number, value: number): Promise\ -Decrements a block with data. This API uses a promise to return the result. +Decrements a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic decrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic decrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -Decrements a block with data. This API uses an asynchronous callback to return the result. +Decrements a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let value = 0x20; // change it to be correct data. -mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { - if (err) { - console.log("mifareClassic decrementBlock err: " + err); - } else { - console.log("mifareClassic decrementBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic decrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic decrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number): Promise\ +transferToBlock(blockIndex: number): Promise\ -Copies data from the register to a block. This API uses a promise to return the result. +Transfers data from the temporary register to a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex).then(() => { + console.log("mifareClassic transferToBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic transferToBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number, callback: AsyncCallback\): void +transferToBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from the register to a block. This API uses an asynchronous callback to return the result. +Transfers data from the temporary register to a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.transferToBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic transferToBlock err: " + err); - } else { - console.log("mifareClassic transferToBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic transferToBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic transferToBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number): Promise\ +restoreFromBlock(blockIndex: number): Promise\ -Copies data from a block to the register. This API uses a promise to return the result. +Restores data in the temporary register from a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex) - .then((data) => { - console.log("mifareClassic restoreFromBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex).then(() => { + console.log("mifareClassic restoreFromBlock Promise success."); }).catch((err)=> { - console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + console.log("mifareClassic restoreFromBlock Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from a block to the register. This API uses an asynchronous callback to return the result. +Restores data in the temporary register from a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { - if (err) { - console.log("mifareClassic restoreFromBlock err: " + err); - } else { - console.log("mifareClassic restoreFromBlock data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic restoreFromBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorCount9+ @@ -1374,9 +1669,7 @@ getSectorCount(): number Obtains the number of sectors in this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1389,7 +1682,7 @@ Obtains the number of sectors in this MIFARE Classic tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let sectorCount = mifareClassic.getSectorCount(); console.log("mifareClassic sectorCount: " + sectorCount); ``` @@ -1400,15 +1693,13 @@ getBlockCountInSector(sectorIndex: number): number Obtains the number of blocks in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1421,33 +1712,37 @@ Obtains the number of blocks in a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockCountInSector = mifareClassic.getBlockCountInSector(); -console.log("mifareClassic blockCountInSector: " + blockCountInSector); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex); + console.log("mifareClassic blockCnt: " + blockCnt); +} catch (busiError) { + console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError); +} ``` ### MifareClassicTag.getType9+ -getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) +getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| +| [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let getType = mifareClassic.getType(); console.log("mifareClassic getType: " + getType); ``` @@ -1456,11 +1751,9 @@ console.log("mifareClassic getType: " + getType); getTagSize(): number -Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1473,7 +1766,7 @@ Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nf ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let tagSize = mifareClassic.getTagSize(); console.log("mifareClassic tagSize: " + tagSize); ``` @@ -1482,11 +1775,9 @@ console.log("mifareClassic tagSize: " + tagSize); isEmulatedTag(): boolean -Checks whether the tag is an emulated tag. +Checks whether it is an emulated tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1499,7 +1790,7 @@ Checks whether the tag is an emulated tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let isEmulatedTag = mifareClassic.isEmulatedTag(); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` @@ -1508,17 +1799,15 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); getBlockIndex(sectorIndex: number): number -Obtains the first block of a sector. +Obtains the index of the first block in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1531,27 +1820,30 @@ Obtains the first block of a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let sectorIndex = 1; // change it to be correct index. -let blockIndex = mifareClassic.getBlockIndex(sectorIndex); -console.log("mifareClassic blockIndex: " + blockIndex); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockIndex = mifareClassic.getBlockIndex(sectorIndex); + console.log("mifareClassic blockIndex: " + blockIndex); +} catch (busiError) { + console.log("mifareClassic getBlockIndex catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorIndex9+ getSectorIndex(blockIndex: number): number -Obtains the index of a sector that contains the specified block. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the index of a sector that holds the specified block. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block contained in the sector.| +| blockIndex | number | Yes| Index of the block. The block indexes start from **0**.| **Return value** @@ -1564,41 +1856,54 @@ Obtains the index of a sector that contains the specified block. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockIndex = 1; // change it to be correct index. -let sectorIndex = mifareClassic.getSectorIndex(blockIndex); -console.log("mifareClassic sectorIndex: " + sectorIndex); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let blockIndex = 1; // Change it as required. + let sectorIndex = mifareClassic.getSectorIndex(blockIndex); + console.log("mifareClassic sectorIndex: " + sectorIndex); +} catch (busiError) { + console.log("mifareClassic getSectorIndex catch busiError: " + busiError); +} ``` ## MifareUltralightTag9+ -Provides access to MIFARE Ultralight properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Ultralight properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareUltralightTag**. +The following describes the unique APIs of **MifareUltralightTag**. ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number): Promise\ -Reads multiple pages (4 bytes per page). This API uses a promise to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------ | -| pageIndex | number | Yes | Indexes of the pages to read.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the data read.| +| Promise\ | Promise used to return the data read, which is 16 bytes in total.| + +**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** @@ -1606,207 +1911,286 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex) - .then((data) => { - console.log("mifareUltralight readMultiplePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex).then((data) => { + console.log("mifareUltralight readMultiplePages Promise data = " + data); }).catch((err)=> { - console.log("mifareUltralight readMultiplePages err: " + err); + console.log("mifareUltralight readMultiplePages Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError); +} ``` ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Indexes of the pages to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read, which is 16 bytes in total.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { - if (err) { - console.log("mifareUltralight readMultiplePages err: " + err); - } else { - console.log("mifareUltralight readMultiplePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err); + } else { + console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[]): Promise\ +writeSinglePage(pageIndex: number, data: number[]): Promise\ -Writes a page of data. This API uses a promise to return the result. +Writes one page (4 bytes) of data to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data) - .then((data) => { - console.log("mifareUltralight writeSinglePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => { + console.log("mifareUltralight writeSinglePage Promise success."); }).catch((err)=> { - console.log("mifareUltralight writeSinglePages err: " + err); + console.log("mifareUltralight writeSinglePage Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void +writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\): void -Writes a page of data. This API uses an asynchronous callback to return the result. +Writes one page (4 bytes) of 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 +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------ | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| -| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| +| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| + +**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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. -let pageIndex = 1; // change it to be correct index. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { - if (err) { - console.log("mifareUltralight writeSinglePages err: " + err); - } else { - console.log("mifareUltralight writeSinglePages data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> { + if (err) { + console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err); + } else { + console.log("mifareUltralight writeSinglePage AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError); +} ``` ### MifareUltralightTag.getType9+ -getType(): MifareUltralightType +getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) -Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the type of this MIFARE Ultralight tag. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| +| [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) | Type of the MIFARE Ultralight tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. let getType = mifareClassic.getType(); console.log("mifareUltralight getType: " + getType); ``` ## NdefFormatableTag9+ -Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. +Provides APIs for formatting NDEF formattable tags. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NdefFormatableTag**. +The following describes the unique APIs of **NdefFormatableTag**. ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9)): Promise\ +format(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage).then(() => { + console.log("ndefFormatable format Promise success."); + }).catch((err)=> { + console.log("ndefFormatable format Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable format Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -1818,7 +2202,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1826,82 +2210,108 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.format(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable format err: " + err); - } else { - console.log("ndefFormatable format data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable format AsyncCallback err: " + err); + } else { + console.log("ndefFormatable format AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. +Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage).then(() => { + console.log("ndefFormatable formatReadOnly Promise success."); + }).catch((err)=> { + console.log("ndefFormatable formatReadOnly Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1909,16 +2319,29 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let data = [0x01, 0x02, ...]; // change it to be correct raw data. -let ndefmessage = ndef.createNdefMessage(data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. -ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { - if (err) { - console.log("ndefFormatable formatReadOnly err: " + err); - } else { - console.log("ndefFormatable formatReadOnly data: " + data); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err); + } else { + console.log("ndefFormatable formatReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 068e2a1ca6c4c01c2e69144354bd90b86302619a..f903401701e9f68ae6277a687215310f59afc34c 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,8 +1,9 @@ -# OS Account Management +# @ohos.account.osAccount The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. -> **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. @@ -2708,7 +2709,6 @@ 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 @@ -4280,17 +4280,12 @@ Register a PIN inputer. | ----------| ----------------------- | --- | -------------------------- | | inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.| -**Return value** - -| Type | Description | -| :------ | :-------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Error codes** | ID| Error Message | | -------- | --------------------------- | | 12300001 | System service exception. | +| 12300102 | Invalid inputer. | | 12300103 | Inputer already registered. | **Example** @@ -4299,8 +4294,8 @@ Register a PIN inputer. let password = new Uint8Array([0, 0, 0, 0, 0]); try { let result = pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); console.log('registerInputer result = ' + result); @@ -4327,6 +4322,91 @@ Unregisters this PIN inputer. pinAuth.unregisterInputer(); ``` +### InputerManager 10+ + +Provides APIs for managing credential inputers. + +### registerInputer10+ + +registerInputer(authType: AuthType, inputer: IInputer): void; + +Register a credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| +| inputer | [IInputer](#iinputer8) | Yes | Credential inputer to register.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300102 | Invalid authType or inputer. | +| 12300103 | The credential inputer has been registered. | +| 12300106 | Unsupported authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + let password = new Uint8Array([0, 0, 0, 0, 0]); + try { + InputerMgr.registerInputer(authType, { + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); + } + }); + console.log('registerInputer success.'); + } catch (e) { + console.log('registerInputer exception = ' + JSON.stringify(e)); + } + ``` + +### unregisterInputer10+ + +unregisterInputer(authType: AuthType): void; + +Unregisters this credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300002 | Invalid authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + try { + inputerMgr.unregisterInputer(authType); + console.log('unregisterInputer success.'); + } catch(err) { + console.log("unregisterInputer err:" + JSON.stringify(err)); + } + ``` + ## UserIdentityManager8+ Provides APIs for user identity management (IDM). @@ -4456,8 +4536,8 @@ Adds credential information, including the credential type, subtype, and token ( let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let pinAuth = new account_osAccount.PINAuth(); pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); let credentialInfo = { @@ -4470,12 +4550,12 @@ Adds credential information, including the credential type, subtype, and token ( try { userIDM.addCredential(credentialInfo, { onResult: (result, extraInfo) => { - console.log('updateCredential result = ' + result); - console.log('updateCredential extraInfo = ' + extraInfo); + console.log('addCredential result = ' + result); + console.log('addCredential extraInfo = ' + extraInfo); } }); } catch (e) { - console.log('updateCredential exception = ' + JSON.stringify(e)); + console.log('addCredential exception = ' + JSON.stringify(e)); } }); ``` @@ -4520,8 +4600,8 @@ Updates credential information. This API uses a callback to return the result. token: null }; pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); userIDM.openSession((err, challenge) => { @@ -4820,7 +4900,7 @@ Provides callbacks for PIN operations. ### onSetData8+ -onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; +onSetData: (authSubType: AuthSubType, data: Uint8Array) => void; **System API**: This is a system API. @@ -4832,7 +4912,7 @@ Called to set data in a PIN operation. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | -| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | +| authSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | | data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.| **Example** @@ -4840,11 +4920,11 @@ Called to set data in a PIN operation. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -4852,13 +4932,13 @@ Called to set data in a PIN operation. ## IInputer8+ -Provides callbacks for the PIN input box. +Provides callbacks for credential inputers. **System API**: This is a system API. ### onGetData8+ -onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; +onGetData: (authSubType: AuthSubType, callback: IInputData) => void; Called to obtain data. @@ -4877,11 +4957,11 @@ Called to obtain data. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -5157,6 +5237,8 @@ Enumerates the authentication credential types. | ----- | ----- | ---------------- | | PIN | 1 | PIN authentication.| | FACE | 2 | Facial authentication.| +| FINGERPRINT10+ | 4 | Fingerprint authentication.| +| DOMAIN10+ | 1024 | Domain authentication.| ## AuthSubType8+ @@ -5170,9 +5252,10 @@ Enumerates the authentication credential subtypes. | ---------- | ----- | ------------------ | | PIN_SIX | 10000 | Six-digit PIN. | | PIN_NUMBER | 10001 | Custom PIN.| -| PIN_MIXED | 10002 | Custom mixed credential.| +| PIN_MIXED | 10002 | Custom mixed credentials.| | FACE_2D | 20000 | 2D face credential. | | FACE_3D | 20001 | 3D face credential. | +| DOMAIN_MIXED10+ | 10240001 | Mixed domain authentication credentials. | ## AuthTrustLevel8+ diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index ad6e437f09767e362b2787f5ee78dd58d1a65165..1c78452681d08db91a4aa3ee4cf2aea785072191 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,10 +1,9 @@ # Power Manager -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status. +> **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 @@ -12,42 +11,294 @@ The Power Manager module provides APIs for rebooting and shutting down the syste import power from '@ohos.power'; ``` -## System Capability - -SystemCapability.PowerManager.PowerManager.Core - +## power.shutdown -## power.shutdownDevice - -shutdownDevice(reason: string): void +shutdown(reason: string): void Shuts down the system. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permission**: ohos.permission.REBOOT +**System capability:** SystemCapability.PowerManager.PowerManager.Core + **Parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ----- | | reason | string | Yes | Reason for system shutdown.| +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + **Example** ```js -power.shutdownDevice("shutdown_test"); -console.info('power_shutdown_device_test success') +try { + power.shutdown('shutdown_test'); +} catch(err) { + console.error('shutdown failed, err: ' + err); +} ``` +## power.reboot9+ + +reboot(reason: string): void + +Reboots the system. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.REBOOT + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| reason | string | Yes | Reason for system reboot.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.reboot('reboot_test'); +} catch(err) { + console.error('reboot failed, err: ' + err); +} +``` + +## power.isActive9+ + +isActive(): boolean + +Checks whether the current device is active. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var isActive = power.isActive(); + console.info('power is active: ' + isActive); +} catch(err) { + console.error('check active status failed, err: ' + err); +} +``` + +## power.wakeup9+ + +wakeup(detail: string): void + +Wakes up a device. + +**System API**: This is a system API. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| detail | string | Yes | Reason for wakeup.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.wakeup('wakeup_test'); +} catch(err) { + console.error('wakeup failed, err: ' + err); +} +``` + +## power.suspend9+ + +suspend(): void + +Hibernates a device. + +**System API**: This is a system API. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.suspend(); +} catch(err) { + console.error('suspend failed, err: ' + err); +} +``` -## power.rebootDevice +## power.getPowerMode9+ + +getPowerMode(): DevicePowerMode + +Obtains the power mode of this device. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------- | +| [DevicePowerMode](#devicepowermode9) | Power mode.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var mode = power.getPowerMode(); + console.info('power mode: ' + mode); +} catch(err) { + console.error('get power mode failed, err: ' + err); +} +``` + +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode, callback: AsyncCallback<void>): void + +Sets the power mode of this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.POWER_OPTIMIZATION + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the power mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE, err => { + if (typeof err === 'undefined') { + console.info('set power mode to MODE_PERFORMANCE'); + } else { + console.error('set power mode failed, err: ' + err); + } +}); +``` + +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode): Promise<void> + +Sets the power mode of this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.POWER_OPTIMIZATION + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ---------- | +| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) +.then(() => { + console.info('set power mode to MODE_PERFORMANCE'); +}) +.catch(err => { + console.error('set power mode failed, err: ' + err); +}); +``` + +## power.rebootDevice(deprecated) rebootDevice(reason: string): void +> This API is deprecated since API version 9. You are advised to use [power.reboot](#powerreboot9) instead. + Reboots the system. -**Required permission**: ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_RECOVERY (to reboot and enter the recovery or updater mode) +**Required permission**: ohos.permission.REBOOT + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** @@ -58,55 +309,73 @@ Reboots the system. **Example** ```js -power.rebootDevice("reboot_test"); -console.info('power_reboot_device_test success') +power.rebootDevice('reboot_test'); ``` - -## power.isScreenOn +## power.isScreenOn(deprecated) isScreenOn(callback: AsyncCallback<boolean>): void -Checks the screen status of the current device. +> 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. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the screen status obtained, where the value **true** indicates on and the value **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** ```js -power.isScreenOn((error, screenOn) => { - if (typeof error === "undefined") { - console.info('screenOn status is ' + screenOn); +power.isScreenOn((err, data) => { + if (typeof err === 'undefined') { + console.info('screen on status is ' + data); } else { - console.log('error: ' + error); + console.error('check screen status failed, err: ' + err); } }) ``` - -## power.isScreenOn +## power.isScreenOn(deprecated) isScreenOn(): Promise<boolean> -Checks the screen status of the current device. +> 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. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Return value** -| Type | Description | -| ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Type | Description | +| ---------------------- | -------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| **Example** ```js power.isScreenOn() -.then(screenOn => { - console.info('screenOn status is ' + screenOn); +.then(data => { + console.info('screen on status is ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.error('check screen status failed, err: ' + err); }) ``` + +## DevicePowerMode9+ + +Enumerates power modes. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +| Name | Value | Description | +| ----------------------- | ---- | ---------------------- | +| MODE_NORMAL | 600 | Standard mode. It is the default value.| +| MODE_POWER_SAVE | 601 | Power saving mode. | +| MODE_PERFORMANCE | 602 | Performance mode. | +| MODE_EXTREME_POWER_SAVE | 603 | Ultra power saving mode. | diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index 59727e8c039dd23adc71b3a0b314e5664e8c9b34..318ba307995a44950461ae3b9a43e92743c37364 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -1,4 +1,4 @@ -# Obtaining Process Information +# @ohos.process (Obtaining Process Information) > **NOTE** > @@ -18,13 +18,13 @@ import process from '@ohos.process'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| egid | number | Yes| No| Effective group identifier (EGID) of a process. This is a system API and cannot be called by third-party applications.| -| euid | number | Yes| No| Effective user identifier (EUID) of a process. This is a system API and cannot be called by third-party applications.| -| gid | number | Yes| No| Group identifier (GID) of a process. This is a system API and cannot be called by third-party applications.| +| egid | number | Yes| No| Effective group identifier (EGID) of a process.
**System API**: This is a system API.
It is used only to test applications.| +| euid | number | Yes| No| Effective user identifier (EUID) of a process.
**System API**: This is a system API.
It is used only to test applications.| +| gid | number | Yes| No| Group identifier (GID) of a process.
**System API**: This is a system API.
It is used only to test applications.| | uid | number | Yes| No| User identifier (UID) of a process.| -| groups | number[] | Yes| No| Array with supplementary group IDs. This is a system API and cannot be called by third-party applications.| +| groups | number[] | Yes| No| Array with supplementary group IDs.
**System API**: This is a system API.
It is used only to test applications.| | pid | number | Yes| No| Process ID (PID) of a process.| -| ppid | number | Yes| No| Parent process ID (PPID) of a process. This is a system API and cannot be called by third-party applications.| +| ppid | number | Yes| No| Parent process ID (PPID) of a process.
**System API**: This is a system API.
It is used only to test applications.| | tid8+ | number | Yes| No| Thread ID (TID) of a process.| @@ -32,7 +32,7 @@ import process from '@ohos.process'; Provides APIs for throwing exceptions during the addition of a process. -### process.isAppUid9+ +### isAppUid9+ isAppUid(v: number): boolean @@ -60,7 +60,7 @@ let result = pro.isAppUid(688); ``` -### process.getUidForName9+ +### getUidForName9+ getUidForName(v: string): number @@ -88,7 +88,7 @@ let pres = pro .getUidForName("tool"); ``` -### process.getThreadPriority9+ +### getThreadPriority9+ getThreadPriority(v: number): number @@ -117,7 +117,7 @@ let pres = pro.getThreadPriority(tid); ``` -### process.getSystemConfig9+ +### getSystemConfig9+ getSystemConfig(name: number): number @@ -146,7 +146,7 @@ let pres = pro.getSystemConfig(_SC_ARG_MAX); ``` -### process.getEnvironmentVar9+ +### getEnvironmentVar9+ getEnvironmentVar(name: string): string @@ -174,7 +174,7 @@ let pres = pro.getEnvironmentVar("PATH"); ``` -### process.exit9+ +### exit9+ exit(code: number): void @@ -198,7 +198,7 @@ pro.exit(0); ``` -### process.kill9+ +### kill9+ kill(signal: number, pid: number): boolean @@ -238,10 +238,10 @@ Allows a process to obtain the standard input and output of its child processes, | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| PID of the child process. This is a system API and cannot be called by third-party applications.| -| ppid | number | Yes| No| PPID of the child process. This is a system API and cannot be called by third-party applications.| -| exitCode | number | Yes| No| Exit code of the child process. This is a system API and cannot be called by third-party applications.| -| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it. This is a system API and cannot be called by third-party applications.| +| pid | number | Yes| No| PID of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| ppid | number | Yes| No| PPID of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| exitCode | number | Yes| No| Exit code of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it.
**System API**: This is a system API.
It is used only to test applications.| ### wait @@ -250,7 +250,9 @@ wait(): Promise<number> Waits until the child process ends. This method uses a promise to return the exit code of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -277,7 +279,9 @@ getOutput(): Promise<Uint8Array> Obtains the standard output of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -304,7 +308,9 @@ getErrorOutput(): Promise<Uint8Array> Obtains the standard error output of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -331,7 +337,9 @@ close(): void Closes the child process in running. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -349,7 +357,9 @@ kill(signal: number | string): void Sends a signal to the specified child process to terminate it. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -593,7 +603,9 @@ runCmd(command: string, options?: { timeout?: number, killSignal?: number | stri Forks a new process to run a shell command and returns the **ChildProcess** object. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -609,7 +621,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.| -| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| +| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| | maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.| **Return value** @@ -650,7 +662,9 @@ on(type: string, listener: EventListener): void Stores the events triggered by the user. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -682,7 +696,9 @@ off(type: string): boolean Deletes the event stored by the user. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -737,7 +753,9 @@ cwd(): string Obtains the working directory of this process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -754,7 +772,9 @@ chdir(dir: string): void Changes the working directory of this process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang 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 f83329d727dd9c95d076415717d1e765665326b8..b423c712999053c8a00d0b8503525cd03ce1cdf8 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# Device Usage Statistics +# @ohos.resourceschedule.usageStatistics (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -703,7 +703,7 @@ Queries FA usage records. This API uses an asynchronous callback to return a max | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of 1000 FA usage records.| +| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of **maxNum** FA usage records.| **Error codes** diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 50e5cfe7cc8bdb66fc5fddce209a47e684d8bc11..94757432a9c16fa471fb98629b63387594542e65 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,9 +1,11 @@ -# RPC +# @ohos.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**
+> **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. +> > This module supports return of error codes since API version 9. @@ -24,7 +26,7 @@ The APIs of this module return exceptions since API version 9. The following tab | ------------------------------------- | ------- | --------------------------------------------- | | CHECK_PARAM_ERROR | 401 | Parameter check failed. | | OS_MMAP_ERROR | 1900001 | Failed to call mmap. | - | OS_IOCTL_ERROR | 1900002 | Failed to execute **ioctl** with the shared memory file descriptor.| + | OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.| | WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | | READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | | ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | @@ -123,7 +125,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode readRemoteObject(): IRemoteObject -Reads a remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. +Reads the remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -405,7 +407,7 @@ Obtains the read position of this **MessageSequence** object. | Type| Description| | ------ | ------ | - | number | Current read position of the **MessageSequence** object.| + | number | Read position obtained.| **Example** @@ -427,7 +429,7 @@ Obtains the write position of this **MessageSequence** object. | Type| Description| | ------ | ----- | - | number | Current write position of the **MessageSequence** object.| + | number | Write position obtained.| **Example** @@ -504,7 +506,7 @@ Moves the write pointer to the specified position. writeByte(val: number): void -Writes a Byte value to this **MessageSequence** object. +Writes a byte value to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -538,7 +540,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode readByte(): number -Reads the Byte value from this **MessageSequence** object. +Reads the byte value from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -2856,7 +2858,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode readFileDescriptor(): number -Reads a file descriptor from this **MessageSequence** object. +Reads the file descriptor from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core @@ -4017,7 +4019,7 @@ Writes a string to this **MessageParcel** object. readString(): string -Reads a string from this **MessageParcel** object. +Reads the string from this **MessageParcel** object. **System capability**: SystemCapability.Communication.IPC.Core diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index 1b25989357a2e101b5b6e95d05b5ca60dab2fb6f..e3718c5878ccae3e63f8bdfae8b37061599fffda 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,95 +1,205 @@ -# Running Lock +# RunningLock -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The RunningLock module provides APIs for creating, querying, holding, and releasing running locks. + +> **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 Running Lock module provides APIs for creating, querying, holding, and releasing running locks. +## Modules to Import +```js +import runningLock from '@ohos.runningLock'; +``` -## Modules to Import +## runningLock.isSupported9+ + +isSupported(type: RunningLockType): boolean; + +Checks whether a specified type of **RunningLock** is supported. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------- | +| boolean | The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** +```js +try { + var isSupported = runningLock.isSupported(runningLock.RunningLockType.BACKGROUND); + console.info('BACKGROUND type supported: ' + isSupported); +} catch(err) { + console.error('check supported failed, err: ' + err); +} ``` -import runningLock from '@ohos.runningLock'; + +## runningLock.create9+ + +create(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void + +Creates a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created. | +| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If a lock is successfully created, **err** is **undefined** and **data** is the created **RunningLock**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); + } else { + console.error('create running lock failed, err: ' + err); + } +}); ``` +## runningLock.create9+ -## RunningLockType +create(name: string, type: RunningLockType): Promise<RunningLock> -Enumerates the types of **RunningLock** objects. +Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -| Name | Default Value | Description | -| ------------------------ | ---- | ------------------- | -| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | -| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| +**Required permission:** ohos.permission.RUNNING_LOCK +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| + +**Return value** + +| Type | Description | +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise used to return the result.| -## isRunningLockTypeSupported +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.error('create running lock failed, error: ' + err); +}); +``` + +## runningLock.isRunningLockTypeSupported(deprecated) isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void -Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. +> 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. **System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| type | RunningLockType | Yes | Type of the **RunningLock** object. | -| callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (error, supported) => { - if (typeof error === "undefined") { - console.info('BACKGROUND support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (err, data) => { + if (typeof err === 'undefined') { + console.info('BACKGROUND lock support status: ' + data); } else { - console.log('error: ' + error); + console.log('check BACKGROUND lock support status failed, err: ' + err); } -}) +}); ``` +## runningLock.isRunningLockTypeSupported(deprecated) -## isRunningLockTypeSupported +isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> -isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> +> 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 function uses an asynchronous callback to return the result. +Checks whether a specified type of **RunningLock** is supported. This API uses a promise to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| ---- | --------------- | ---- | ---------- | -| type | RunningLockType | Yes | Type of the **RunningLock** object.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| -**Return Value** +**Return value** -| Type | Description | -| ---------------------- | ---------------------------------------- | -| Promise<boolean> | Promise used to asynchronously obtain the return value.
Return value: The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Type | Description | +| ---------------------- | ---------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| **Example** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL) -.then(supported => { - console.info('PROXIMITY_SCREEN_CONTROL support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND) +.then(data => { + console.info('BACKGROUND lock support status: ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.log('check BACKGROUND lock support status failed, err: ' + err); }); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void +> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. + Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -98,33 +208,30 @@ Creates a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| name | string | Yes | Name of the **RunningLock** object. | -| type | RunningLockType | Yes | Type of the **RunningLock** object to be created. | -| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to obtain the return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created. | +| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If a lock is successfully created, **err** is **undefined** and **data** is the created **RunningLock**. Otherwise, **err** is an error object.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND, (error, lockIns) => { - if (typeof error === "undefined") { - var used = lockIns.isUsed(); - console.info('runninglock is used: ' + used); - lockIns.lock(500); - used = lockIns.isUsed(); - console.info('after lock runninglock is used ' + used); +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); } else { - console.log('create runningLock test error: ' + error); + console.error('create running lock failed, err: ' + err); } -}) +}); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> +> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. + Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -133,39 +240,157 @@ Creates a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | --------------- | ---- | --------- | -| name | string | Yes | Name of the **RunningLock** object. | -| type | RunningLockType | Yes | Type of the **RunningLock** object to be created.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| -**Return Value** +**Return value** | Type | Description | -| ---------------------------------------- | ---------------------------------- | -| Promise<[RunningLock](#runninglock)> | Promise used to asynchronously obtain the returned **RunningLock** object.| +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise used to return the result.| **Example** +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.log('create running lock failed, err: ' + err); +}); ``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runninglock => { - console.info('create runningLock success'); + +## RunningLock + +Represents a **RunningLock** object. + +### hold9+ + +hold(timeout: number): void + +Locks and holds a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | Yes | Duration for locking and holding the **RunningLock** object, in ms.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.hold(500); + console.info('hold running lock success'); + } catch(err) { + console.error('hold running lock failed, err: ' + err); + } }) -.catch(error => { - console.log('create runningLock test error: ' + error); +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### unhold9+ + +unhold(): void + +Releases a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.unhold(); + console.info('unhold running lock success'); + } catch(err) { + console.error('unhold running lock failed, err: ' + err); + } }) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); ``` +### isHolding9+ -## RunningLock +isHolding(): boolean + +Checks the hold status of the **Runninglock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core -Defines a **RunningLock** object. +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| -### lock +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + var isHolding = lock.isHolding(); + console.info('check running lock holding status: ' + isHolding); + } catch(err) { + console.error('check running lock holding status failed, err: ' + err); + } +}) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### lock(deprecated) lock(timeout: number): void +> This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9) instead. + Locks and holds a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -174,29 +399,30 @@ Locks and holds a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | -------------------------- | -| timeout | number | No | Duration for locking and holding the **RunningLock** object, in ms.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | Yes | Duration for locking and holding the **RunningLock** object, in ms.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.lock(100) - console.info('create runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.lock(500); + console.info('create running lock and lock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### unlock +### unlock(deprecated) unlock(): void -Releases a **Runninglock** object. +> This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9) instead. + +Releases a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -204,40 +430,52 @@ Releases a **Runninglock** object. **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.unlock() - console.info('create and unLock runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.unlock(); + console.info('create running lock and unlock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### isUsed +### isUsed(deprecated) isUsed(): boolean -Checks the status of the **Runninglock** object. +> 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. **System capability:** SystemCapability.PowerManager.PowerManager.Core -**Return Value** -| Type | Description | -| ------- | ------------------------------------- | -| boolean | Returns **true** if the **Runninglock** object is held; returns **false** if the **Runninglock** object is released.| +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - var used = runningLock.isUsed() - console.info('runningLock used status: ' + used) +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + var isUsed = lock.isUsed(); + console.info('check running lock used status: ' + isUsed); }) -.catch(error => { - console.log('runningLock isUsed test error: ' + error) +.catch(err => { + console.error('check running lock used status failed, err: ' + err); }); ``` + +## RunningLockType + +Enumerates the types of **RunningLock** objects. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------------- | +| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | +| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| 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 7b577c8ee81c733cdb1aa1f2ccfcced87829f304..31959da80f23b90f54ea10883417eec202152d1a 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,9 +1,10 @@ -# Battery Level +# Battery Info -> ![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.batteryInfo`](js-apis-battery-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. +This 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. +> - 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 @@ -16,40 +17,46 @@ import battery from '@system.battery'; ## battery.getStatus -getStatus(Object): void +getStatus(options?: GetStatusOptions): void; Obtains the current charging state and battery level. **System capability**: SystemCapability.PowerManager.BatteryManager.Core -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the check result is obtained | -| fail | Function | No | Called when the check result fails to be obtained | -| complete | Function | No | Called when the execution is complete | - -The following value will be returned when the check result is obtained. - -| Name | Type | Description | -| -------- | -------- | -------- | -| charging | boolean | Whether the battery is being charged | -| level | number | Current battery level, which ranges from 0.00 to 1.00. | +| options | [GetStatusOptions](#getstatusoptions) | No| Object that contains the API calling result.| **Example** ```js -export default { - getStatus() { - battery.getStatus({ - success: function(data) { - console.log('success get battery level:' + data.level); - }, - fail: function(data, code) { - console.log('fail to get battery level code:' + code + ', data: ' + data); - }, - }); - }, -} -``` \ No newline at end of file +battery.getStatus({ + success: function(data) { + console.log('success get battery level:' + data.level); + }, + fail: function(data, code) { + console.error('fail to get battery level code:' + code + ', data: ' + data); + } +}); +``` + +## GetStatusOptions + +Object that contains the API calling result. + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## BatteryResponse + +Defines a response that returns the charging status and remaining power of the device. + +| Name| Type| Description| +| -------- | -------- | -------- | +| charging | boolean | Whether the battery is being charged.| +| level | number | Current battery level, which ranges from **0.00** to **1.00**.| 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 71e9b7072d03d8c25297cfd2c8f3c97c295097eb..2773c74397046c44784b65cc458be75eef8c21ea 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,8 +1,9 @@ # Screen Brightness -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +This 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. -> > - 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. @@ -16,7 +17,7 @@ import brightness from '@system.brightness'; ## brightness.getValue -getValue(Object): void +getValue(options?: GetBrightnessOptions): void Obtains the current screen brightness. @@ -24,39 +25,27 @@ Obtains the current screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete | - -The following values will be returned when the operation is successful. - -| Name | Type | Description | -| -------- | -------- | -------- | -| value | number | Screen brightness, which ranges from 1 to 255. | +| options | [GetBrightnessOptions](#getbrightnessoptions) | No | Options for obtaining the screen brightness.| **Example** -```js -export default { - getValue() { - brightness.getValue({ - success: function(data){ - console.log('success get brightness value:' + data.value); - }, - fail: function(data, code) { - console.log('get brightness fail, code: ' + code + ', data: ' + data); + ```js + brightness.getValue({ + success: function(data) { + console.log('success get brightness value:' + data.value); }, - }); - }, -} -``` + fail: function(data, code) { + console.error('get brightness fail, code: ' + code + ', data: ' + data); + } + }); + ``` ## brightness.setValue -setValue(Object): void +etValue(options?: SetBrightnessOptions): void Sets the screen brightness. @@ -64,35 +53,28 @@ Sets the screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes | Screen brightness. The value is an integer ranging from 1 to 255.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used. | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetBrightnessOptions](#setbrightnessoptions) | No | Options for setting the screen brightness.| **Example** -```js -export default { - setValue() { - brightness.setValue({ - value: 100, - success: function(){ - console.log('handling set brightness success.'); - }, - fail: function(data, code){ - console.log('handling set brightness value fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` + ```js + brightness.setValue({ + value: 100, + success: function() { + console.log('handling set brightness success.'); + }, + fail: function(data, code) { + console.error('handling set brightness value fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.getMode -getMode(Object): void +getMode(options?: GetBrightnessModeOptions: void Obtains the screen brightness adjustment mode. @@ -100,75 +82,57 @@ Obtains the screen brightness adjustment mode. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete | - -The following values will be returned when the operation is successful. - -| Name | Type | Description | -| -------- | -------- | -------- | -| mode | number | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | +| options | [GetBrightnessModeOptions](#getbrightnessmodeoptions) | No| Options for obtaining the screen brightness mode.| **Example** -```js -export default { - getMode() { - brightness.getMode({ - success: function(data){ - console.log('success get mode:' + data.mode); - }, - fail: function(data, code){ - console.log('handling get mode fail, code:' + code + ', data: ' + data); + ```js + brightness.getMode({ + success: function(data) { + console.log('success get mode:' + data.mode); }, - }); - }, -} -``` + fail: function(data, code){ + console.error('handling get mode fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.setMode -setMode(Object): void +setMode(options?: SetBrightnessModeOptions): void Sets the screen brightness adjustment mode. **System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** - -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mode | number | Yes | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetBrightnessModeOptions](#setbrightnessmodeoptions) | No | Options for setting the screen brightness mode.| **Example** -```js -export default { - setMode() { - brightness.setMode({ - mode: 1, - success: function(){ - console.log('handling set mode success.'); - }, - fail: function(data, code){ - console.log('handling set mode fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` + ```js + brightness.setMode({ + mode: 1, + success: function() { + console.log('handling set mode success.'); + }, + fail: function(data, code) { + console.error('handling set mode fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.setKeepScreenOn -setKeepScreenOn(Object): void +setKeepScreenOn(options?: SetKeepScreenOnOptions): void + +>This API is no longer maintained since API version 7. It is recommended that you use [window.setKeepScreenOn](js-apis-window.md#setkeepscreenon) instead. Sets whether to always keep the screen on. Call this API in **onShow()**. @@ -176,27 +140,88 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| keepScreenOn | boolean | Yes | Whether to always keep the screen on | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetKeepScreenOnOptions](#setkeepscreenonoptions) | No| Options for setting the screen to be steady on.| **Example** -```js -export default { - setKeepScreenOn() { - brightness.setKeepScreenOn({ - keepScreenOn: true, - success: function () { - console.log('handling set keep screen on success.') - }, - fail: function (data, code) { - console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` \ No newline at end of file + ```js + brightness.setKeepScreenOn({ + keepScreenOn: true, + success: function () { + console.log('handling set keep screen on success.'); + }, + fail: function (data, code) { + console.error('handling set keep screen on fail, code:' + code + ', data: ' + data); + } + }); + ``` +## GetBrightnessOptions + +Defines the options for obtaining the screen brightness. + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessResponse](#brightnessresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessResponse](#brightnessresponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## SetBrightnessOptions + +Defines the options for setting the screen brightness. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| value | number | Yes | Screen brightness. The value is an integer ranging from **1** to **255**.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.| +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## BrightnessResponse + +Defines a response that returns the screen brightness. + +| Parameter| Type | Description| +| -------- | -------- | -------- | +| value | number | Screen brightness. The value ranges from 1 to 255.| + +## GetBrightnessModeOptions + +Defines the options for obtaining the screen brightness mode. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessModeResponse](#brightnessmoderesponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## SetBrightnessModeOptions + +Defines the options for setting the screen brightness mode. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | +| mode | number | Yes | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| +| complete | () => void | No | Called when API call is complete. | + +## BrightnessModeResponse + +Defines a response that returns the screen brightness mode. + +| Name| Type | Description| +| -------- | -------- | -------- | +| mode | number | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| + +## SetKeepScreenOnOptions + +Defines the options for setting the screen to be steady on. + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | +| keepScreenOn | boolean | Yes | The value **true** means to keep the screen steady on, and the value **false** indicates the opposite. | +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| +| complete | () => void | No | Called when API call is complete. | diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index e6073f2dca4b101454fbdf14dd9bdd406a8eaade..3138f52c7089ba4a53809711c442b79f6a1aa1aa 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -1,8 +1,9 @@ -# NFC Tag Session +# tagSession The **tagSession** module provides common APIs for establishing connections and transferring 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. ## **Modules to Import** @@ -15,17 +16,15 @@ import tag from '@ohos.nfc.tag'; Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). -A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. +A child class instance is required to access the following interfaces. You can use **get**XXX() to obtain a child class instance. The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md). -### tagSession.connectTag - -connectTag(): boolean; +### tagSession.getTagInfo -Connects to this tag. +getTagInfo(): tag.TagInfo -Call this API to set up a connection before reading data from or writing data to a tag. +Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched. **Required permissions**: ohos.permission.NFC_TAG @@ -35,23 +34,25 @@ Call this API to set up a connection before reading data from or writing data to | **Type**| **Description** | | ------------------ | --------------------------| -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| TagInfo | **Taginfo** object obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); -console.log("isNfcConnected:" +isNfcConnected); +// 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 tagInfo = tag.getIsoDep(tagInfo).getTagInfo(); +console.log("tag tagInfo: " + tagInfo); ``` -### tagSession.reset() +### tagSession.connectTag -reset(): void +connectTag(): boolean; -Resets the connection to this tag and restores the default timeout duration for writing data to the tag. +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 @@ -68,9 +69,32 @@ Resets the connection to this tag and restores the default timeout duration for ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let reset = tag.getXXXTag(taginfo).reset(); -console.log("reset:" +reset); +// 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 connectStatus = tag.getIsoDep(tagInfo).connectTag(); +console.log("connectStatus: " + connectStatus); +``` + +### tagSession.reset() + +reset(): void + +Resets the connection to this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**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. + +tag.getIsoDep(tagInfo).reset(); ``` ### tagSession.isTagConnected @@ -94,16 +118,18 @@ Checks whether the tag is connected. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); -console.log("isTagConnected:" +isTagConnected); +// 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 isTagConnected = tag.getIsoDep(tagInfo).isTagConnected(); +console.log("isTagConnected: " + isTagConnected); ``` ### tagSession.getMaxSendLength getMaxSendLength(): number -Obtains the maximum length of the data that can be sent to the tag. +Obtains the maximum length of the data that can be sent to this tag. **Required permissions**: ohos.permission.NFC_TAG @@ -113,14 +139,167 @@ Obtains the maximum length of the data that can be sent to the tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | Maximum data length obtained.| +| number | Maximum data length obtained. The value cannot be a negative number.| + +**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 maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength(); +console.log("tag maxSendLen: " + maxSendLen); +``` + +### tagSession.getSendDataTimeout + +getSendDataTimeout(): number + +Obtains the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.| + +**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 sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout(); +console.log("tag sendDataTimeout: " + sendDataTimeout); +``` + +### tagSession.setSendDataTimeout + +setSendDataTimeout(timeout: number): boolean + +Sets the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the timeout period is set successfully; 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. + +let timeoutMs = 700; // Change it as required. +let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs); +console.log("tag setSendDataTimeout setStatus: " + setStatus); +``` + +### tagSession.sendData + +sendData(data: number[]): Promise + +Sends data to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. 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**.| + +**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. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData).then((response) => { + console.log("tagSession sendData Promise response: " + response); +}).catch((err)=> { + console.log("tagSession sendData Promise err: " + err); +}); +``` + +### tagSession.sendData + +sendData(data: number[], callback: AsyncCallback): void + +Sends 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.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. 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**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); -console.log("mazSendLen:" +mazSendLen); +// 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. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> { + if (err) { + console.log("tagSession sendData AsyncCallback err: " + err); + } else { + console.log("tagSession sendData AsyncCallback response: " + response); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index b7b7e08a0a6a5a82a8813aad1f9d2010ff899a50..e0d809d06ab24702e5eaf67eb6b1b841a7944ffc 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,11 +1,9 @@ # Thermal Manager -> **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 provides thermal level-related callback and query APIs to obtain the information required for thermal control. +> **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 @@ -13,78 +11,168 @@ This module provides thermal level-related callback and query APIs to obtain the import thermal from '@ohos.thermal'; ``` +## thermal.registerThermalLevelCallback9+ -## ThermalLevel +registerThermalLevelCallback(callback: Callback<ThermalLevel>): void -Represents the thermal level. +Subscribes to thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager -| Name | Default Value | Description | -| ---------- | ---- | ---------------------------------------- | -| COOL | 0 | The device is cool, and services are not restricted.| -| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| -| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| -| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.| -| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| -| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.| -| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------ | +| callback | Callback<ThermalLevel> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + thermal.registerThermalLevelCallback(level => { + console.info('thermal level is: ' + level); + }); + console.info('register thermal level callback success.'); +} catch(err) { + console.error('register thermal level callback failed, err: ' + err); +} +``` + +## thermal.unregisterThermalLevelCallback9+ + +unregisterThermalLevelCallback(callback?: Callback\): void + +Unsubscribes from thermal level changes. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------------------- | +| callback | Callback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + thermal.unregisterThermalLevelCallback(() => { + console.info('unsubscribe thermal level success.'); + }); + console.info('unregister thermal level callback success.'); +} catch(err) { + console.error('unregister thermal level callback failed, err: ' + err); +} +``` + +## thermal.getLevel9+ + +getLevel(): ThermalLevel + +Obtains the current thermal level. + +**System capability:** SystemCapability.PowerManager.ThermalManager +**Return value** -## thermal.subscribeThermalLevel +| Type | Description | +| ------------ | ------------ | +| ThermalLevel | Thermal level obtained.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var level = thermal.getLevel(); + console.info('thermal level is: ' + level); +} catch(err) { + console.error('get thermal level failed, err: ' + err); +} +``` + +## thermal.subscribeThermalLevel(deprecated) subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void +> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead. + Subscribes to thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to obtain the return value.
The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to return the result. The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| **Example** ```js -var lev = 0; -thermal.subscribeThermalLevel((lev) => { - console.info("Thermal level is: " + lev); -}) +thermal.subscribeThermalLevel((level) => { + console.info('thermal level is: ' + level); +}); ``` -## thermal.unsubscribeThermalLevel +## thermal.unsubscribeThermalLevel(deprecated) unsubscribeThermalLevel(callback?: AsyncCallback\): void +> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead. + Unsubscribes from thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------------- | -| callback | AsyncCallback<void> | No | Callback without a return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------- | +| callback | AsyncCallback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| **Example** ```js thermal.unsubscribeThermalLevel(() => { - console.info("Unsubscribe completed."); + console.info('unsubscribe thermal level success.'); }); ``` -## thermal.getThermalLevel +## thermal.getThermalLevel(deprecated) getThermalLevel(): ThermalLevel +> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead. + Obtains the current thermal level. **System capability:** SystemCapability.PowerManager.ThermalManager -**Return value**: +**Return value** | Type | Description | | ------------ | ------ | @@ -93,6 +181,22 @@ Obtains the current thermal level. **Example** ```js -var lev = thermal.getThermalLevel(); -console.info("Thermal level is: " + lev); +var level = thermal.getThermalLevel(); +console.info('thermal level is: ' + level); ``` + +## ThermalLevel + +Represents the thermal level. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +| Name | Value | Description | +| ---------- | ---- | ------------------------------------------------------------ | +| COOL | 0 | The device is cool, and services are not restricted. | +| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| +| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| +| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.| +| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| +| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.| +| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 383dd4b3862b849db5e9292d4b841acbc8e3cc33..442c62ee76cf48b60361ee939c0f116bf98fb1fa 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -1,4 +1,4 @@ -# URL String Parsing +# @ohos.url (URL String Parsing) > **NOTE** > @@ -14,7 +14,7 @@ import Url from '@ohos.url' ### constructor9+ -constructor(init?: string[][] | Record<string, string> | string | URLParams) +constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) A constructor used to create a **URLParams** instance. @@ -24,7 +24,7 @@ A constructor used to create a **URLParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| **Example** @@ -140,7 +140,7 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ### forEach9+ -forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void +forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. @@ -150,10 +150,10 @@ 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 the callback is invoked.| +| callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| -**Table 1** callbackfn parameter description +**Table 1** callbackFn parameter description | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -165,7 +165,7 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal ```js const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -myURLObject.URLParams.forEach((value, name, searchParams) => { +myURLObject.searchParams.forEach((value, name, searchParams) => { console.log(name, value, myURLObject.searchParams === searchParams); }); ``` @@ -366,18 +366,148 @@ params.append('fod', '3'); console.log(params.toString()); ``` -## URLSearchParams(deprecated) +## 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) +constructor(url: string, base?: string | URL) + +Creates a URL. + > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [URLParams9+](#constructor9+) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. + +**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 = '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'; +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| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid url string. | + +**Example** + +```js +let mm = 'http://username:password@host:8080'; +Url.URL.parseURL(mm); // Output 'http://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('http://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('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +url.toJSON(); +``` + +## URLSearchParams(deprecated) + +### constructor(deprecated) constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) A constructor used to create a **URLSearchParams** instance. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -398,14 +528,14 @@ let params = new Url.URLSearchParams(urlObject.search); ### append(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. - append(name: string, value: string): void Appends a key-value pair into the query string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -425,14 +555,14 @@ paramsObject.append('fod', '3'); ### delete(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. - delete(name: string): void Deletes key-value pairs of the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -451,14 +581,14 @@ paramsobject.delete('fod'); ### getAll(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. - getAll(name: string): string[] Obtains all the key-value pairs based on the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -484,14 +614,14 @@ console.log(params.getAll('fod').toString()) // Output ["1","3"]. ### entries(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. - entries(): IterableIterator<[string, string]> Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -511,24 +641,25 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ### forEach(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. -forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void +forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | 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 the callback is invoked.| +| 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.| -**Table 1** callbackfn parameter description +**Table 1** callbackFn parameter description | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -547,14 +678,15 @@ myURLObject.searchParams.forEach((value, name, searchParams) => { ### get(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. get(name: string): string | null Obtains the value of the first key-value pair based on the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -580,14 +712,15 @@ let age = parseInt(paramsObject.get("age"), 10); // is the number 18 ### has(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. has(name: string): boolean Checks whether a key has a value. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -612,14 +745,15 @@ paramsObject.has('bard') === true; ### set(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. set(name: string, value: string): void Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -639,14 +773,15 @@ paramsObject.set('baz', '3'); // Add a third parameter. ### sort(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. sort(): void Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -659,14 +794,15 @@ console.log(searchParamsObject.toString()); // Display the sorted query string / ### keys(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. keys(): IterableIterator<string> Obtains an ES6 iterator that contains the keys of all the key-value pairs. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -686,14 +822,15 @@ for (var key of searchParamsObject .keys()) { // Output key-value pairs ### values(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. values(): IterableIterator<string> Obtains an ES6 iterator that contains the values of all the key-value pairs. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -714,15 +851,14 @@ for (var value of searchParams.values()) { ### [Symbol.iterator](deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [[Symbol.iterator]9+](#symboliterator9) instead. - - [Symbol.iterator]\(): IterableIterator<[string, string]> Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [Symbol.iterator]9+](#symboliterator9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -741,14 +877,15 @@ for (const [name, value] of paramsObject) { ``` ### tostring(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.tostring9+](#tostring9) instead. toString(): string Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tostring9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -784,14 +921,17 @@ 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.| +| 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) -### constructor +> **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) +constructor(url: string, base?: string | URL) Creates a URL. @@ -807,23 +947,23 @@ 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 -new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ -new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ +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(inputUrl : string, inputBase ?: string | URL) +static parseURL(url : string, base?: string | URL): URL Parses a URL. @@ -833,14 +973,14 @@ Parses a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| inputUrl | string | Yes| Input object.| -| inputBase | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| 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 = 'http://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +let mm = 'https://username:password@host:8080'; +Url.URL.parseURL(mm); // Output 'https://username:password@host:8080/'; ``` ### tostring @@ -860,7 +1000,7 @@ 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 = new Url.URL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toString(); ``` @@ -881,7 +1021,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 = 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-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index a8221a78898accf8d18724193df311a13693b998..6af6bc0a51e3a862a159b6bf450c9ce90bd31346 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifi (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**
+> **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. @@ -166,20 +168,17 @@ Represents WLAN hotspot information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| Service set identifier (SSID) of the hotspot, in UTF-8 format.| -| bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| -| capabilities | string | Read only| Hotspot capabilities.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| WLAN security type.| -| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN access point (AP).| -| frequency | number | Read only| Frequency of the WLAN AP.| -| channelWidth | number | Read only| Channel width of the WLAN AP.| -| centerFrequency09+ | number | Read only| Center frequency of the hotspot.| -| centerFrequency19+ | number | Read only| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| -| infoElems9+ | Array<[WifiInfoElem](#wifiinfoelem9)> | Read only| Information elements.| -| timestamp | number | Read only| Timestamp.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Yes| No| Hotspot capabilities.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| +| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| timestamp | number | Yes| No| Timestamp.| ## WifiSecurityType @@ -189,50 +188,13 @@ Enumerates the WLAN security types. **System capability**: SystemCapability.Communication.WiFi.Core -| **Name**| **Default Value**| **Description**| +| **Name**| **Value**| **Description**| | -------- | -------- | -------- | | WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| | WIFI_SEC_TYPE_OPEN | 1 | Open security type.| | WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| | WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| | WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| -| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| -| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| -| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| -| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| -| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| - - -## WifiInfoElem9+ - -Represents a WLAN information element. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eid | number | Read only| ID of the information element.| -| content | Uint8Array | Read only| Content of the information element.| - - -## WifiChannelWidth9+ - -Enumerates the WLAN channel widths. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Default Value**| **Description**| -| -------- | -------- | -------- | -| WIDTH_20MHZ | 0 | 20 MHz.| -| WIDTH_40MHZ | 1 | 40 MHz.| -| WIDTH_80MHZ | 2 | 80 MHz.| -| WIDTH_160MHZ | 3 | 160 MHz.| -| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| -| WIDTH_INVALID | 5 | Invalid value.| ## wifi.getScanInfosSync9+ @@ -274,7 +236,7 @@ Adds network configuration. This API uses a promise to return the result. | **Type**| **Description**| | -------- | -------- | - | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| ## WifiDeviceConfig @@ -283,33 +245,32 @@ Represents the WLAN configuration. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| isHiddenSsid | boolean | Read only| Whether the network is hidden.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| creatorUid | number | Read only| ID of the creator.
**System API**: This is a system API.| -| disableReason | number | Read only| Reason for disabling WLAN.
**System API**: This is a system API.| -| netId | number | Read only| Network ID.
**System API**: This is a system API.| -| randomMacType | number | Read only| Random MAC type.
**System API**: This is a system API.| -| randomMacAddr | string | Read only| Random MAC address.
**System API**: This is a system API.| -| ipType | [IpType](#iptype7) | Read only| IP address type.
**System API**: This is a system API.| -| staticIp | [IpConfig](#ipconfig7) | Read only| Static IP address configuration.
**System API**: This is a system API.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Read only| EAP configuration.
**System API**: This is a system API.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype7) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| ## IpType7+ -Enumerates the IP address types. +Enumerate the IP address types. **System API**: This is a system API. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATIC | 0 | Static IP address.| | DHCP | 1 | IP address allocated by DHCP.| @@ -324,78 +285,12 @@ Represents IP configuration information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| dnsServers | number[] | Read only| Domain name server (DNS) information.| -| domains | Array<string> | Read only| Domain information.| - - -## WifiEapConfig9+ - -Represents EAP configuration information. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eapMethod | [EapMethod](#eapmethod9) | Read only| EAP authentication method.| -| phase2Method | [Phase2Method](#phase2method9) | Read only| Phase 2 authentication method.| -| identity | string | Read only| Identity Information.| -| anonymousIdentity | string | Read only| Anonymous identity.| -| password | string | Read only| Password.| -| caCertAliases | string | Read only| CA certificate alias.| -| caPath | string | Read only| CA certificate path.| -| clientCertAliases | string | Read only| Client certificate alias.| -| altSubjectMatch | string | Read only| A string to match the alternate subject.| -| domainSuffixMatch | string | Read only| A string to match the domain suffix.| -| realm | string | Read only| Realm for the passpoint credential.| -| plmn | string | Read only| Public land mobile network (PLMN) of the passpoint credential provider.| -| eapSubId | number | Read only| Sub-ID of the SIM card.| - - -## EapMethod9+ - -Enumerates the EAP authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| EAP_NONE | 0 | Not specified.| -| EAP_PEAP | 1 | PEAP.| -| EAP_TLS | 2 | TLS.| -| EAP_TTLS | 3 | TTLS.| -| EAP_PWD | 4 | Password.| -| EAP_SIM | 5 | SIM.| -| EAP_AKA | 6 | AKA.| -| EAP_AKA_PRIME | 7 | AKA Prime.| -| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| - - -## Phase2Method9+ - -Enumerates the Phase 2 authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| PHASE2_NONE | 0 | Not specified.| -| PHASE2_PAP | 1 | PAP.| -| PHASE2_MSCHAP | 2 | MS-CHAP.| -| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| -| PHASE2_GTC | 4 | GTC .| -| PHASE2_SIM | 5 | SIM.| -| PHASE2_AKA | 6 | AKA.| -| PHASE2_AKA_PRIME | 7 | AKA Prime.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| ## wifi.addDeviceConfig @@ -500,122 +395,6 @@ Removes the configuration of an untrusted network. This API uses an asynchronous | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig): Promise<number> - -Adds the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the network configuration ID.| - - -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void - -Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number): Promise<void> - -Removes the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void - -Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| - - -## wifi.getCandidateConfigs9+ - -getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> - -Obtains candidate network configuration. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| - - -## wifi.connectToCandidateConfig9+ - -connectToCandidateConfig(networkId: number): void - -Connects to a candidate network. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the candidate network configuration.| - - ## wifi.connectToNetwork connectToNetwork(networkId: number): boolean @@ -725,7 +504,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul | Type| Description| | -------- | -------- | - | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information.| ## wifi.getLinkedInfo @@ -770,24 +549,23 @@ Represents the WLAN connection information. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| networkId | number | Read only| Network configuration ID.
**System API**: This is a system API.| -| rssi | number | Read only| RSSI of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN AP.| -| linkSpeed | number | Read only| Speed of the WLAN AP.| -| frequency | number | Read only| Frequency of the WLAN AP.| -| isHidden | boolean | Read only| Whether to hide the WLAN AP.| -| isRestricted | boolean | Read only| Whether to restrict data volume at the WLAN AP.| -| chload | number | Read only| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| -| snr | number | Read only| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| -| macType9+ | number | Read only| MAC address type.| -| macAddress | string | Read only| MAC address of the device.| -| ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| -| suppState | [SuppState](#suppstate) | Read only| Supplicant state.
**System API**: This is a system API.| -| connState | [ConnState](#connstate) | Read only| WLAN connection state.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| ## ConnState @@ -796,7 +574,7 @@ Enumerates the WLAN connection states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SCANNING | 0 | The device is scanning for available APs.| | CONNECTING | 1 | A WLAN connection is being established.| @@ -816,7 +594,7 @@ Enumerates the supplicant states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | The supplicant is disconnected from the AP.| | INTERFACE_DISABLED | 1 | The network interface is disabled.| @@ -871,16 +649,16 @@ Obtains the features supported by this device. | Value| Description| | -------- | -------- | -| 0x0001 | WLAN infrastructure mode. | -| 0x0002 | 5 GHz feature. | -| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature. | -| 0x0008 | Wi-Fi Direct. | -| 0x0010 | SoftAP. | -| 0x0040 | Wi-Fi AWare. | -| 0x8000 | WLAN AP/STA concurrency. | -| 0x8000000 | WPA3 Personal (WPA-3 SAE). | -| 0x10000000 | WPA3-Enterprise Suite B. | -| 0x20000000 | Enhanced open feature. | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| ## wifi.isFeatureSupported7+ @@ -949,15 +727,15 @@ Represents IP information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| netmask | number | Read only| Subnet mask.| -| primaryDns | number | Read only| IP address of the preferred DNS server.| -| secondDns | number | Read only| IP address of the alternate DNS server.| -| serverIp | number | Read only| IP address of the DHCP server.| -| leaseDuration | number | Read only| Lease duration of the IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| ## wifi.getCountryCode7+ @@ -1237,13 +1015,13 @@ Represents the hotspot configuration. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| band | number | Read only| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| maxConn | number | Read only| Maximum number of connections allowed.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| ## wifi.getHotspotConfig7+ @@ -1292,11 +1070,11 @@ Represents the station information. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| name | string | Read only| Device name.| -| macAddress | string | Read only| MAC address.| -| ipAddress | string | Read only| IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| ## wifi.getP2pLinkedInfo8+ @@ -1323,11 +1101,11 @@ Represents the P2P link information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| connectState | [P2pConnectState](#p2pconnectstate8) | Read only| P2P connection state.| -| isGroupOwner | boolean | Read only| Whether the device is the group owner.| -| groupOwnerAddr | string | Read only| MAC address of the group. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate8) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. ## P2pConnectState8+ @@ -1336,7 +1114,7 @@ Enumerates the P2P connection states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | Disconnected.| | CONNECTED | 1 | Connected.| @@ -1373,7 +1151,7 @@ Obtains the current P2P group information. This API uses a promise to return the | Type| Description| | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the P2P group information obtained.| ## wifi.getCurrentGroup8+ @@ -1433,13 +1211,13 @@ Represents the P2P device information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Read only| Device name.| -| deviceAddress | string | Read only| MAC address of the device.| -| primaryDeviceType | string | Read only| Type of the primary device.| -| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Read only| Device status.| -| groupCapabilitys | number | Read only| Group capabilities.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Yes| No| Device status.| +| groupCapabilitys | number | Yes| No| Group capabilities.| ## P2pDeviceStatus8+ @@ -1448,7 +1226,7 @@ Enumerates the P2P device states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | CONNECTED | 0 | Connected.| | INVITED | 1 | Invited.| @@ -1457,40 +1235,6 @@ Enumerates the P2P device states. | UNAVAILABLE | 4 | Unavailable.| -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(): Promise<WifiP2pDevice> - -Obtains the local device information in the P2P connection. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| - - -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void - -Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| - - ## wifi.createGroup8+ createGroup(config: WifiP2PConfig): boolean @@ -1520,13 +1264,13 @@ Represents P2P group configuration. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceAddress | string | Read only| Device address.| -| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| -| passphrase | string | Read only| Passphrase of the group.| -| groupName | string | Read only| Name of the group.| -| goBand | [GroupOwnerBand](#groupownerband8) | Read only| Frequency band of the group.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| groupName | string | Yes| No| Name of the group.| +| goBand | [GroupOwnerBand](#groupownerband8) | Yes| No| Frequency band of the group.| ## GroupOwnerBand8+ @@ -1535,7 +1279,7 @@ Enumerates the P2P group frequency bands. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | GO_BAND_AUTO | 0 | Auto.| | GO_BAND_2GHZ | 1 | 2 GHz.| @@ -1727,61 +1471,23 @@ Deletes a persistent group. | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -## wifi.getP2pGroups9+ - -getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> - -Obtains information about all P2P groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| - - ## WifiP2pGroupInfo8+ Represents the P2P group information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| isP2pGo | boolean | Read only| Whether the device is the group owner.| -| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Read only| Device information of the group.| -| passphrase | string | Read only| Passphrase of the group.| -| interface | string | Read only| Interface name.| -| groupName | string | Read only| Group name.| -| networkId | number | Read only| Network ID.| -| frequency | number | Read only| Frequency of the group.| -| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Read only| List of connected devices.| -| goIpAddress | string | Read only| IP address of the group.| - - -## wifi.getP2pGroups9+ - -getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void - -Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| ## wifi.setDeviceName8+ @@ -1830,10 +1536,10 @@ Registers the WLAN state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('wifiStateChange')7+ @@ -2012,10 +1718,10 @@ Registers the hotspot state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('hotspotStateChange')7+ @@ -2057,11 +1763,11 @@ Registers the P2P state change events. | **Value**| **Description**| | -------- | -------- | -| 1 | Available. | -| 2 | Opening. | -| 3 | Opened. | -| 4 | Closing. | -| 5 | Closed. | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| ## wifi.off('p2pStateChange')8+ diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..8e3526343a3f62066af7686b4fbe5cb587fa1cbc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -0,0 +1,2187 @@ +# 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** +> +> 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 +import wifiManager from '@ohos.wifiManager'; +``` + +## wifi.enableWifi9+ + +enableWifi(): void + +Enables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableWifi9+ + +disableWifi(): void + +Disables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isWifiActive9+ + +isWifiActive(): boolean + +Checks whether WLAN is enabled. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + + +## wifi.scan9+ + +scan(): void + +Starts a scan for WLAN. + +**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION** + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getScanResults9+ + +getScanResults(): Promise<Array<WifiScanInfo>> + +Obtains the scan result. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| + + +## wifi.getScanResults9+ + +getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void + +Obtains the scan result. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + ``` + + +## WifiScanInfo9+ + +Represents WLAN hotspot information. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Yes| No| Hotspot capabilities.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| +| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| centerFrequency0 | number | Yes| No| Center frequency of the hotspot.| +| centerFrequency1 | number | Yes| No| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| +| infoElems | Array<[WifiInfoElem](#wifiinfoelem9)> | Yes| No| Information elements.| +| timestamp | number | Yes| No| Timestamp.| + + +## WifiSecurityType9+ + +Enumerates the WLAN security types. + +**System capability**: SystemCapability.Communication.WiFi.Core + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type.| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| +| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| +| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| +| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| +| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| +| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| + + +## WifiInfoElem9+ + +Represents a WLAN information element. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eid | number | Yes| No| ID of the information element.| +| content | Uint8Array | Yes| No| Content of the information element.| + + +## WifiChannelWidth9+ + +Enumerates the WLAN channel widths. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIDTH_20MHZ | 0 | 20 MHz.| +| WIDTH_40MHZ | 1 | 40 MHz.| +| WIDTH_80MHZ | 2 | 80 MHz.| +| WIDTH_160MHZ | 3 | 160 MHz.| +| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| +| WIDTH_INVALID | 5 | Invalid value.| + + +## wifi.getScanResultsSync9+ + +getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> + +Obtains the scan result. This API returns the result synchronously. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig): Promise<number> + +Adds network configuration. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| + +## WifiDeviceConfig9+ + +Represents the WLAN configuration. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| +| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| + + +## IpType9+ + +Enumerates the IP address types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| Name| Value| Description| +| -------- | -------- | -------- | +| STATIC | 0 | Static IP address.| +| DHCP | 1 | IP address allocated by DHCP.| +| UNKNOWN | 2 | Not specified.| + + +## IpConfig9+ + +Represents IP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| prefixLength | number | Yes| No| Subnet mask.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| + + +## WifiEapConfig9+ + +Represents EAP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eapMethod | [EapMethod](#eapmethod9) | Yes| No| EAP authentication method.| +| phase2Method | [Phase2Method](#phase2method9) | Yes| No| Phase 2 authentication method.| +| identity | string | Yes| No| Identity Information.| +| anonymousIdentity | string | Yes| No| Anonymous identity.| +| password | string | Yes| No| Password.| +| caCertAliases | string | Yes| No| CA certificate alias.| +| caPath | string | Yes| No| CA certificate path.| +| clientCertAliases | string | Yes| No| Client certificate alias.| +| altSubjectMatch | string | Yes| No| A string to match the alternate subject.| +| domainSuffixMatch | string | Yes| No| A string to match the domain suffix.| +| realm | string | Yes| No| Realm for the passpoint credential.| +| plmn | string | Yes| No| Public land mobile network (PLMN) of the passpoint credential provider.| +| eapSubId | number | Yes| No| Sub-ID of the SIM card.| + + +## EapMethod9+ + +Enumerates the EAP authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| EAP_NONE | 0 | Not specified.| +| EAP_PEAP | 1 | PEAP.| +| EAP_TLS | 2 | TLS.| +| EAP_TTLS | 3 | TTLS.| +| EAP_PWD | 4 | Password.| +| EAP_SIM | 5 | SIM.| +| EAP_AKA | 6 | AKA.| +| EAP_AKA_PRIME | 7 | AKA Prime.| +| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| + + +## Phase2Method9+ + +Enumerates the Phase 2 authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| PHASE2_NONE | 0 | Not specified.| +| PHASE2_PAP | 1 | PAP.| +| PHASE2_MSCHAP | 2 | MS-CHAP.| +| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| +| PHASE2_GTC | 4 | GTC .| +| PHASE2_SIM | 5 | SIM.| +| PHASE2_AKA | 6 | AKA.| +| PHASE2_AKA_PRIME | 7 | AKA Prime.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds network configuration. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig): Promise<number> + +Adds the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number): Promise<void> + +Removes the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void + +Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| + + +## wifi.getCandidateConfigs9+ + +getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains candidate network configuration. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + + +## wifi.connectToCandidateConfig9+ + +connectToCandidateConfig(networkId: number): void + +Connects to a candidate network. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| + + +## wifi.connectToNetwork9+ + +connectToNetwork(networkId: number): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.connectToDevice9+ + +connectToDevice(config: WifiDeviceConfig): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disconnect9+ + +disconnect(): void + +Disconnects the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getSignalLevel9+ + +getSignalLevel(rssi: number, band: number): number + +Obtains the WLAN signal level. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| RSSI of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(): Promise<WifiLinkedInfo> + +Obtains WLAN connection information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void + +Obtains WLAN connection information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); + }); + + wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); + }).catch(error => { + console.info("get linked info error"); + }); + ``` + + +## WifiLinkedInfo9+ + +Represents the WLAN connection information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macType9+ | number | Yes| No| MAC address type.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| + + +## ConnState9+ + +Enumerates the WLAN connection states. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| SCANNING | 0 | The device is scanning for available APs.| +| CONNECTING | 1 | A WLAN connection is being established.| +| AUTHENTICATING | 2 | An authentication is being performed for a WLAN connection.| +| OBTAINING_IPADDR | 3 | The IP address of the WLAN connection is being acquired.| +| CONNECTED | 4 | A WLAN connection is established.| +| DISCONNECTING | 5 | The WLAN connection is being disconnected.| +| DISCONNECTED | 6 | The WLAN connection is disconnected.| +| UNKNOWN | 7 | Failed to set up the WLAN connection.| + + +## SuppState9+ + +Enumerates the supplicant states. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | The supplicant is disconnected from the AP.| +| INTERFACE_DISABLED | 1 | The network interface is disabled.| +| INACTIVE | 2 | The supplicant is inactive.| +| SCANNING | 3 | The supplicant is scanning for a WLAN connection.| +| AUTHENTICATING | 4 | The supplicant is being authenticated.| +| ASSOCIATING | 5 | The supplicant is being associated with an AP.| +| ASSOCIATED | 6 | The supplicant is associated with an AP.| +| FOUR_WAY_HANDSHAKE | 7 | A four-way handshake is being performed for the supplicant.| +| GROUP_HANDSHAKE | 8 | A group handshake is being performed for the supplicant.| +| COMPLETED | 9 | The authentication is complete.| +| UNINITIALIZED | 10 | The supplicant failed to set up the connection.| +| INVALID | 11 | Invalid value.| + + +## wifi.isConnected9+ + +isConnected(): boolean + +Checks whether the WLAN is connected. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + + +## wifi.getSupportedFeatures9+ + +getSupportedFeatures(): number + +Obtains the features supported by this device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | + +**Feature IDs** + +| Value| Description| +| -------- | -------- | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| + + +## wifi.isFeatureSupported9+ + +isFeatureSupported(featureId: number): boolean + +Checks whether the device supports the specified WLAN feature. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.getDeviceMacAddress9+ + +getDeviceMacAddress(): string[] + +Obtains the device MAC address. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_LOCAL_MAC and ohos.permission.GET_WIFI_INFO (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| + + +## wifi.getIpInfo9+ + +getIpInfo(): IpInfo + +Obtains IP information. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo9) | IP information obtained.| + + +## IpInfo9+ + +Represents IP information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| + + +## wifi.getCountryCode9+ + +getCountryCode(): string + +Obtains the country code. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| + + +## wifi.reassociate9+ + +reassociate(): void + +Re-associates with the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.reconnect9+ + +reconnect(): void + +Reconnects to the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getDeviceConfigs9+ + +getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + + +## wifi.updateNetwork9+ + +updateNetwork(config: WifiDeviceConfig): number + +Updates network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| + + +## wifi.disableNetwork9+ + +disableNetwork(netId: number): void + +Disables network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the network configuration to disable.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeAllNetwork9+ + +removeAllNetwork(): void + +Removes the configuration of all networks. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeDevice9+ + +removeDevice(id: number): void + +Removes the specified network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | +| id | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.enableHotspot9+ + +enableHotspot(): void + +Enables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableHotspot9+ + +disableHotspot(): void + +Disables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isHotspotDualBandSupported9+ + +isHotspotDualBandSupported(): boolean + +Checks whether the hotspot supports dual band. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.isHotspotActive9+ + +isHotspotActive(): boolean + +Checks whether this hotspot is active. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + + +## wifi.setHotspotConfig9+ + +setHotspotConfig(config: HotspotConfig): void + +Sets hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## HotspotConfig9+ + +Represents the hotspot configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| + + +## wifi.getHotspotConfig9+ + +getHotspotConfig(): HotspotConfig + +obtains hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| + + +## wifi.getStations9+ + +getStations():  Array<[StationInfo](#stationinfo9)> + +Obtains information about the connected stations. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| + + +## StationInfo9+ + +Represents the station information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> + +Obtains P2P link information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| + + + +## WifiP2pLinkedInfo9+ + +Represents the P2P link information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate9) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. + + +## P2pConnectState9+ + +Enumerates the P2P connection states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | Disconnected.| +| CONNECTED | 1 | Connected.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void + +Obtains P2P link information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(): Promise<WifiP2pGroupInfo> + +Obtains the current P2P group information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void + +Obtains the current P2P group information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(): Promise<WifiP2pDevice[]> + +Obtains the peer device list in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void + +Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + + +## WifiP2pDevice9+ + +Represents the P2P device information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.| +| groupCapabilities | number | Yes| No| Group capabilities.| + + +## P2pDeviceStatus9+ + +Enumerates the P2P device states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| CONNECTED | 0 | Connected.| +| INVITED | 1 | Invited.| +| FAILED | 2 | Failed.| +| AVAILABLE | 3 | Available.| +| UNAVAILABLE | 4 | Unavailable.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(): Promise<WifiP2pDevice> + +Obtains the local device information in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void + +Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.createGroup9+ + +createGroup(config: WifiP2PConfig): void + +Creates a P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## WifiP2PConfig9+ + +Represents P2P group configuration. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| groupName | string | Yes| No| Name of the group.| +| goBand | [GroupOwnerBand](#groupownerband9) | Yes| No| Frequency band of the group.| + + +## GroupOwnerBand9+ + +Enumerates the P2P group frequency bands. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| GO_BAND_AUTO | 0 | Auto.| +| GO_BAND_2GHZ | 1 | 2 GHz.| +| GO_BAND_5GHZ | 2 | 5 GHz.| + + +## wifi.removeGroup9+ + +removeGroup(): void + +Removes this P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.p2pConnect9+ + +p2pConnect(config: WifiP2PConfig): void + +Sets up a P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); + } + wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + + var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); + } + wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + + var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); + } + wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + + var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); + } + wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + + setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); + console.info("start discover devices -> " + wifi.startDiscoverDevices()); + ``` + +## wifi.p2pCancelConnect9+ + +p2pCancelConnect(): void + +Cancels this P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.startDiscoverDevices9+ + +startDiscoverDevices(): void + +Starts to discover devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.stopDiscoverDevices9+ + +stopDiscoverDevices(): void + +Stops discovering devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.deletePersistentGroup9+ + +deletePersistentGroup(netId: number): void + +Deletes a persistent group. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the group to delete.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> + +Obtains information about all P2P groups. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| + + +## WifiP2pGroupInfo9+ + +Represents the P2P group information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice9) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice9) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void + +Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.setDeviceName9+ + +setDeviceName(devName: string): void + +Sets the device name. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.on('wifiStateChange')9+ + +on(type: "wifiStateChange", callback: Callback<number>): void + +Registers the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + +**WLAN states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('wifiStateChange')9+ + +off(type: "wifiStateChange", callback?: Callback<number>): void + +Unregisters the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); + } + + // Register an event. + wifi.on("wifiStateChange", recvPowerNotifyFunc); + + // Unregister an event. + wifi.off("wifiStateChange", recvPowerNotifyFunc); + ``` + + +## wifi.on('wifiConnectionChange')7+ + +on(type: "wifiConnectionChange", callback: Callback<number>): void + +Registers the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + +**WLAN connection states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Disconnected.| +| 1 | Connected.| + + +## wifi.off('wifiConnectionChange')9+ + +off(type: "wifiConnectionChange", callback?: Callback<number>): void + +Unregisters the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiScanStateChange')9+ + +on(type: "wifiScanStateChange", callback: Callback<number>): void + +Registers the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + +**WLAN scan states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Scan failed.| +| 1 | Scan successful.| + + +## wifi.off('wifiScanStateChange')9+ + +off(type: "wifiScanStateChange", callback?: Callback<number>): void + +Unregisters the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiRssiChange')9+ + +on(type: "wifiRssiChange", callback: Callback<number>): void + +Registers the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + + +## wifi.off('wifiRssiChange')9+ + +off(type: "wifiRssiChange", callback?: Callback<number>): void + +Unregisters the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('hotspotStateChange')9+ + +on(type: "hotspotStateChange", callback: Callback<number>): void + +Registers the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + +**Hotspot states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('hotspotStateChange')9+ + +off(type: "hotspotStateChange", callback?: Callback<number>): void + +Unregisters the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pStateChange')9+ + +on(type: "p2pStateChange", callback: Callback<number>): void + +Registers the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + +**P2P states** + +| **Value**| **Description**| +| -------- | -------- | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| + +## wifi.off('p2pStateChange')9+ + +off(type: "p2pStateChange", callback?: Callback<number>): void + +Unregisters the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + + ## wifi.on('p2pConnectionChange')9+ + +on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void + +Registers the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| + + +## wifi.off('p2pConnectionChange')9+ + +off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void + +Unregisters the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDeviceChange')9+ + +on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void + +Registers the P2P device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| + + +## wifi.off('p2pDeviceChange')9+ + +off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void + +Unregisters the P2P device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPeerDeviceChange')9+ + +on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void + +Registers the P2P peer device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| + + +## wifi.off('p2pPeerDeviceChange')9+ + +off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void + +Unregisters the P2P peer device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPersistentGroupChange')9+ + +on(type: "p2pPersistentGroupChange", callback: Callback<void>): void + +Registers the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + + +## wifi.off('p2pPersistentGroupChange')9+ + +off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void + +Unregisters the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDiscoveryChange')9+ + +on(type: "p2pDiscoveryChange", callback: Callback<number>): void + +Registers the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + +**P2P discovered device states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Initial state.| +| 1 | Discovered.| + + +## wifi.off('p2pDiscoveryChange')9+ + +off(type: "p2pDiscoveryChange", callback?: Callback<number>): void + +Unregisters the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md new file mode 100644 index 0000000000000000000000000000000000000000..f024294ddbc393a57394a1ad20d2686d30060e52 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -0,0 +1,152 @@ +# WLAN Extension Interface + +This **wifiext** module provides WLAN extension interfaces for non-universal products. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The APIs described in this document are used only for non-universal products, such as routers. + + +## Modules to Import + +```js +import wifiManagerExt from '@ohos.wifiManagerExt'; +``` + +## wifiext.enableHotspot + +enableHotspot(): boolean; + +Enables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.disableHotspot + +disableHotspot(): boolean; + +Disables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(): Promise<Array<PowerModel>> + +Obtains the supported power models. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + + +## PowerModel + +Enumerates the power models. + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +| Name| Value| Description| +| -------- | -------- | -------- | +| SLEEPING | 0 | Sleeping| +| GENERAL | 1 | General| +| THROUGH_WALL | 2 | Through_wall| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void + +Obtains the supported power models. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**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.| + + +## wifiext.getPowerModel + +getPowerModel(): Promise<PowerModel> + +Obtains the power model. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| + + +## wifiext.getPowerModel + +getPowerModel(callback: AsyncCallback<PowerModel>): void + +Obtains the power model. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**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.| + + +## wifiext.setPowerModel + +setPowerModel(model: PowerModel) : boolean; + + Sets the power model. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | 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.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 9ce53d76e2517eb199067f779168fb9fe9d8b032..70961ffe279bf5543bbe28168f8571a54ca46651 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifiext + This **wifiext** module provides WLAN extension interfaces for non-universal products. -> **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. The APIs described in this document are used only for non-universal products, such as routers. @@ -69,7 +71,7 @@ Enumerates the power models. **System capability**: SystemCapability.Communication.WiFi.AP.Extension -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SLEEPING | 0 | Sleeping| | GENERAL | 1 | General| @@ -90,7 +92,7 @@ Obtains the supported power models. This API uses an asynchronous callback to re | 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 models obtained. If **err** is not **0**, an error has occurred.| + | 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 @@ -141,7 +143,7 @@ setPowerModel(model: PowerModel) : boolean; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | model | AsyncCallback<[PowerModel](#powermodel)> | Yes| Power model to set.| + | model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** diff --git a/en/application-dev/reference/errorcodes/errorcode-accessibility.md b/en/application-dev/reference/errorcodes/errorcode-accessibility.md new file mode 100644 index 0000000000000000000000000000000000000000..954c8464f3fd81d2f6c980f42711871d546dc078 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-accessibility.md @@ -0,0 +1,96 @@ +# Accessibility Error Codes + +## 9300001 Invalid Bundle Name or Ability Name + +**Error Message** + +Invalid bundle name or ability name. + +**Description** + +This error code is reported when the entered bundle name or ability name is invalid. + +**Possible Causes** + + +1. The bundle name does not exist. +2. The bundle does not contain the target ability. + +**Solution** + +1. Verify the bundle name. +2. Check whether the ability name corresponding to the bundle name is correct. + +## 9300002 Target Ability Already Enabled + +**Error Message** + +Target ability already enabled. + +**Description** + +This error code is reported when the target ability is already enabled. + +**Possible Causes** + +The target ability is already enabled and cannot be enabled again. + +**Solution** + +1. Stop the target Ability. +2. Re-enable the target ability. + +## 9300003 No Accessibility Permission to Perform the Operation + +**Error Message** + +Do not have accessibility right for this operation. + +**Description** + +This error code is reported when an application performs an accessibility operation for which the related permission has not been granted. + +**Possible Causes** + +The permission for performing the accessibility operation is not granted when the accessibility application is enabled. + +**Solution** + +1. Request from the user the permission for performing the accessibility operation, stating the reason for the request. +2. Have the accessibility application re-enabled and the required accessibility operation enabled. + +## 9300004 Attribute Not Found + +**Error Message** + +This property does not exist. + +**Description** + +This error code is reported when the entered attribute of the accessibility element does not exist. + +**Possible Causes** + +The attribute does not exist in the accessibility element. + +**Solution** + +Make sure the accessibility element has the target attribute. + +## 9300005 Operation Not Supported + +**Error Message** + +This action is not supported. + +**Description** + +This error code is reported when the application performs an operation that is not supported by the accessibility element. + +**Possible Causes** + +The accessibility element does not support the target operation. + +**Solution** + +Make sure the operation is included in the list of operations supported by the accessibility element. diff --git a/en/application-dev/reference/errorcodes/errorcode-batteryStatistics.md b/en/application-dev/reference/errorcodes/errorcode-batteryStatistics.md new file mode 100644 index 0000000000000000000000000000000000000000..6618e266707d3e187e0b79fcef9c67ac9ae5d142 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-batteryStatistics.md @@ -0,0 +1,29 @@ +# Power Consumption Statistics Error Codes + +## 4600101 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported for a service connection failure. + +**Possible Causes** + +1. The system service stops running. + +2. The internal communication of system services is abnormal. + +**Solution** + +Check whether the system services are running properly. + +1. Run the following command on the console to view the current system service list: + + ```bash + > hdc shell hidumper -ls + ``` + +2. Check whether **BatteryStatisticsService** is included in the system service list. diff --git a/en/application-dev/reference/errorcodes/errorcode-brightness.md b/en/application-dev/reference/errorcodes/errorcode-brightness.md new file mode 100644 index 0000000000000000000000000000000000000000..98dbced9c54a41dc6c55eb35ddf018c5a089d4be --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-brightness.md @@ -0,0 +1,29 @@ +# Brightness Error Codes + +## 4700101 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported for a service connection failure. + +**Possible Causes** + +1. The system service stops running. + +2. The internal communication of system services is abnormal. + +**Solution** + +Check whether the system services are running properly. + +1. Run the following command on the console to view the current system service list: + + ```bash + > hdc shell hidumper -ls + ``` + +2. Check whether **DisplayPowerManagerService** is included in the system service list. diff --git a/en/application-dev/reference/errorcodes/errorcode-geoLocationManager.md b/en/application-dev/reference/errorcodes/errorcode-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c02263c609d1fc477d39db80eb632b00bec2b5 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-geoLocationManager.md @@ -0,0 +1,157 @@ +# Location Subsystem Error Codes + +## 3301000 Location Service Unavailable + +**Error Message** + +Location service is unavailable. + +**Description** + +This error code is reported when the location service is unavailable and relevant APIs cannot be called. + +**Possible Causes** + +1. The location service fails to be started. As a result, the communication between the application and the location service fails, and the location service is unavailable. + +2. The GNSS chip fails to be initialized, and thus the GNSS positioning function becomes invalid. + +3. The network positioning service is abnormal, and thus the network positioning function becomes invalid. + +**Solution** + +Stop calling the API. + +## 3301100 Location Service Unavailable Because of Switch Toggled Off + +**Error Message** + +The location switch is off. + +**Description** + +This error code is reported when the location service is unavailable because the service switch is toggled off. + +**Possible Causes** + +The location service switch is toggled off, which makes basic functions such as continuous positioning and immediate positioning unavailable. + +**Solution** + +Display a prompt asking for enabling the location service. + +## 3301200 Failure to Obtain the Positioning Result + +**Error Message** + +Failed to obtain the geographical location. + +**Description** + +This error code is reported when the location service fails, and no positioning result is obtained. + +**Possible Causes** + +1. Positioning timed out because of weak GNSS signals. + +2. Positioning timed out because the network positioning service is abnormal. + +**Solution** + +Initiate a positioning request again. + +## 3301300 Reverse Geocoding Query Failure + +**Error Message** + +Reverse geocoding query failed. + +**Description** + +This error code is reported for a reverse geocoding query failure. + +**Possible Causes** + +Network connection is poor, which makes the request fail to be sent from the device or the result fail to be returned from the cloud to the device. + +**Solution** + +Try the reverse geocoding query again. + +## 3301400 Geocoding Query Failure + +**Error Message** + +Geocoding query failed. + +**Description** + +This error code is reported for a geocoding query failure. + +**Possible Causes** + +Network connection is poor, which makes the request fail to be sent from the device or the result fail to be returned from the cloud to the device. + +**Solution** + +Try the geocoding query again. + +## 3301500 Area Information Query Failure + +**Error Message** + +Failed to query the area information. + +**Description** + +This error code is reported for the failure to query the area information (including the country code). + +**Possible Causes** + +The correct area information is not found. + +**Solution** + +Stop calling the API for querying the country code. + +## 3301600 Geofence Operation Failure + +**Error Message** + +Failed to operate the geofence. + +**Description** + +This error code is reported when an operation (like adding, deleting, pausing, and resuming) fails to be performed on the geofence. + +**Possible Causes** + +1. The GNSS chip does not support the geofence function. + +2. The bottom-layer service logic is abnormal. + +**Solution** + +Stop calling the geofence operation API. + +## 3301700 No Response to the Request + +**Error Message** + +No response to the request. + +**Description** + +This error code is reported when no response is received for an asynchronous request that requires a user to click a button for confirmation or requires a response from the GNSS chip or network server. + +**Possible Causes** + +1. The user does not click a button as required for confirmation. + +2. The GNSS chip does not respond. + +3. The network server does not respond. + +**Solution** + +Stop calling relevant APIs. diff --git a/en/application-dev/reference/errorcodes/errorcode-nfc.md b/en/application-dev/reference/errorcodes/errorcode-nfc.md new file mode 100644 index 0000000000000000000000000000000000000000..500d870366c8a88a9036454ada2d0ffe0a3c04a9 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-nfc.md @@ -0,0 +1,43 @@ +# NFC Error Codes + +## 3100101 + +**Error Message** + +NFC opening or closing state is abnormal in service. + +**Description** + +The NFC service fails to enable or disable NFC. + +**Possible Causes** + +Communication with the NFC service failed. + +**Solution** + +Enable or disable NFC again. + +## 3100201 + +**Error Message** + +Tag running state is abnormal in service. + +**Description** + +An error occurs when the NFC service executes the tag service logic. + +**Possible Causes** +1. The tag parameters do not match the API to invoke. +2. The NFC is disabled. +3. The tag is disconnected before the tag operation. +4. The tag chip returns an error status or response timeout. +5. Binding with the NFC service has not been established. + +**Solution** +1. Check whether the NFC parameters match the API to invoke. +2. Enable NFC for the device. +3. Connect to the tag and then perform the read and write operations. +4. Touch and read the card again. +5. Exit the app and read the card again. diff --git a/en/application-dev/reference/errorcodes/errorcode-power.md b/en/application-dev/reference/errorcodes/errorcode-power.md new file mode 100644 index 0000000000000000000000000000000000000000..83bbb2cdea786fd43b780fb9c153a31faf924e17 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-power.md @@ -0,0 +1,47 @@ +# Power Manager Error Codes + +## 4900101 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported for a service connection failure. + +**Possible Causes** + +1. The system service stops running. + +2. The internal communication of system services is abnormal. + +**Solution** + +Check whether the system services are running properly. + +1. Run the following command on the console to view the current system service list: + + ```bash + > hdc shell hidumper -ls + ``` + +2. Check whether **PowerManagerService** is included in the system service list. + +## 4900102 System Shuting Down + +**Error Message** + +Operation failed. System is shutting down. + +**Description** + +This error code is reported when an operation failed during system shutting down. + +**Possible Causes** + +The system is shutting down. + +**Solution** + +Make sure that the operation is performed when the system is running properly. diff --git a/en/application-dev/reference/errorcodes/errorcode-runninglock.md b/en/application-dev/reference/errorcodes/errorcode-runninglock.md new file mode 100644 index 0000000000000000000000000000000000000000..5e55c69b6304f626ab2bc247e17547703c424056 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-runninglock.md @@ -0,0 +1,29 @@ +# Running Lock Error Codes + +## 4900101 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported for a service connection failure. + +**Possible Causes** + +1. The system service stops running. + +2. The internal communication of system services is abnormal. + +**Solution** + +Check whether the system services are running properly. + +1. Run the following command on the console to view the current system service list: + + ```bash + > hdc shell hidumper -ls + ``` + +2. Check whether **PowerManagerService** is included in the system service list. diff --git a/en/application-dev/reference/errorcodes/errorcode-thermal.md b/en/application-dev/reference/errorcodes/errorcode-thermal.md new file mode 100644 index 0000000000000000000000000000000000000000..d831a9ebe63ccff1a86ea8e77cb56a969c115f0b --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-thermal.md @@ -0,0 +1,29 @@ +# Thermal Manager Error Codes + +## 4800101 Service Connection Failure + +**Error Message** + +Operation failed. Cannot connect to service. + +**Description** + +This error code is reported for a service connection failure. + +**Possible Causes** + +1. The system service stops running. + +2. The internal communication of system services is abnormal. + +**Solution** + +Check whether the system services are running properly. + +1. Run the following command on the console to view the current system service list: + + ```bash + > hdc shell hidumper -ls + ``` + +2. Check whether **ThermalService** is included in the system service list. diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md index 4dccc4dbf082cc1121443c00adbef531b2b5ed23..cb0f8cead65cd1faed98c723d30f557b4302bbab 100644 --- a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @@ -42,7 +42,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | Option| Description| | -------- | -------- | | -t | Event tag used to filter subscribed real-time system events.| - | -c | Matching rule for event tags. The options can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| + | -c | Matching rule for event tags. The option can be **WHOLE_WORD**, **PREFIX**, or **REGULAR**.| Example: @@ -67,7 +67,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** | -------- | -------- | | -o | Event domain used to filter subscribed real-time system events.| | -n | Event name used to filter subscribed real-time system events.| - | -c | Matching rule for event domains and event names. The options can be **WHOLE_WORD**, PREFIX, or **REGULAR**.| + | -c | Matching rule for event domains and event names. The option can be **WHOLE_WORD**, PREFIX, or **REGULAR**.| Example: @@ -83,6 +83,30 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** > **NOTE** > If **-t**, **-o**, and **-n** are specified, the system checks whether the configured event tag is null. If the event tag is not null, the system filters system events based on the matching rules for the event tag. Otherwise, the system filters system events based on the matching rules for the event domain and event name. +- Command for subscribing to real-time system events by event type: + + ``` + hisysevent -r -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] + ``` + + Description of command options: + + | Option| Description| + | -------- | -------- | + | -g | Type of the system events to be subscribed to. The option can be **FAULT**, **STATISTIC**, **SECURITY**, or **BEHAVIOR**.| + + Example: + + ``` + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -g FAULT + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "POWER\w{0,8}" -n "POWER_RUNNINGLOCK" -c REGULAR -g STATISTIC + {"domain_":"POWER","name_":"POWER_RUNNINGLOCK","type_":2,"time_":1667485283785,"tz_":"+0000","pid_":538,"tid_":684,"uid_":5523,"PID":360,"UID":1001,"STATE":0,"TYPE":1,"NAME":"telRilRequestRunningLock","LOG_LEVEL":2,"TAG":"DUBAI_TAG_RUNNINGLOCK_REMOVE","MESSAGE":"token=25956496","level_":"MINOR","tag_":"PowerStats","id_":"11994072552538324655","info_":""} + # hisysevent -r -o "ACCOU\w+" -c REGULAR -g SECURITY + {"domain_":"ACCOUNT","name_":"PERMISSION_EXCEPTION","type_":3,"time_":1667484405993,"tz_":"+0000","pid_":614,"tid_":614,"uid_":3058,"CALLER_UID":1024,"CALLER_PID":523,"PERMISSION_NAME":"ohos.permission.MANAGE_LOCAL_ACCOUNTS","level_":"CRITICAL","tag_":"security","id_":"15077995598140341422","info_":""} + # hisysevent -r -o MULTIMODALINPUT -g BEHAVIOR + {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} + ``` ## Querying Historical System Events @@ -139,6 +163,56 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} ``` +- Command for querying historical system events by event domain and event name: + + ``` + hisysevent -l -o -n [-c WHOLE_WORD] + ``` + + Description of command options: + + | Option| Description| + | -------- | -------- | + | -o | Domain based on which historical system events are queried.| + | -n | Name based on which historical system events are queried.| + | -c | Rule for matching the domain and name of historical system events. The option can only be **WHOLE_WORD**.| + + Example: + + ``` + # hisysevent -l -n "APP_FREEZE" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "RELIABILITY" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""} + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -c WHOLE_WORD + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""} + ``` + +- Command for querying historical system events by event type: + + ``` + hisysevent -l -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] + ``` + + Description of command options: + + | Option| Description| + | -------- | -------- | + | -g | Type of the historical system events to be queried. The option can be **FAULT**, **STATISTIC**, **SECURITY**, or **BEHAVIOR**.| + + Example: + + ``` + # hisysevent -l -o "RELIABILITY" -g FAULT + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -l -n "POWER_RUNNINGLOCK" -c WHOLE_WORD -g STATISTIC + {"domain_":"POWER","name_":"POWER_RUNNINGLOCK","type_":2,"time_":1667485283785,"tz_":"+0000","pid_":538,"tid_":684,"uid_":5523,"PID":360,"UID":1001,"STATE":0,"TYPE":1,"NAME":"telRilRequestRunningLock","LOG_LEVEL":2,"TAG":"DUBAI_TAG_RUNNINGLOCK_REMOVE","MESSAGE":"token=25956496","level_":"MINOR","tag_":"PowerStats","id_":"11994072552538324655","info_":""} + # hisysevent -l -g SECURITY + {"domain_":"ACCOUNT","name_":"PERMISSION_EXCEPTION","type_":3,"time_":1667484405993,"tz_":"+0000","pid_":614,"tid_":614,"uid_":3058,"CALLER_UID":1024,"CALLER_PID":523,"PERMISSION_NAME":"ohos.permission.MANAGE_LOCAL_ACCOUNTS","level_":"CRITICAL","tag_":"security","id_":"15077995598140341422","info_":""} + # hisysevent -l -o MULTIMODALINPUT -g BEHAVIOR + {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} + ``` + ## System Event Validity Check - Enabling system event validity check diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-ability.md index f507dbeb818ec3b7800d31e0083af40c7beb96fc..66610c4d955a7037cc957b2602b791bde8ef72aa 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-ability.md @@ -1,18 +1,12 @@ # @ohos.app.ability.Ability (Ability基类) -[UIAbility](js-apis-app-ability-uiAbility.md)和[ExtensionAbility](js-apis-app-ability-extensionAbility.md)的基类,提供系统配置更新回调和系统内存调整回调。 +[UIAbility](js-apis-app-ability-uiAbility.md)和[ExtensionAbility](js-apis-app-ability-extensionAbility.md)的基类,提供系统配置更新回调和系统内存调整回调。不支持开发者直接继承该基类。 > **说明:** > > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块接口仅可在Stage模型下使用。 -## 导入模块 - -```ts -import Ability from '@ohos.app.ability.Ability'; -``` - ## Ability.onConfigurationUpdate onConfigurationUpdate(newConfig: Configuration): void; @@ -29,7 +23,10 @@ onConfigurationUpdate(newConfig: Configuration): void; **示例:** ```ts -class MyAbility extends Ability { +// Ability是顶层基类,不支持开发者直接继承。故以派生类UIAbility举例说明。 +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { onConfigurationUpdate(config) { console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); } @@ -40,7 +37,7 @@ class MyAbility extends Ability { onMemoryLevel(level: AbilityConstant.MemoryLevel): void; -当系统已决定调整内存时调用。例如,当该功能在后台运行时,没有足够的内存来运行尽可能多的后台进程时可以使用。 +当内存到达不同级别时系统回调该方法。 **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -48,12 +45,15 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | 是 | 回调返回内存微调级别,显示当前内存使用状态。| +| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | 是 | 当前内存使用级别。| **示例:** ```ts -class MyAbility extends Ability { +// Ability是顶层基类,不支持开发者直接继承。故以派生类UIAbility举例说明。 +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md index a31dd54294e8bcae8e7b66e3b91b4e12bb5e9f8f..87c394fc1db9e2a8bcebcc34d5628ebee23da840 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md @@ -1,31 +1,10 @@ # @ohos.app.ability.ExtensionAbility (扩展能力基类) -ExtensionAbility是特定场景扩展能力的基类,继承自[Ability](js-apis-app-ability-ability.md),未新增属性和方法。 +ExtensionAbility是特定场景扩展能力的基类,继承自[Ability](js-apis-app-ability-ability.md),未新增属性和方法。不支持开发者直接继承该基类。 > **说明:** > > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块接口仅可在Stage模型下使用。 -## 导入模块 - -```ts -import ExtensionAbility from '@ohos.app.ability.ExtensionAbility'; -``` - -**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore - -**示例:** - - ```ts - class MyExtensionAbility extends ExtensionAbility { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - - onMemoryLevel(level) { - console.log('onMemoryLevel, level:' + JSON.stringify(level)); - } - } - ``` - +**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md index 55653a9924d67ee8a901845d7a99ab5abd005a9c..0d9e28f090c17ff153c65bad60cc278b2f417f89 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @@ -593,7 +593,7 @@ KVStore数据库类型枚举。 | --- | ---- | ----------------------- | | DEVICE_COLLABORATION | 0 | 表示多设备协同数据库。
**数据库特点:** 数据以设备的维度管理,不存在冲突;支持按照设备的维度查询数据。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | | SINGLE_VERSION | 1 | 表示单版本数据库。
**数据库特点:** 数据不分设备,设备之间修改相同的key会覆盖。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| MULTI_VERSION | 2 | 表示多版本数据库。此类型当前不允许使用。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| MULTI_VERSION | 2 | 表示多版本数据库。当前暂不支持使用此接口。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | ## SecurityLevel diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md index 851a2725467242725c2ae0da44c6afcc89e8df8b..e0472d5cc12d0fecc5a12e8c7897475d3ca156e6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -10,6 +10,6 @@ | 名称 | 可读 | 可写 | 类型 | 必填 | 说明 | | ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ | -| resultCode | 是 | 否 | number | 否 | 表示ability拉起、销毁之后返回的结果码。 | +| resultCode | 是 | 否 | number | 是 | 表示ability拉起、销毁之后返回的结果码。 | | want | 是 | 否 | [Want](./js-apis-app-ability-want.md) | 否 | 表示ability销毁之后返回的数据。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md index 8f0c31e365d8aaa42fcb929c5647b00c684b017d..feaa175b8cd23fceb8e9dfee727ef603356f9a4c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -1,8 +1,6 @@ # UIAbilityContext -UIAbilityContext是UIAbility的上下文环境,继承自Context。 - -UIAbilityContext模块提供允许访问特定UIAbility的资源的能力,包括对UIAbility的启动、停止的设置、获取caller通信接口、拉起弹窗请求用户授权等。 +UIAbilityContext是[UIAbility](js-apis-app-ability-uiAbility.md)的上下文环境,继承自[Context](js-apis-inner-application-context.md),提供UIAbility的相关配置信息以及操作UIAbility和ServiceExtensionAbility的方法,如启动UIAbility,停止当前UIAbilityContext所属的UIAbility,启动、停止、连接、断开连接ServiceExtensionAbility等。 > **说明:** > @@ -15,9 +13,12 @@ UIAbilityContext模块提供允许访问特定UIAbility的资源的能力,包 | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 否 | Abilityinfo相关信息 | -| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | 是 | 否 | 当前hap包的信息 | -| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 否 | 表示配置信息。 | +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 否 | UIAbility的相关信息。 | +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | 是 | 否 | 当前HAP包的信息。 | +| config | [Configuration](js-apis-app-ability-configuration.md) | 是 | 否 | 与UIAbility相关的配置信息,如语言、颜色模式等。 | + +> **关于示例代码的说明:** +> - 本文档中的示例,通过this.context获取UIAbilityContext,this代表的是继承自UIAbility的UIAbility实例,若需要在页面中使用UIAbilityContext的能力,请参照[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息) ## UIAbilityContext.startAbility @@ -32,7 +33,7 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| callback | AsyncCallback<void> | 是 | callback形式返回启动结果 | +| callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | **错误码:** @@ -84,7 +85,6 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; } ``` - ## UIAbilityContext.startAbility startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; @@ -150,7 +150,7 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -213,7 +213,7 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; try { this.context.startAbility(want, options) - .then((data) => { + .then(() => { // 执行正常业务 console.log('startAbility succeed'); }) @@ -224,12 +224,11 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` - ## UIAbilityContext.startAbilityForResult startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; @@ -292,7 +291,7 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -461,8 +460,8 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | -| callback | AsyncCallback\ | 是 | 启动Ability的回调函数,返回Ability结果。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | 是 | 启动Ability的回调函数,返回Ability结果。 | **错误码:** @@ -509,11 +508,11 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC } // 执行正常业务 console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + result.resultCode + ' result.want = ' + JSON.stringify(result.want)) }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -523,7 +522,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -启动一个Ability并在该Ability帐号销毁时返回执行结果(callback形式)。 +启动一个Ability并在该Ability销毁时返回执行结果(callback形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -536,9 +535,9 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | | options | [StartOptions](js-apis-app-ability-startOptions.md) | 是 | 启动Ability所携带的参数。 | -| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +| callback | AsyncCallback\ | 是 | 启动Ability后,Ability被销毁时的回调函数。 | **错误码:** @@ -579,7 +578,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp }; try { - this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error) => { if (error.code) { // 处理业务逻辑错误 console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + @@ -588,11 +587,11 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp } // 执行正常业务 console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + - result.resultCode) + result.resultCode + ' result.want = ' + JSON.stringify(result.want)) }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -602,7 +601,7 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -启动一个Ability并在该Ability帐号销毁时返回执行结果(promise形式)。 +启动一个Ability并在该Ability销毁时返回执行结果(promise形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -615,14 +614,14 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Promise<AbilityResult> | 返回一个Promise,包含Ability结果。 | +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Ability被销毁时的回调函数,包含Ability结果。 | **错误码:** @@ -736,7 +735,7 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -755,7 +754,7 @@ startServiceExtensionAbility(want: Want): Promise\; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| want | [Want](js-apis-application-want.md) | 是 | 启动ServiceExtensionAbility的want信息。 | **错误码:** @@ -785,7 +784,7 @@ startServiceExtensionAbility(want: Want): Promise\; try { this.context.startServiceExtensionAbility(want) - .then((data) => { + .then(() => { // 执行正常业务 console.log('startServiceExtensionAbility succeed'); }) @@ -796,7 +795,7 @@ startServiceExtensionAbility(want: Want): Promise\; }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -818,7 +817,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | **错误码:** @@ -858,7 +857,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -880,7 +879,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | **错误码:** @@ -923,7 +922,7 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -980,7 +979,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -999,7 +998,7 @@ stopServiceExtensionAbility(want: Want): Promise\; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | +| want | [Want](js-apis-application-want.md) | 是 | 停止ServiceExtensionAbility的want信息。 | **错误码:** @@ -1037,7 +1036,7 @@ stopServiceExtensionAbility(want: Want): Promise\; }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1046,7 +1045,7 @@ stopServiceExtensionAbility(want: Want): Promise\; stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -使用帐户停止同一应用程序内的服务(callback形式)。 +停止同一应用程序内指定账户的服务(callback形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -1058,9 +1057,9 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | -| callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +| want | [Want](js-apis-application-want.md) | 是 | 停止ServiceExtensionAbility的want信息。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | +| callback | AsyncCallback\ | 是 | 停止ServiceExtensionAbility的回调函数。 | **错误码:** @@ -1100,7 +1099,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1109,7 +1108,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -使用帐户停止同一应用程序内的服务(Promise形式)。 +停止同一应用程序内指定账户的服务(Promise形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -1121,8 +1120,8 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| want | [Want](js-apis-application-want.md) | 是 | 停止ServiceExtensionAbility的want信息。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | **错误码:** @@ -1162,7 +1161,7 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1179,7 +1178,7 @@ terminateSelf(callback: AsyncCallback<void>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | +| callback | AsyncCallback<void> | 是 | 停止Ability自身的回调函数。 | **错误码:** @@ -1195,16 +1194,22 @@ terminateSelf(callback: AsyncCallback<void>): void; **示例:** ```ts - this.context.terminateSelf((error) => { - if (error.code) { - // 处理业务逻辑错误 - console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + - ' error.message: ' + JSON.stringify(error.message)); - return; - } - // 执行正常业务 - console.log('terminateSelf succeed'); - }); + try { + this.context.terminateSelf((error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('terminateSelf succeed'); + }); + } catch (error) { + // 捕获同步的参数错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } ``` @@ -1236,14 +1241,22 @@ terminateSelf(): Promise<void>; **示例:** ```ts - this.context.terminateSelf().then((data) => { - // 执行正常业务 - console.log('terminateSelf succeed'); - }).catch((error) => { - // 处理业务逻辑错误 + try { + this.context.terminateSelf() + .then(() => { + // 执行正常业务 + console.log('terminateSelf succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (error) { + // 捕获同步的参数错误 console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + ' error.message: ' + JSON.stringify(error.message)); - }); + } ``` @@ -1300,7 +1313,7 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1365,7 +1378,7 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1374,7 +1387,7 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; -使用AbilityInfo.AbilityType.SERVICE模板将当前Ability连接到一个Ability。 +将当前Ability连接到一个使用AbilityInfo.AbilityType.SERVICE模板的Ability。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -1434,7 +1447,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -使用AbilityInfo.AbilityType.SERVICE模板和account将当前Ability连接到一个Ability。 +将当前Ability连接到一个使用AbilityInfo.AbilityType.SERVICE模板的指定account的Ability。 **需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -1447,7 +1460,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | | options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 否 | 远端对象实例。 | **返回值:** @@ -1498,7 +1511,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options disconnectServiceExtensionAbility(connection: number): Promise\; -断开连接(promise形式)。 +断开与ServiceExtensionAbility的连接(promise形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -1508,7 +1521,7 @@ disconnectServiceExtensionAbility(connection: number): Promise\; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| connection | number | 是 | 连接的Ability的数字代码。 | +| connection | number | 是 | 连接的ServiceExtensionAbility的数字代码,即connectServiceExtensionAbility返回的connectionId。 | **返回值:** @@ -1555,7 +1568,7 @@ disconnectServiceExtensionAbility(connection: number): Promise\; disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; -断开连接(callback形式)。 +断开与ServiceExtensionAbility的连接(callback形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -1565,7 +1578,7 @@ disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\ | 是 | 表示指定的回调方法。 | **错误码:** @@ -1694,7 +1707,7 @@ startAbilityByCall(want: Want): Promise<Caller>; startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -根据account启动Ability(callback形式)。 +根据accountId启动Ability(callback形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -1707,7 +1720,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | **错误码:** @@ -1768,7 +1781,7 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -根据account启动Ability(callback形式)。 +根据accountId及startOptions启动Ability(callback形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -1781,7 +1794,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。| +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。| | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | @@ -1836,7 +1849,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` @@ -1846,7 +1859,7 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -根据account启动Ability(Promise形式)。 +根据accountId和startOptions启动Ability(Promise形式)。 **需要权限**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -1859,7 +1872,7 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-want.md) | 是 | 启动Ability的want信息。 | -| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +| accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount)。 | | options | [StartOptions](js-apis-app-ability-startOptions.md) | 否 | 启动Ability所携带的参数。 | **错误码:** @@ -1913,13 +1926,16 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): }); } catch (paramError) { // 处理入参错误异常 - console.log('error.code: ' + JSON.stringify(paramError.code) + + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + ' error.message: ' + JSON.stringify(paramError.message)); } ``` ## UIAbilityContext.requestPermissionsFromUser +> **说明:** +> - 该接口自API version 9已废弃。 + requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; 拉起弹窗请求用户授权(callback形式)。 @@ -1946,6 +1962,9 @@ requestPermissionsFromUser(permissions: Array<string>, requestCallback: As ## UIAbilityContext.requestPermissionsFromUser +> **说明:** +> - 该接口自API version 9已废弃。 + requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; 拉起弹窗请求用户授权(promise形式)。 @@ -1995,7 +2014,7 @@ setMissionLabel(label: string, callback:AsyncCallback<void>): void; **示例:** ```ts - this.context.setMissionLabel("test",(result) => { + this.context.setMissionLabel("test", (result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index e2d95fca9f38d2f6a42a933a1f4a0d5ce5b11cb6..7ae6d88fe7ae60eb5e4c879e7ca13acd721d6ac8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -870,7 +870,7 @@ getActivePeers(): Promise\>; | 类型 | 说明 | | ------------------- | -------------------- | -| Promise\> | 返回获取的所有在线对端设备的PeerInfo | +| Promise\> | 返回获取的所有在线对端设备的PeerInfo | **示例:** @@ -906,7 +906,7 @@ getActivePeers(callback: AsyncCallback\>): void; | 类型 | 说明 | | ------------------- | -------------------- | -| callback: AsyncCallback\> | 返回获取的所有在线对端设备的PeerInfo | +| callback: AsyncCallback\> | 返回获取的所有在线对端设备的PeerInfo | **示例:** @@ -941,7 +941,7 @@ getAllPeers(): Promise\>; | 类型 | 说明 | | ------------------- | -------------------- | -| Promise\> | 返回获取的所有对端设备的PeerInfo | +| Promise\> | 返回获取的所有对端设备的PeerInfo | **示例:** @@ -977,7 +977,7 @@ getAllPeers(callback: AsyncCallback\>): void; | 类型 | 说明 | | ------------------- | -------------------- | -| callback: AsyncCallback\> | 返回获取的所有对端设备的PeerInfo | +| callback: AsyncCallback\> | 返回获取的所有对端设备的PeerInfo | **示例:** @@ -2539,9 +2539,9 @@ async function example() { | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | 是 | 是 | 检索条件,使用[FileKey](#filekey8)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | -| selectionArgs | Array<string> | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | 是 | 是 | 检索结果排序方式,使用[FileKey](#filekey8)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:
升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | +| selections | string | 是 | 是 | 检索条件,使用[FileKey](#filekey8)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | +| selectionArgs | Array<string> | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | +| order | string | 是 | 是 | 检索结果排序方式,使用[FileKey](#filekey8)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:
升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | | uri8+ | string | 是 | 是 | 文件URI | | networkId8+ | string | 是 | 是 | 注册设备网络ID | | extendArgs8+ | string | 是 | 是 | 扩展的检索参数,目前没有扩展检索参数 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-notification.md b/zh-cn/application-dev/reference/apis/js-apis-notification.md index 6d53569527ec0f4ca78c556e1f8f6c5e4e3dc582..0d772942b0f9301f331efc7d5237132f7f530a54 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -2,11 +2,11 @@ 本模块提供通知管理的能力,包括发布、取消发布通知,创建、获取、移除通知通道,订阅、取消订阅通知,获取通知的使能状态、角标使能状态,获取通知的相关信息等。 -一般情况下,只有系统应用具有通知订阅和取消订阅的权限。 - > **说明:** > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 通知订阅和取消订阅仅对系统应用开放。 ## 导入模块 @@ -26,13 +26,13 @@ publish(request: NotificationRequest, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 设置要发布通知内容的NotificationRequest对象。 | -| callback | AsyncCallback\ | 是 | 被指定的回调方法。 | +| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| callback | AsyncCallback\ | 是 | 发布通知的回调方法。 | **示例:** ```js -//publish回调 +// publish回调 function publishCallback(err) { if (err.code) { console.info("publish failed " + JSON.stringify(err)); @@ -40,7 +40,7 @@ function publishCallback(err) { console.info("publish success"); } } -//通知Request对象 +// 通知Request对象 var notificationRequest = { id: 1, content: { @@ -69,12 +69,12 @@ publish(request: NotificationRequest): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 设置要发布通知内容的NotificationRequest对象。 | +| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | **示例:** ```js -//通知Request对象 +// 通知Request对象 var notificationRequest = { notificationId: 1, content: { @@ -87,7 +87,7 @@ var notificationRequest = { } } Notification.publish(notificationRequest).then(() => { - console.info("publish sucess"); + console.info("publish success"); }); ``` @@ -96,7 +96,7 @@ Notification.publish(notificationRequest).then(() => { publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void -发布通知(callback形式)。 +发布通知给指定的用户(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -108,14 +108,14 @@ publish(request: NotificationRequest, userId: number, callback: AsyncCallback\ | 是 | 被指定的回调方法。 | **示例:** ```js -//publish回调 +// publish回调 function publishCallback(err) { if (err.code) { console.info("publish failed " + JSON.stringify(err)); @@ -123,9 +123,9 @@ function publishCallback(err) { console.info("publish success"); } } -// 接收通知的用户ID +// 用户ID var userId = 1 -//通知Request对象 +// 通知Request对象 var notificationRequest = { id: 1, content: { @@ -144,7 +144,7 @@ Notification.publish(notificationRequest, userId, publishCallback); publish(request: NotificationRequest, userId: number): Promise\ -发布通知(Promise形式)。 +发布通知给指定的用户(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -156,8 +156,8 @@ publish(request: NotificationRequest, userId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 设置要发布通知内容的NotificationRequest对象。 | -| userId | number | 是 | 接收通知用户的Id。 | +| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| userId | number | 是 | 用户ID。 | **示例:** @@ -177,7 +177,7 @@ var notificationRequest = { var userId = 1 Notification.publish(notificationRequest, userId).then(() => { - console.info("publish sucess"); + console.info("publish success"); }); ``` @@ -186,7 +186,7 @@ Notification.publish(notificationRequest, userId).then(() => { cancel(id: number, label: string, callback: AsyncCallback\): void -取消与指定id和label相匹配的已发布通知(callback形式)。 +通过通知ID和通知标签取消已发布的通知(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -201,7 +201,7 @@ cancel(id: number, label: string, callback: AsyncCallback\): void **示例:** ```js -//cancel回调 +// cancel回调 function cancelCallback(err) { if (err.code) { console.info("cancel failed " + JSON.stringify(err)); @@ -218,7 +218,7 @@ Notification.cancel(0, "label", cancelCallback) cancel(id: number, label?: string): Promise\ -取消与指定id相匹配的已发布通知,label可以指定也可以不指定(Promise形式)。 +取消与指定通知ID相匹配的已发布通知,label可以指定也可以不指定(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -233,7 +233,7 @@ cancel(id: number, label?: string): Promise\ ```js Notification.cancel(0).then(() => { - console.info("cancel sucess"); + console.info("cancel success"); }); ``` @@ -243,7 +243,7 @@ Notification.cancel(0).then(() => { cancel(id: number, callback: AsyncCallback\): void -取消与指定id相匹配的已发布通知(callback形式)。 +取消与指定通知ID相匹配的已发布通知(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -257,7 +257,7 @@ cancel(id: number, callback: AsyncCallback\): void **示例:** ```js -//cancel回调 +// cancel回调 function cancelCallback(err) { if (err.code) { console.info("cancel failed " + JSON.stringify(err)); @@ -287,7 +287,7 @@ cancelAll(callback: AsyncCallback\): void **示例:** ```js -//cancel回调 +// cancel回调 function cancelAllCallback(err) { if (err.code) { console.info("cancelAll failed " + JSON.stringify(err)); @@ -312,7 +312,7 @@ cancelAll(): Promise\ ```js Notification.cancelAll().then(() => { - console.info("cancelAll sucess"); + console.info("cancelAll success"); }); ``` @@ -340,7 +340,7 @@ addSlot(slot: NotificationSlot, callback: AsyncCallback\): void **示例:** ```js -//addslot回调 +// addslot回调 function addSlotCallBack(err) { if (err.code) { console.info("addSlot failed " + JSON.stringify(err)); @@ -348,7 +348,7 @@ function addSlotCallBack(err) { console.info("addSlot success"); } } -//通知slot对象 +// 通知slot对象 var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } @@ -378,12 +378,12 @@ addSlot(slot: NotificationSlot): Promise\ **示例:** ```js -//通知slot对象 +// 通知slot对象 var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.addSlot(notificationSlot).then(() => { - console.info("addSlot sucess"); + console.info("addSlot success"); }); ``` @@ -393,7 +393,7 @@ Notification.addSlot(notificationSlot).then(() => { addSlot(type: SlotType, callback: AsyncCallback\): void -创建通知通道(callback形式)。 +创建指定类型的通知通道(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -407,7 +407,7 @@ addSlot(type: SlotType, callback: AsyncCallback\): void **示例:** ```js -//addslot回调 +// addslot回调 function addSlotCallBack(err) { if (err.code) { console.info("addSlot failed " + JSON.stringify(err)); @@ -424,7 +424,7 @@ Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack addSlot(type: SlotType): Promise\ -创建通知通道(Promise形式)。 +创建指定类型的通知通道(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -438,7 +438,7 @@ addSlot(type: SlotType): Promise\ ```js Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { - console.info("addSlot sucess"); + console.info("addSlot success"); }); ``` @@ -466,7 +466,7 @@ addSlots(slots: Array\, callback: AsyncCallback\): voi **示例:** ```js -//addSlots回调 +// addSlots回调 function addSlotsCallBack(err) { if (err.code) { console.info("addSlots failed " + JSON.stringify(err)); @@ -474,11 +474,11 @@ function addSlotsCallBack(err) { console.info("addSlots success"); } } -//通知slot对象 +// 通知slot对象 var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -//通知slot array 对象 +// 通知slot array 对象 var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; @@ -508,16 +508,16 @@ addSlots(slots: Array\): Promise\ **示例:** ```js -//通知slot对象 +// 通知slot对象 var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -//通知slot array 对象 +// 通知slot array 对象 var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { - console.info("addSlots sucess"); + console.info("addSlots success"); }); ``` @@ -527,7 +527,7 @@ Notification.addSlots(notificationSlotArray).then(() => { getSlot(slotType: SlotType, callback: AsyncCallback\): void -获取一个通知通道(callback形式)。 +获取一个指定类型的通知通道(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -535,14 +535,14 @@ getSlot(slotType: SlotType, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| slotType | [SlotType](#slottype) | 是 | 通知渠道类型,目前分为社交通信、服务提醒、内容咨询和其他类型。 | +| slotType | [SlotType](#slottype) | 是 | 通知渠道类型,目前分为社交通信、服务提醒、内容咨询和其他类型。 | | callback | AsyncCallback\<[NotificationSlot](#notificationslot)\> | 是 | 表示被指定的回调方法。 | **示例:** ```js -//getSlot回调 -function getSlotCallback(err,data) { +// getSlot回调 +function getSlotCallback(err, data) { if (err.code) { console.info("getSlot failed " + JSON.stringify(err)); } else { @@ -559,7 +559,7 @@ Notification.getSlot(slotType, getSlotCallback) getSlot(slotType: SlotType): Promise\ -获取一个通知通道(Promise形式)。 +获取一个指定类型的通知通道(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -567,7 +567,7 @@ getSlot(slotType: SlotType): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | ----------------------------------------------------------- | -| slotType | [SlotType](#slottype) | 是 | 通知渠道类型,目前分为社交通信、服务提醒、内容咨询和其他类型。 | +| slotType | [SlotType](#slottype) | 是 | 通知渠道类型,目前分为社交通信、服务提醒、内容咨询和其他类型。 | **返回值:** @@ -580,7 +580,7 @@ getSlot(slotType: SlotType): Promise\ ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { - console.info("getSlot sucess, data: " + JSON.stringify(data)); + console.info("getSlot success, data: " + JSON.stringify(data)); }); ``` @@ -598,13 +598,13 @@ getSlots(callback: AsyncCallback>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | -------------------- | -| callback | AsyncCallback\\> | 是 | 表示被指定的回调方法。 | +| callback | AsyncCallback\\> | 是 | 以callback形式返回获取此应用程序的所有通知通道的结果。 | **示例:** ```js -//getSlots回调 -function getSlotsCallback(err,data) { +// getSlots回调 +function getSlotsCallback(err, data) { if (err.code) { console.info("getSlots failed " + JSON.stringify(err)); } else { @@ -634,7 +634,7 @@ getSlots(): Promise\> ```js Notification.getSlots().then((data) => { - console.info("getSlots sucess, data: " + JSON.stringify(data)); + console.info("getSlots success, data: " + JSON.stringify(data)); }); ``` @@ -644,7 +644,7 @@ Notification.getSlots().then((data) => { removeSlot(slotType: SlotType, callback: AsyncCallback\): void -根据通知通道类型删除创建的通知通道(callback形式)。 +删除指定类型的通知通道(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -658,7 +658,7 @@ removeSlot(slotType: SlotType, callback: AsyncCallback\): void **示例:** ```js -//removeSlot回调 +// removeSlot回调 function removeSlotCallback(err) { if (err.code) { console.info("removeSlot failed " + JSON.stringify(err)); @@ -676,7 +676,7 @@ Notification.removeSlot(slotType,removeSlotCallback) removeSlot(slotType: SlotType): Promise\ -根据通知通道类型删除创建的通知通道(Promise形式)。 +删除指定类型的通知通道(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -691,7 +691,7 @@ removeSlot(slotType: SlotType): Promise\ ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { - console.info("removeSlot sucess"); + console.info("removeSlot success"); }); ``` @@ -738,7 +738,7 @@ removeAllSlots(): Promise\ ```js Notification.removeAllSlots().then(() => { - console.info("removeAllSlots sucess"); + console.info("removeAllSlots success"); }); ``` @@ -761,13 +761,13 @@ subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, c | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ---------------- | | subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 是 | 订阅信息。 | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 是 | 通知订阅信息。 | | callback | AsyncCallback\ | 是 | 订阅动作回调函数。 | **示例:** ```js -//subscribe回调 +// subscribe回调 function subscribeCallback(err) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); @@ -782,7 +782,7 @@ var subscriber = { onConsume: onConsumeCallback } var info = { - bundleNames: ["bundleName1","bundleName2"] + bundleNames: ["bundleName1", "bundleName2"] } Notification.subscribe(subscriber, info, subscribeCallback); ``` @@ -793,7 +793,7 @@ Notification.subscribe(subscriber, info, subscribeCallback); subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void -订阅通知并指定订阅信息(callback形式)。 +订阅当前用户下所有应用的通知(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -846,7 +846,7 @@ subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ------------ | | subscriber | [NotificationSubscriber](#notificationsubscriber) | 是 | 通知订阅对象。 | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 否 | 订阅信息。 | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | 否 | 通知订阅信息。 | **示例:** @@ -858,7 +858,7 @@ var subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { - console.info("subscribe sucess"); + console.info("subscribe success"); }); ``` @@ -893,11 +893,11 @@ function unsubscribeCallback(err) { console.info("unsubscribe success"); } } -function onCancelCallback(data) { +function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onCancel: onCancelCallback + onDisconnect: onDisconnectCallback } Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -925,14 +925,14 @@ unsubscribe(subscriber: NotificationSubscriber): Promise\ **示例:** ```js -function onCancelCallback(data) { +function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onCancel: onCancelCallback + onDisconnect: onDisconnectCallback }; Notification.unsubscribe(subscriber).then(() => { - console.info("unsubscribe sucess"); + console.info("unsubscribe success"); }); ``` @@ -942,7 +942,7 @@ Notification.unsubscribe(subscriber).then(() => { enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -设定指定包的通知使能状态(Callback形式)。 +设定指定应用的通知使能状态(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -954,7 +954,7 @@ enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallbac | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | enable | boolean | 是 | 使能状态。 | | callback | AsyncCallback\ | 是 | 设定通知使能回调函数。 | @@ -980,7 +980,7 @@ Notification.enableNotification(bundle, false, enableNotificationCallback); enableNotification(bundle: BundleOption, enable: boolean): Promise\ -设定指定包的通知使能状态(Promise形式)。 +设定指定应用的通知使能状态(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -992,7 +992,7 @@ enableNotification(bundle: BundleOption, enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | enable | boolean | 是 | 使能状态。 | **示例:** @@ -1002,7 +1002,7 @@ var bundle = { bundle: "bundleName1", } Notification.enableNotification(bundle, false).then(() => { - console.info("enableNotification sucess"); + console.info("enableNotification success"); }); ``` @@ -1012,7 +1012,7 @@ Notification.enableNotification(bundle, false).then(() => { isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void -获取指定包的通知使能状态(Callback形式)。 +获取指定应用的通知使能状态(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1024,7 +1024,7 @@ isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | callback | AsyncCallback\ | 是 | 获取通知使能状态回调函数。 | **示例:** @@ -1049,7 +1049,7 @@ Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); isNotificationEnabled(bundle: BundleOption): Promise\ -获取指定包的通知使能状态(Promise形式)。 +获取指定应用的通知使能状态(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1061,13 +1061,13 @@ isNotificationEnabled(bundle: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取指定包的通知使能状态的结果。 | +| 类型 | 说明 | +| ------------------ | --------------------------------------------------- | +| Promise\ | 以Promise形式返回获取指定应用的通知使能状态的结果。 | **示例:** @@ -1076,7 +1076,7 @@ var bundle = { bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { - console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1132,7 +1132,7 @@ isNotificationEnabled(): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** @@ -1144,7 +1144,7 @@ isNotificationEnabled(): Promise\ ```js Notification.isNotificationEnabled().then((data) => { - console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1154,7 +1154,7 @@ Notification.isNotificationEnabled().then((data) => { displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -设定指定包的角标使能状态(Callback形式)。 +设定指定应用的角标使能状态(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1166,7 +1166,7 @@ displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\ | 是 | 设定角标使能回调函数。 | @@ -1192,7 +1192,7 @@ Notification.displayBadge(bundle, false, displayBadgeCallback); displayBadge(bundle: BundleOption, enable: boolean): Promise\ -设定指定包的角标使能状态(Promise形式)。 +设定指定应用的角标使能状态(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1204,7 +1204,7 @@ displayBadge(bundle: BundleOption, enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | enable | boolean | 是 | 使能状态。 | **示例:** @@ -1214,7 +1214,7 @@ var bundle = { bundle: "bundleName1", } Notification.displayBadge(bundle, false).then(() => { - console.info("displayBadge sucess"); + console.info("displayBadge success"); }); ``` @@ -1224,7 +1224,7 @@ Notification.displayBadge(bundle, false).then(() => { isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void -获取指定包的角标使能状态(Callback形式)。 +获取指定应用的角标使能状态(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1236,7 +1236,7 @@ isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | callback | AsyncCallback\ | 是 | 获取角标使能状态回调函数。 | **示例:** @@ -1261,7 +1261,7 @@ Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); isBadgeDisplayed(bundle: BundleOption): Promise\ -获取指定包的角标使能状态(Promise形式)。 +获取指定应用的角标使能状态(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1273,13 +1273,13 @@ isBadgeDisplayed(bundle: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** | 类型 | 说明 | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取指定包的角标使能状态。 | +| Promise\ | 以Promise形式返回获取指定应用的角标使能状态。 | **示例:** @@ -1288,7 +1288,7 @@ var bundle = { bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { - console.info("isBadgeDisplayed sucess, data: " + JSON.stringify(data)); + console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); }); ``` @@ -1298,7 +1298,7 @@ Notification.isBadgeDisplayed(bundle).then((data) => { setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void -设定指定包的通知通道状态(Callback形式)。 +设定指定应用的通知通道(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1310,7 +1310,7 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCal | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | slot | [NotificationSlot](#notificationslot) | 是 | 通知通道。 | | callback | AsyncCallback\ | 是 | 设定通知通道回调函数。 | @@ -1339,7 +1339,7 @@ Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ -设定指定包的通知通道状态(Promise形式)。 +设定指定应用的通知通道(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1351,8 +1351,8 @@ setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| slot | [NotificationSlot](#notificationslot) | 是 | 使能状态。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| slot | [NotificationSlot](#notificationslot) | 是 | 通知通道。 | **示例:** @@ -1364,7 +1364,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.setSlotByBundle(bundle, notificationSlot).then(() => { - console.info("setSlotByBundle sucess"); + console.info("setSlotByBundle success"); }); ``` @@ -1374,7 +1374,7 @@ Notification.setSlotByBundle(bundle, notificationSlot).then(() => { getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void -获取指定包的通知通道(Callback形式)。 +获取指定应用的所有通知通道(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1386,7 +1386,7 @@ getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback> | 是 | 获取通知通道回调函数。 | **示例:** @@ -1411,7 +1411,7 @@ Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); getSlotsByBundle(bundle: BundleOption): Promise> -获取指定包的通知通道(Promise形式)。 +获取指定应用的所有通知通道(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1423,13 +1423,13 @@ getSlotsByBundle(bundle: BundleOption): Promise> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** | 类型 | 说明 | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise> | 以Promise形式返回获取指定包的通知通道。 | +| Promise> | 以Promise形式返回获取指定应用的通知通道。 | **示例:** @@ -1438,7 +1438,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { - console.info("getSlotsByBundle sucess, data: " + JSON.stringify(data)); + console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -1448,7 +1448,7 @@ Notification.getSlotsByBundle(bundle).then((data) => { getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void -获取指定包的通知通道数(Callback形式)。 +获取指定应用的通知通道数量(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1460,8 +1460,8 @@ getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| callback | AsyncCallback\ | 是 | 获取通知通道数回调函数。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| callback | AsyncCallback\ | 是 | 获取通知通道数量回调函数。 | **示例:** @@ -1485,7 +1485,7 @@ Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); getSlotNumByBundle(bundle: BundleOption): Promise\ -获取指定包的通知通道数(Promise形式)。 +获取指定应用的通知通道数量(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1497,13 +1497,13 @@ getSlotNumByBundle(bundle: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | **返回值:** | 类型 | 说明 | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取指定包的通知通道数。 | +| Promise\ | 以Promise形式返回获取指定应用的通知通道数量。 | **示例:** @@ -1512,7 +1512,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { - console.info("getSlotNumByBundle sucess, data: " + JSON.stringify(data)); + console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -1534,7 +1534,7 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea | 参数名 | 类型 | 必填 | 说明 | | --------------- | ----------------------------------| ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | notificationKey | [NotificationKey](#notificationkey) | 是 | 通知键值。 | | reason | [RemoveReason](#removereason9) | 是 | 通知删除原因。 | | callback | AsyncCallback\ | 是 | 删除指定通知回调函数。 | @@ -1578,7 +1578,7 @@ remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveRea | 参数名 | 类型 | 必填 | 说明 | | --------------- | --------------- | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | | notificationKey | [NotificationKey](#notificationkey) | 是 | 通知键值。 | | reason | [RemoveReason](#removereason9) | 是 | 通知删除原因。 | @@ -1594,7 +1594,7 @@ var notificationKey = { } var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(bundle, notificationKey, reason).then(() => { - console.info("remove sucess"); + console.info("remove success"); }); ``` @@ -1616,7 +1616,7 @@ remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | 是 | 通知唯一ID。 | +| hashCode | string | 是 | 通知唯一ID。可以通过[onConsume](#onconsume)回调的入参[SubscribeCallbackData](#subscribecallbackdata)获取其内部[NotificationRequest](#notificationrequest)对象中的hashCode。 | | reason | [RemoveReason](#removereason9) | 是 | 通知删除原因。 | | callback | AsyncCallback\ | 是 | 删除指定通知回调函数。 | @@ -1663,7 +1663,7 @@ remove(hashCode: string, reason: RemoveReason): Promise\ var hashCode = 'hashCode' var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(hashCode, reason).then(() => { - console.info("remove sucess"); + console.info("remove success"); }); ``` @@ -1673,7 +1673,7 @@ Notification.remove(hashCode, reason).then(() => { removeAll(bundle: BundleOption, callback: AsyncCallback\): void -删除指定包的所有通知(Callback形式)。 +删除指定应用的所有通知(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1685,8 +1685,8 @@ removeAll(bundle: BundleOption, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| callback | AsyncCallback\ | 是 | 删除指定包的所有通知回调函数。 | +| bundle | [BundleOption](#bundleoption) | 是 | 指定应用的包信息。 | +| callback | AsyncCallback\ | 是 | 删除指定应用的所有通知回调函数。 | **示例:** @@ -1744,7 +1744,7 @@ Notification.removeAll(removeAllCallback); removeAll(bundle?: BundleOption): Promise\ -删除所有通知(Promise形式)。 +删除指定应用的所有通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1756,13 +1756,14 @@ removeAll(bundle?: BundleOption): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | 否 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 否 | 指定应用的包信息。 | **示例:** ```js +// 不指定应用时,删除所有通知 Notification.removeAll().then(() => { - console.info("removeAll sucess"); + console.info("removeAll success"); }); ``` @@ -1770,7 +1771,7 @@ Notification.removeAll().then(() => { removeAll(userId: number, callback: AsyncCallback\): void -删除所有通知(callback形式)。 +删除指定用户下的所有通知(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1782,8 +1783,8 @@ removeAll(userId: number, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| userId | number | 是 | 接收通知用户的Id。 | -| callback | AsyncCallback\ | 是 | 删除所有通知回调函数。 | +| userId | number | 是 | 用户ID。 | +| callback | AsyncCallback\ | 是 | 删除指定用户所有通知回调函数。 | **示例:** @@ -1797,7 +1798,6 @@ function removeAllCallback(err) { } var userId = 1 - Notification.removeAll(userId, removeAllCallback); ``` @@ -1805,7 +1805,7 @@ Notification.removeAll(userId, removeAllCallback); removeAll(userId: number): Promise\ -删除所有通知(Promise形式)。 +删除指定用户下的所有通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1817,22 +1817,15 @@ removeAll(userId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------ | ---- | ---------- | -| userId | number | 是 | 接收通知用户的Id。 | +| userId | number | 是 | 用户ID。 | **示例:** ```js -function removeAllCallback(err) { - if (err.code) { - console.info("removeAll failed " + JSON.stringify(err)); - } else { - console.info("removeAll success"); - } -} - var userId = 1 - -Notification.removeAll(userId, removeAllCallback); +Notification.removeAll(userId).then(() => { + console.info("removeAll success"); +}); ``` @@ -1840,7 +1833,7 @@ Notification.removeAll(userId, removeAllCallback); getAllActiveNotifications(callback: AsyncCallback>): void -获取活动通知(Callback形式)。 +获取当前未删除的所有通知(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1874,7 +1867,7 @@ Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); getAllActiveNotifications(): Promise\\> -获取活动通知(Promise形式)。 +获取当前未删除的所有通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1892,7 +1885,7 @@ getAllActiveNotifications(): Promise\ { - console.info("getAllActiveNotifications sucess, data: " + JSON.stringify(data)); + console.info("getAllActiveNotifications success, data: " + JSON.stringify(data)); }); ``` @@ -1902,7 +1895,7 @@ Notification.getAllActiveNotifications().then((data) => { getActiveNotificationCount(callback: AsyncCallback\): void -获取当前应用的活动通知数(Callback形式)。 +获取当前应用未删除的通知数(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1910,7 +1903,7 @@ getActiveNotificationCount(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---------------------- | -| callback | AsyncCallback\ | 是 | 获取活动通知数回调函数。 | +| callback | AsyncCallback\ | 是 | 获取未删除通知数回调函数。 | **示例:** @@ -1932,21 +1925,21 @@ Notification.getActiveNotificationCount(getActiveNotificationCountCallback); getActiveNotificationCount(): Promise\ -获取当前应用的活动通知数(Promise形式)。 +获取当前应用未删除的通知数(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取当前应用的活动通知数。 | +| 类型 | 说明 | +| ----------------- | ------------------------------------------- | +| Promise\ | 以Promise形式返回获取当前应用未删除通知数。 | **示例:** ```js Notification.getActiveNotificationCount().then((data) => { - console.info("getActiveNotificationCount sucess, data: " + JSON.stringify(data)); + console.info("getActiveNotificationCount success, data: " + JSON.stringify(data)); }); ``` @@ -1956,7 +1949,7 @@ Notification.getActiveNotificationCount().then((data) => { getActiveNotifications(callback: AsyncCallback>): void -获取当前应用的活动通知(Callback形式)。 +获取当前应用未删除的通知列表(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -1964,7 +1957,7 @@ getActiveNotifications(callback: AsyncCallback>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------ | -| callback | AsyncCallback> | 是 | 获取当前应用的活动通知回调函数。 | +| callback | AsyncCallback> | 是 | 获取当前应用通知列表回调函数。 | **示例:** @@ -1986,21 +1979,21 @@ Notification.getActiveNotifications(getActiveNotificationsCallback); getActiveNotifications(): Promise\\> -获取当前应用的活动通知(Promise形式)。 +获取当前应用未删除的通知列表(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\\> | 以Promise形式返回获取当前应用的活动通知。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------------- | +| Promise\\> | 以Promise形式返回获取当前应用通知列表。 | **示例:** ```js Notification.getActiveNotifications().then((data) => { - console.info("removeGroupByBundle sucess, data: " + JSON.stringify(data)); + console.info("removeGroupByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -2010,7 +2003,7 @@ Notification.getActiveNotifications().then((data) => { cancelGroup(groupName: string, callback: AsyncCallback\): void -取消本应用指定组通知(Callback形式)。 +取消本应用指定组下的通知(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2018,8 +2011,8 @@ cancelGroup(groupName: string, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ---------------------------- | -| groupName | string | 是 | 指定通知组名称。 | -| callback | AsyncCallback\ | 是 | 取消本应用指定组通知回调函数。 | +| groupName | string | 是 | 通知组名称,此名称需要在发布通知时通过[NotificationRequest](#notificationrequest)对象指定。 | +| callback | AsyncCallback\ | 是 | 取消本应用指定组下通知的回调函数。 | **示例:** @@ -2043,7 +2036,7 @@ Notification.cancelGroup(groupName, cancelGroupCallback); cancelGroup(groupName: string): Promise\ -取消本应用指定组通知(Promise形式)。 +取消本应用指定组下的通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2051,14 +2044,14 @@ cancelGroup(groupName: string): Promise\ | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | -------------- | -| groupName | string | 是 | 指定通知组名称。 | +| groupName | string | 是 | 通知组名称。 | **示例:** ```js var groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { - console.info("cancelGroup sucess"); + console.info("cancelGroup success"); }); ``` @@ -2068,7 +2061,7 @@ Notification.cancelGroup(groupName).then(() => { removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void -删除指定应用指定组通知(Callback形式)。 +删除指定应用的指定组下的通知(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2080,9 +2073,9 @@ removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCall | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| groupName | string | 是 | 指定通知组名称。 | -| callback | AsyncCallback\ | 是 | 删除本应用指定组通知回调函数。 | +| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| groupName | string | 是 | 通知组名称。 | +| callback | AsyncCallback\ | 是 | 删除指定应用指定组下通知的回调函数。 | **示例:** @@ -2107,7 +2100,7 @@ Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCal removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ -删除指定应用指定组通知(Promise形式)。 +删除指定应用的指定组下的通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2119,8 +2112,8 @@ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------ | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| groupName | string | 是 | 指定通知组名称。 | +| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| groupName | string | 是 | 通知组名称。 | **示例:** @@ -2128,7 +2121,7 @@ removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ var bundleOption = {bundle: "Bundle"}; var groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { - console.info("removeGroupByBundle sucess"); + console.info("removeGroupByBundle success"); }); ``` @@ -2179,7 +2172,7 @@ Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ -设置免打扰时间接口(Promise形式)。 +设置免打扰时间(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2202,7 +2195,7 @@ var doNotDisturbDate = { end: new Date(2021, 11, 15, 18, 0) } Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("setDoNotDisturbDate sucess"); + console.info("setDoNotDisturbDate success"); }); ``` @@ -2224,7 +2217,7 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallb | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------- | ---- | ---------------------- | | date | [DoNotDisturbDate](#donotdisturbdate8) | 是 | 免打扰时间选项。 | -| userId | number | 是 | 设置免打扰事件的用户ID。 | +| userId | number | 是 | 设置免打扰时间的用户ID。 | | callback | AsyncCallback\ | 是 | 设置免打扰时间回调函数。 | **示例:** @@ -2245,7 +2238,6 @@ var doNotDisturbDate = { } var userId = 1 - Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` @@ -2255,7 +2247,7 @@ Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCa setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ -指定用户设置免打扰时间接口(Promise形式)。 +指定用户设置免打扰时间(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2268,7 +2260,7 @@ setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ---------------- | ---- | -------------- | | date | [DoNotDisturbDate](#donotdisturbdate8) | 是 | 免打扰时间选项。 | -| userId | number | 是 | 设置免打扰事件的用户ID。 | +| userId | number | 是 | 设置免打扰时间的用户ID。 | **示例:** @@ -2282,7 +2274,7 @@ var doNotDisturbDate = { var userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { - console.info("setDoNotDisturbDate sucess"); + console.info("setDoNotDisturbDate success"); }); ``` @@ -2291,7 +2283,7 @@ Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { getDoNotDisturbDate(callback: AsyncCallback\): void -查询免打扰时间接口(Callback形式)。 +查询免打扰时间(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2308,7 +2300,7 @@ getDoNotDisturbDate(callback: AsyncCallback\): void **示例:** ```js -function getDoNotDisturbDateCallback(err,data) { +function getDoNotDisturbDateCallback(err, data) { if (err.code) { console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); } else { @@ -2325,7 +2317,7 @@ Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); getDoNotDisturbDate(): Promise\ -查询免打扰时间接口(Promise形式)。 +查询免打扰时间(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2335,15 +2327,15 @@ getDoNotDisturbDate(): Promise\ **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | 以Promise形式返回获取查询免打扰时间接口。 | +| 类型 | 说明 | +| ------------------------------------------------- | ----------------------------------------- | +| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | 以Promise形式返回获取查询到的免打扰时间。 | **示例:** ```js Notification.getDoNotDisturbDate().then((data) => { - console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` @@ -2352,7 +2344,7 @@ Notification.getDoNotDisturbDate().then((data) => { getDoNotDisturbDate(userId: number, callback: AsyncCallback\): void -指定用户查询免打扰时间接口(Callback形式)。 +查询指定用户的免打扰时间(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2365,7 +2357,7 @@ getDoNotDisturbDate(userId: number, callback: AsyncCallback\) | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ---------------------- | | callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | 是 | 查询免打扰时间回调函数。 | -| userId | number | 是 | 设置免打扰事件的用户ID。 | +| userId | number | 是 | 用户ID。 | **示例:** @@ -2389,7 +2381,7 @@ Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); getDoNotDisturbDate(userId: number): Promise\ -指定用户查询免打扰时间接口(Promise形式)。 +查询指定用户的免打扰时间(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2401,13 +2393,13 @@ getDoNotDisturbDate(userId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ---------------------- | -| userId | number | 是 | 设置免打扰事件的用户ID。 | +| userId | number | 是 | 用户ID。 | **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | 以Promise形式返回获取查询免打扰时间接口。 | +| 类型 | 说明 | +| ------------------------------------------------- | ----------------------------------------- | +| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | 以Promise形式返回获取查询到的免打扰时间。 | **示例:** @@ -2415,7 +2407,7 @@ getDoNotDisturbDate(userId: number): Promise\ var userId = 1 Notification.getDoNotDisturbDate(userId).then((data) => { - console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` @@ -2424,7 +2416,7 @@ Notification.getDoNotDisturbDate(userId).then((data) => { supportDoNotDisturbMode(callback: AsyncCallback\): void -查询是否支持勿扰模式功能(Callback形式)。 +查询是否支持免打扰功能(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2436,7 +2428,7 @@ supportDoNotDisturbMode(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------------------------------- | -| callback | AsyncCallback\ | 是 | 查询是否支持勿扰模式功能回调函数。 | +| callback | AsyncCallback\ | 是 | 查询是否支持免打扰功能回调函数。 | **示例:** @@ -2458,7 +2450,7 @@ Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); supportDoNotDisturbMode(): Promise\ -查询是否支持勿扰模式功能(Promise形式)。 +查询是否支持免打扰功能(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2470,13 +2462,13 @@ supportDoNotDisturbMode(): Promise\ | 类型 | 说明 | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取是否支持勿扰模式功能的结果。 | +| Promise\ | 以Promise形式返回获取是否支持免打扰功能的结果。 | **示例:** ```js Notification.supportDoNotDisturbMode().then((data) => { - console.info("supportDoNotDisturbMode sucess, data: " + JSON.stringify(data)); + console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); }); ``` @@ -2567,7 +2559,7 @@ function requestEnableNotificationCallback(err) { if (err.code) { console.info("requestEnableNotification failed " + JSON.stringify(err)); } else { - + console.info("requestEnableNotification success"); } }; @@ -2587,10 +2579,9 @@ requestEnableNotification(): Promise\ **示例:** ```javascript -Notification.requestEnableNotification() - .then(() => { - console.info("requestEnableNotification sucess"); - }); +Notification.requestEnableNotification().then(() => { + console.info("requestEnableNotification success"); +}); ``` @@ -2610,7 +2601,7 @@ enableDistributed(enable: boolean, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------------------------- | -| enable | boolean | 是 | 是否支持。
true 支持。
false 不支持。| +| enable | boolean | 是 | 是否支持。 | | callback | AsyncCallback\ | 是 | 设置设备是否支持分布式通知的回调函数。 | **示例:** @@ -2647,17 +2638,15 @@ enableDistributed(enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------------------------- | -| enable | boolean | 是 | 是否支持。
true 支持。
false 不支持。| +| enable | boolean | 是 | 是否支持。 | **示例:** ```javascript var enable = true - -Notification.enableDistributed(enable) - .then(() => { - console.info("enableDistributed sucess"); - }); +Notification.enableDistributed(enable).then(() => { + console.info("enableDistributed success"); +}); ``` @@ -2665,7 +2654,7 @@ Notification.enableDistributed(enable) isDistributedEnabled(callback: AsyncCallback\): void -获取设备是否支持分布式通知(Callback形式)。 +查询设备是否支持分布式通知(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2695,23 +2684,22 @@ Notification.isDistributedEnabled(isDistributedEnabledCallback); isDistributedEnabled(): Promise\ -获取设备是否支持分布式通知(Promise形式)。 +查询设备是否支持分布式通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification **返回值:** -| 类型 | 说明 | -| ------------------ | --------------- | -| Promise\ | Promise方式返回设备是否支持分布式通知的结果。
true 支持。
false 不支持。 | +| 类型 | 说明 | +| ------------------ | --------------------------------------------- | +| Promise\ | Promise方式返回设备是否支持分布式通知的结果。 | **示例:** ```javascript -Notification.isDistributedEnabled() - .then((data) => { - console.info("isDistributedEnabled sucess, data: " + JSON.stringify(data)); - }); +Notification.isDistributedEnabled().then((data) => { + console.info("isDistributedEnabled success, data: " + JSON.stringify(data)); +}); ``` @@ -2719,7 +2707,7 @@ Notification.isDistributedEnabled() enableDistributedByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -根据应用的包设置应用程序是否支持分布式通知(Callback形式)。 +设置指定应用是否支持分布式通知(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2731,7 +2719,7 @@ enableDistributedByBundle(bundle: BundleOption, enable: boolean, callback: Async | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 应用的包。 | +| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | | enable | boolean | 是 | 是否支持。 | | callback | AsyncCallback\ | 是 | 应用程序是否支持分布式通知的回调函数。 | @@ -2761,7 +2749,7 @@ Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundle enableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise\ -根据应用的包设置应用程序是否支持分布式通知(Promise形式)。 +设置指定应用是否支持分布式通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2784,11 +2772,9 @@ var bundle = { } var enable = true - -Notification.enableDistributedByBundle(bundle, enable) - .then(() => { - console.info("enableDistributedByBundle sucess"); - }); +Notification.enableDistributedByBundle(bundle, enable).then(() => { + console.info("enableDistributedByBundle success"); +}); ``` ## Notification.isDistributedEnabledByBundle8+ @@ -2808,7 +2794,7 @@ isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\ | 是 | 应用程序是否支持分布式通知的回调函数。 | +| callback | AsyncCallback\ | 是 | 查询指定应用是否支持分布式通知的回调函数。 | **示例:** @@ -2834,7 +2820,7 @@ Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCa isDistributedEnabledByBundle(bundle: BundleOption): Promise\ -根据应用的包获取应用程序是否支持分布式通知(Promise形式)。 +查询指定应用是否支持分布式通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -2850,9 +2836,9 @@ isDistributedEnabledByBundle(bundle: BundleOption): Promise\ **返回值:** -| 类型 | 说明 | -| ------------------ | --------------- | -| Promise\ | Promise方式返回应用程序是否支持分布式通知的结果。
true 支持。
false 不支持。 | +| 类型 | 说明 | +| ------------------ | ------------------------------------------------- | +| Promise\ | Promise方式返回指定应用是否支持分布式通知的结果。 | **示例:** @@ -2861,10 +2847,9 @@ var bundle = { bundle: "bundleName1", } -Notification.isDistributedEnabledByBundle(bundle) - .then((data) => { - console.info("isDistributedEnabledByBundle sucess, data: " + JSON.stringify(data)); - }); +Notification.isDistributedEnabledByBundle(bundle).then((data) => { + console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); +}); ``` @@ -2884,7 +2869,7 @@ getDeviceRemindType(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype8)\> | 是 | 获取通知的提醒方式的回调函数。 | +| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype8)\> | 是 | 获取通知提醒方式的回调函数。 | **示例:** @@ -2918,15 +2903,14 @@ getDeviceRemindType(): Promise\ | 类型 | 说明 | | ------------------ | --------------- | -| Promise\<[DeviceRemindType](#deviceremindtype8)\> | Promise方式返回通知的提醒方式的结果。 | +| Promise\<[DeviceRemindType](#deviceremindtype8)\> | Promise方式返回获取通知提醒方式的结果。 | **示例:** ```javascript -Notification.getDeviceRemindType() - .then((data) => { - console.info("getDeviceRemindType sucess, data: " + JSON.stringify(data)); - }); +Notification.getDeviceRemindType().then((data) => { + console.info("getDeviceRemindType success, data: " + JSON.stringify(data)); +}); ``` @@ -2944,18 +2928,18 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 设置要发布通知内容的NotificationRequest对象。 | -| representativeBundle | string | 是 | 被代理应用的包名。 | -| userId | number | 是 | 接收通知用户的Id。 | -| callback | AsyncCallback | 是 | 发布代理通知的回调方法。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------------- | ------------------------------------------- | ---- | ---------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | +| representativeBundle | string | 是 | 被代理应用的包名。 | +| userId | number | 是 | 用户ID。 | +| callback | AsyncCallback | 是 | 发布代理通知的回调方法。 | **示例:** ```js -//publishAsBundle回调 -function publishAsBundleCallback(err) { +// publishAsBundle回调 +function callback(err) { if (err.code) { console.info("publishAsBundle failed " + JSON.stringify(err)); } else { @@ -2964,10 +2948,10 @@ function publishAsBundleCallback(err) { } // 被代理应用的包名 let representativeBundle = "com.example.demo" -// 接收通知的用户ID +// 用户ID let userId = 100 -//通知Request对象 -let notificationRequest = { +// NotificationRequest对象 +let request = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -2979,7 +2963,7 @@ let notificationRequest = { } } -Notification.publishAsBundle(notificationRequest, representativeBundle, userId, publishAsBundleCallback); +Notification.publishAsBundle(request, representativeBundle, userId, callback); ``` ## Notification.publishAsBundle9+ @@ -2999,19 +2983,19 @@ publishAsBundle(request: NotificationRequest, representativeBundle: string, user | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | 是 | 设置要发布通知内容的NotificationRequest对象。 | +| request | [NotificationRequest](#notificationrequest) | 是 | 用于设置要发布通知的内容和相关配置信息。 | | representativeBundle | string | 是 | 被代理应用的包名。 | -| userId | number | 是 | 接收通知用户的Id。 | +| userId | number | 是 | 用户ID。 | **示例:** ```js // 被代理应用的包名 let representativeBundle = "com.example.demo" -// 接收通知的用户ID +// 用户ID let userId = 100 -//通知Request对象 -var notificationRequest = { +// NotificationRequest对象 +var request = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -3023,8 +3007,8 @@ var notificationRequest = { } } -Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { - console.info("publishAsBundle sucess"); +Notification.publishAsBundle(request, representativeBundle, userId).then(() => { + console.info("publishAsBundle success"); }); ``` @@ -3048,13 +3032,13 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number, callbac | -------------------- | ------------- | ---- | ------------------------ | | id | number | 是 | 通知ID。 | | representativeBundle | string | 是 | 被代理应用的包名。 | -| userId | number | 是 | 接收通知用户的Id。 | +| userId | number | 是 | 用户ID。 | | callback | AsyncCallback | 是 | 取消代理通知的回调方法。 | **示例:** ```js -//cancelAsBundle +// cancelAsBundle function cancelAsBundleCallback(err) { if (err.code) { console.info("cancelAsBundle failed " + JSON.stringify(err)); @@ -3064,7 +3048,7 @@ function cancelAsBundleCallback(err) { } // 被代理应用的包名 let representativeBundle = "com.example.demo" -// 接收通知的用户ID +// 用户ID let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); @@ -3074,7 +3058,7 @@ Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallb cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ -发布代理通知(Promise形式)。 +代理通知(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3090,14 +3074,14 @@ cancelAsBundle(id: number, representativeBundle: string, userId: number): Promis | -------------------- | ------ | ---- | ------------------ | | id | number | 是 | 通知ID。 | | representativeBundle | string | 是 | 被代理应用的包名。 | -| userId | number | 是 | 接收通知用户的Id。 | +| userId | number | 是 | 用户ID。 | **示例:** ```js // 被代理应用的包名 let representativeBundle = "com.example.demo" -// 接收通知的用户ID +// 用户ID let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { @@ -3109,7 +3093,7 @@ Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void -设定指定类型的渠道使能状态(Callback形式)。 +设置指定应用的指定渠道类型的使能状态(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3121,15 +3105,15 @@ enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, ca | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | +| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | | type | [SlotType](#slottype) | 是 | 指定渠道类型。 | | enable | boolean | 是 | 使能状态。 | -| callback | AsyncCallback\ | 是 | 设定渠道使能回调函数。 | +| callback | AsyncCallback\ | 是 | 设置渠道使能回调函数。 | **示例:** ```js -//enableNotificationSlot +// enableNotificationSlot function enableSlotCallback(err) { if (err.code) { console.info("enableNotificationSlot failed " + JSON.stringify(err)); @@ -3149,7 +3133,7 @@ Notification.enableNotificationSlot( enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ -设定指定类型的渠道使能状态(Promise形式)。 +设置指定应用的指定渠道类型的使能状态(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3161,27 +3145,25 @@ enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): P | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| type | [SlotType](#slottype) | 是 | 指定渠道类型。 | +| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| type | [SlotType](#slottype) | 是 | 渠道类型。 | | enable | boolean | 是 | 使能状态。 | **示例:** ```js -//enableNotificationSlot -Notification.enableNotificationSlot( - { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, - true).then(() => { - console.info("enableNotificationSlot sucess"); - }); +// enableNotificationSlot +Notification.enableNotificationSlot({ bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION,true).then(() => { + console.info("enableNotificationSlot success"); +}); ``` ## Notification.isNotificationSlotEnabled 9+ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void -获取指定类型的渠道使能状态(Callback形式)。 +获取指定应用的指定渠道类型的使能状态(Callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3193,14 +3175,14 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncC | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | 是 | 指定包信息。 | -| type | [SlotType](#slottype) | 是 | 指定渠道类型。 | -| callback | AsyncCallback\ | 是 | 设定渠道使能回调函数。 | +| bundle | [BundleOption](#bundleoption) | 是 | 应用的包信息。 | +| type | [SlotType](#slottype) | 是 | 渠道类型。 | +| callback | AsyncCallback\ | 是 | 获取渠道使能状态回调函数。 | **示例:** ```js -//isNotificationSlotEnabled +// isNotificationSlotEnabled function getEnableSlotCallback(err, data) { if (err.code) { console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); @@ -3219,7 +3201,7 @@ Notification.isNotificationSlotEnabled( isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ -获取指定类型的渠道使能状态(Promise形式)。 +获取指定应用的指定渠道类型的使能状态(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3231,25 +3213,23 @@ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ | 以Promise形式返回指定类型的渠道使能状态。 | +| 类型 | 说明 | +| ------------------ | ------------------------------- | +| Promise\ | 以Promise形式返回渠道使能状态。 | **示例:** ```js -//isNotificationSlotEnabled -Notification.isNotificationSlotEnabled( - { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION - ).then((data) => { - console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); - }); +// isNotificationSlotEnabled +Notification.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION).then((data) => { + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); +}); ``` @@ -3269,8 +3249,8 @@ setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | -------------- | -| userId | number | 是 | 用户Id。 | -| enable | boolean | 是 | 是否启用。
true:启用。
false:禁用。 | +| userId | number | 是 | 用户ID。 | +| enable | boolean | 是 | 是否启用。 | | callback | AsyncCallback\ | 是 | 设置是否将通知同步到未安装应用程序的设备的回调函数。 | **示例:** @@ -3279,7 +3259,7 @@ setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: let userId = 100; let enable = true; -function setSyncNotificationEnabledWithoutAppCallback(err) { +function callback(err) { if (err.code) { console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); } else { @@ -3287,7 +3267,7 @@ function setSyncNotificationEnabledWithoutAppCallback(err) { } } -Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); +Notification.setSyncNotificationEnabledWithoutApp(userId, enable, callback); ``` @@ -3307,8 +3287,8 @@ setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\< | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | -------------- | -| userId | number | 是 | 用户Id。 | -| enable | boolean | 是 | 是否启用。
true:启用。
false:禁用。 | +| userId | number | 是 | 用户ID。 | +| enable | boolean | 是 | 是否启用。 | **返回值:** @@ -3322,13 +3302,11 @@ setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\< let userId = 100; let enable = true; -Notification.setSyncNotificationEnabledWithoutApp(userId, enable) - .then(() => { - console.info('setSyncNotificationEnabledWithoutApp'); - }) - .catch((err) => { - console.info('setSyncNotificationEnabledWithoutApp, err:', err); - }); +Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { + console.info('setSyncNotificationEnabledWithoutApp success'); +}).catch((err) => { + console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); +}); ``` @@ -3336,7 +3314,7 @@ Notification.setSyncNotificationEnabledWithoutApp(userId, enable) getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void -获取是否同步通知到未安装应用程序的设备(callback形式)。 +获取同步通知到未安装应用程序设备的开关是否开启(callback形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3348,19 +3326,19 @@ getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\ | 是 | 设置是否将通知同步到未安装应用程序的设备的回调函数。
true: 是。
false: 否。 | +| userId | number | 是 | 用户ID。 | +| callback | AsyncCallback\ | 是 | 获取同步通知到未安装应用程序设备的开关是否开启的回调函数。 | **示例:** ```js let userId = 100; -function getSyncNotificationEnabledWithoutAppCallback(data, err) { +function getSyncNotificationEnabledWithoutAppCallback(err, data) { if (err) { - console.info('getSyncNotificationEnabledWithoutAppCallback, err' + err); + console.info('getSyncNotificationEnabledWithoutAppCallback, err:' + err); } else { - console.info('getSyncNotificationEnabledWithoutAppCallback, data' + data); + console.info('getSyncNotificationEnabledWithoutAppCallback, data:' + data); } } @@ -3372,7 +3350,7 @@ Notification.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEna getSyncNotificationEnabledWithoutApp(userId: number): Promise\ -获取是否同步通知到未安装应用程序的设备(Promise形式)。 +获取同步通知到未安装应用程序设备的开关是否开启(Promise形式)。 **系统能力**:SystemCapability.Notification.Notification @@ -3384,33 +3362,30 @@ getSyncNotificationEnabledWithoutApp(userId: number): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | -------------- | -| userId | number | 是 | 用户Id。 | +| userId | number | 是 | 用户ID。 | **返回值:** -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取是否同步通知到未安装应用程序的设备的结果。
true: 是。
false: 否。 | +| 类型 | 说明 | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | 以Promise形式返回获取同步通知到未安装应用程序设备的开关是否开启的结果。 | **示例:** ```js let userId = 100; - -Notification.getSyncNotificationEnabledWithoutApp(userId) - .then((data) => { - console.info('getSyncNotificationEnabledWithoutApp, data:', data); - }) - .catch((err) => { - console.info('getSyncNotificationEnabledWithoutApp, err:', err); - }); +Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { + console.info('getSyncNotificationEnabledWithoutApp, data:' + data); +}).catch((err) => { + console.info('getSyncNotificationEnabledWithoutApp, err:' + err); +}); ``` ## NotificationSubscriber -提供订阅者接收到新通知或取消通知时的回调方法。 +作为订阅通知接口[subscribe](#notificationsubscribe)的入参,提供订阅者接收到新通知、取消通知等的回调方法。 **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -3418,7 +3393,7 @@ Notification.getSyncNotificationEnabledWithoutApp(userId) onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void -接收通知回调函数。 +接收到新通知的回调函数。 **系统能力**:SystemCapability.Notification.Notification @@ -3428,7 +3403,7 @@ onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | 是 | 回调返回接收到的通知信息。 | +| data | [SubscribeCallbackData](#subscribecallbackdata) | 是 | 新接收到的通知信息。 | **示例:** @@ -3442,7 +3417,6 @@ function subscribeCallback(err) { }; function onConsumeCallback(data) { - console.info('===> onConsume in test'); let req = data.request; console.info('===> onConsume callback req.id:' + req.id); }; @@ -3458,7 +3432,7 @@ Notification.subscribe(subscriber, subscribeCallback); onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void -删除通知回调函数。 +取消通知的回调函数。 **系统能力**:SystemCapability.Notification.Notification @@ -3468,7 +3442,7 @@ onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| data | [SubscribeCallbackData](#subscribecallbackdata) | 是 | 回调返回接收到的通知信息。 | +| data | [SubscribeCallbackData](#subscribecallbackdata) | 是 | 需要取消的通知信息。 | **示例:** @@ -3482,7 +3456,6 @@ function subscribeCallback(err) { }; function onCancelCallback(data) { - console.info('===> onCancel in test'); let req = data.request; console.info('===> onCancel callback req.id:' + req.id); } @@ -3498,7 +3471,7 @@ Notification.subscribe(subscriber, subscribeCallback); onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void -更新通知排序回调函数。 +更新通知排序的回调函数。 **系统能力**:SystemCapability.Notification.Notification @@ -3508,7 +3481,7 @@ onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void | 参数名 | 类型 | 必填 | 说明 | | ------------ | ------------------------ | ---- | -------------------------- | -| data | [NotificationSortingMap](#notificationsortingmap) | 是 | 回调返回接收到的通知信息。 | +| data | [NotificationSortingMap](#notificationsortingmap) | 是 | 最新的通知排序列表。 | **示例:** @@ -3521,8 +3494,8 @@ function subscribeCallback(err) { } }; -function onUpdateCallback() { - console.info('===> onUpdate in test'); +function onUpdateCallback(map) { + console.info('===> onUpdateCallback map:' + JSON.stringify(map)); } var subscriber = { @@ -3536,7 +3509,7 @@ Notification.subscribe(subscriber, subscribeCallback); onConnect?:() => void -注册订阅回调函数。 +订阅完成的回调函数。 **系统能力**:SystemCapability.Notification.Notification @@ -3568,7 +3541,7 @@ Notification.subscribe(subscriber, subscribeCallback); onDisconnect?:() => void -取消订阅回调函数。 +取消订阅的回调函数。 **系统能力**:SystemCapability.Notification.Notification @@ -3584,16 +3557,30 @@ function subscribeCallback(err) { console.info("subscribeCallback"); } }; +function unsubscribeCallback(err) { + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribeCallback"); + } +}; +function onConnectCallback() { + console.info('===> onConnect in test'); +} function onDisconnectCallback() { console.info('===> onDisconnect in test'); } var subscriber = { + onConnect: onConnectCallback, onDisconnect: onDisconnectCallback }; +// 订阅通知后会收到onConnect回调 Notification.subscribe(subscriber, subscribeCallback); +// 取消订阅后会收到onDisconnect回调 +Notification.unsubscribe(subscriber, unsubscribeCallback); ``` ### onDestroy @@ -3632,7 +3619,7 @@ Notification.subscribe(subscriber, subscribeCallback); onDoNotDisturbDateChange?:(mode: notification.[DoNotDisturbDate](#donotdisturbdate8)) => void -免打扰时间选项变更回调函数。 +免打扰时间选项发生变更时的回调函数。 **系统能力**:SystemCapability.Notification.Notification @@ -3654,15 +3641,24 @@ function subscribeCallback(err) { } }; -function onDoNotDisturbDateChangeCallback() { - console.info('===> onDoNotDisturbDateChange in test'); +function onDoNotDisturbDateChangeCallback(mode) { + console.info('===> onDoNotDisturbDateChange:' + mode); } var subscriber = { onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback }; - Notification.subscribe(subscriber, subscribeCallback); + +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} +// 设置一个新的免打扰时间选项时触发onDoNotDisturbDateChange回调 +Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { + console.info("setDoNotDisturbDate sucess"); +}); ``` @@ -3694,16 +3690,23 @@ function subscribeCallback(err) { }; function onEnabledNotificationChangedCallback(callbackData) { - console.info("bundle: ", callbackData.bundle); - console.info("uid: ", callbackData.uid); - console.info("enable: ", callbackData.enable); + console.info("bundle: " + callbackData.bundle); + console.info("uid: " + callbackData.uid); + console.info("enable: " + callbackData.enable); }; var subscriber = { onEnabledNotificationChanged: onEnabledNotificationChangedCallback }; - Notification.subscribe(subscriber, subscribeCallback); + +var bundle = { + bundle: "bundleName1", +} +// 设置指定应用通知使能状态触发onEnabledNotificationChanged回调 +Notification.enableNotification(bundle, false).then(() => { + console.info("enableNotification sucess"); +}); ``` ## SubscribeCallbackData @@ -3715,7 +3718,7 @@ Notification.subscribe(subscriber, subscribeCallback); | 名称 | 类型 | 可读 | 可写 | 说明 | | --------------- | ------------------------------------------------- | ---- | --- | -------- | | request | [NotificationRequest](#notificationrequest) | 是 | 否 | 通知内容。 | -| sortingMap | [NotificationSortingMap](#notificationsortingmap) | 是 | 否 | 排序信息。 | +| sortingMap | [NotificationSortingMap](#notificationsortingmap) | 是 | 否 | 通知排序信息。 | | reason | number | 是 | 否 | 删除原因。 | | sound | string | 是 | 否 | 通知声音。 | | vibrationValues | Array\ | 是 | 否 | 通知震动。 | @@ -3740,13 +3743,11 @@ Notification.subscribe(subscriber, subscribeCallback); **系统API**:此接口为系统接口,三方应用不支持调用。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| ----- ------------------------------------- || ---- | --- | ------------------------ | -| type | [DoNotDisturbType](#donotdisturbtype8) | 是 | 否 | 指定免打扰设置的时间类型。 | -| begin | Date | 是 | 否 | 指定免打扰设置的起点时间。 | -| end | Date | 是 | 否 | 指定免打扰设置的终点时间。 | - - +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | -------------------------------------- | ---- | ---- | ---------------------- | +| type | [DoNotDisturbType](#donotdisturbtype8) | 是 | 是 | 免打扰设置的时间类型。 | +| begin | Date | 是 | 是 | 免打扰设置的起点时间。 | +| end | Date | 是 | 是 | 免打扰设置的终点时间。 | ## DoNotDisturbType8+ @@ -3793,8 +3794,8 @@ Notification.subscribe(subscriber, subscribeCallback); | 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ |---- | --- | ------ | -| bundle | string | 是 | 是 | 包名。 | -| uid | number | 是 | 是 | 用户id。 | +| bundle | string | 是 | 是 | 应用的包信息。 | +| uid | number | 是 | 是 | 用户ID。 | @@ -3830,7 +3831,7 @@ Notification.subscribe(subscriber, subscribeCallback); | 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ----------------------------------------------- | --- | ---- | ------------------------- | | title | string | 是 | 是 | 按钮标题。 | -| wantAgent | WantAgent | 是 | 是 | 点击按钮时触发的WantAgent。 | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | 点击按钮时触发的WantAgent。 | | extras | { [key: string]: any } | 是 | 是 | 按钮扩展信息。 | | userInput8+ | [NotificationUserInput](#notificationuserinput8) | 是 | 是 | 用户输入对象实例。 | @@ -3845,7 +3846,7 @@ Notification.subscribe(subscriber, subscribeCallback); | -------------- | ------ | ---- | ---- | ---------------------------------- | | title | string | 是 | 是 | 通知标题。 | | text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知次要内容,是对通知内容的补充。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | ## NotificationLongTextContent @@ -3858,7 +3859,7 @@ Notification.subscribe(subscriber, subscribeCallback); | -------------- | ------ | ---- | --- | -------------------------------- | | title | string | 是 | 是 | 通知标题。 | | text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知次要内容,是对通知内容的补充。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | | longText | string | 是 | 是 | 通知的长文本。 | | briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | | expandedTitle | string | 是 | 是 | 通知展开时的标题。 | @@ -3874,7 +3875,7 @@ Notification.subscribe(subscriber, subscribeCallback); | -------------- | --------------- | --- | --- | -------------------------------- | | title | string | 是 | 是 | 通知标题。 | | text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知次要内容,是对通知内容的补充。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | | briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | | longTitle | string | 是 | 是 | 通知展开时的标题。 | | lines | Array\ | 是 | 是 | 通知的多行文本。 | @@ -3890,10 +3891,10 @@ Notification.subscribe(subscriber, subscribeCallback); | -------------- | -------------- | ---- | --- | -------------------------------- | | title | string | 是 | 是 | 通知标题。 | | text | string | 是 | 是 | 通知内容。 | -| additionalText | string | 是 | 是 | 通知次要内容,是对通知内容的补充。 | +| additionalText | string | 是 | 是 | 通知附加内容,是对通知内容的补充。 | | briefText | string | 是 | 是 | 通知概要内容,是对通知内容的总结。 | | expandedTitle | string | 是 | 是 | 通知展开时的标题。 | -| picture | image.PixelMap | 是 | 是 | 通知的图片内容。 | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知的图片内容。 | ## NotificationContent @@ -3934,8 +3935,8 @@ Notification.subscribe(subscriber, subscribeCallback); | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------------- | ---------------------- | ---- | ---- | --------------------------------- | -| soundEnabled | NotificationFlagStatus | 是 | 否 | 是否启用声音提示。 | -| vibrationEnabled | NotificationFlagStatus | 是 | 否 | 是否启用振动提醒功能。 | +| soundEnabled | [NotificationFlagStatus](#notificationflagstatus8) | 是 | 否 | 是否启用声音提示。 | +| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus8) | 是 | 否 | 是否启用振动提醒功能。 | ## NotificationRequest @@ -3954,11 +3955,11 @@ Notification.subscribe(subscriber, subscribeCallback); | deliveryTime | number | 是 | 是 | 通知发送时间。 | | tapDismissed | boolean | 是 | 是 | 通知是否自动清除。 | | autoDeletedTime | number | 是 | 是 | 自动清除的时间。 | -| wantAgent | WantAgent | 是 | 是 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | | extraInfo | {[key: string]: any} | 是 | 是 | 扩展参数。 | -| color | number | 是 | 是 | 通知背景颜色。暂不支持。 | -| colorEnabled | boolean | 是 | 是 | 通知背景颜色是否使能。暂不支持。 | -| isAlertOnce | boolean | 是 | 是 | 设置是否仅有一次此通知警报。 | +| color | number | 是 | 是 | 通知背景颜色。预留能力,暂未支持。 | +| colorEnabled | boolean | 是 | 是 | 通知背景颜色是否使能。预留能力,暂未支持。 | +| isAlertOnce | boolean | 是 | 是 | 设置是否仅有一次此通知提醒。 | | isStopwatch | boolean | 是 | 是 | 是否显示已用时间。 | | isCountDown | boolean | 是 | 是 | 是否显示倒计时时间。 | | isFloatingIcon | boolean | 是 | 是 | 是否显示状态栏图标。 | @@ -3966,8 +3967,8 @@ Notification.subscribe(subscriber, subscribeCallback); | badgeIconStyle | number | 是 | 是 | 通知角标类型。 | | showDeliveryTime | boolean | 是 | 是 | 是否显示分发时间。 | | actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | 是 | 是 | 通知按钮,最多两个按钮。 | -| smallIcon | PixelMap | 是 | 是 | 通知小图标。(可选字段,大小不超过30KB) | -| largeIcon | PixelMap | 是 | 是 | 通知大图标。(可选字段,大小不超过30KB) | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知小图标。可选字段,大小不超过30KB。 | +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | 是 | 通知大图标。可选字段,大小不超过30KB。 | | creatorBundleName | string | 是 | 否 | 创建通知的包名。 | | creatorUid | number | 是 | 否 | 创建通知的UID。 | | creatorPid | number | 是 | 否 | 创建通知的PID。 | @@ -3981,7 +3982,7 @@ Notification.subscribe(subscriber, subscribeCallback); | distributedOption8+ | [DistributedOptions](#distributedoptions8) | 是 | 是 | 分布式通知的选项。 | | deviceId8+ | string | 是 | 否 | 通知源的deviceId。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | | notificationFlags8+ | [NotificationFlags](#notificationflags8) | 是 | 否 | 获取NotificationFlags。 | -| removalWantAgent9+ | WantAgent | 是 | 是 | 当移除通知时,通知将被重定向到的WantAgent实例。 | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | 是 | 是 | 当移除通知时,通知将被重定向到的WantAgent实例。 | | badgeNumber9+ | number | 是 | 是 | 应用程序图标上显示的通知数。 | ## DistributedOptions8+ @@ -3993,8 +3994,8 @@ Notification.subscribe(subscriber, subscribeCallback); | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------------------- | -------------- | ---- | ---- | ---------------------------------- | | isDistributed | boolean | 是 | 是 | 是否为分布式通知。 | -| supportDisplayDevices | Array\ | 是 | 是 | 可以同步通知到的设备类型。 | -| supportOperateDevices | Array\ | 是 | 是 | 可以打开通知的设备。 | +| supportDisplayDevices | Array\ | 是 | 是 | 可以同步通知到的设备列表。 | +| supportOperateDevices | Array\ | 是 | 是 | 可以打开通知的设备列表。 | | remindType | number | 是 | 否 | 通知的提醒方式。
**系统API**: 此接口为系统接口,三方应用不支持调用。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md index 91aea9501f91f557e4b40015353ff6f09baeb9b9..ec4eea276e6879f5d95b34f3d03d2b909d0854b5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notificationManager.md @@ -3589,7 +3589,7 @@ getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\ { if (fileAsset != undefined) { @@ -178,7 +178,7 @@ async function example() { } else { console.info('createPhotoAsset failed, message = ', err); } - }) + }); } ``` @@ -203,7 +203,7 @@ createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): ```ts async function example() { - console.info('createPhotoAssetDemo') + console.info('createPhotoAssetDemo'); let testFileName = "testFile" + Date.now() + ".jpg"; mgr.createPhotoAsset(testFileName, (err, fileAsset) => { if (fileAsset != undefined) { @@ -212,7 +212,7 @@ async function example() { } else { console.info('createPhotoAsset failed, message = ', err); } - }) + }); } ``` @@ -243,10 +243,10 @@ createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset&g ```ts async function example() { - console.info('createPhotoAssetDemo') + console.info('createPhotoAssetDemo'); try { let testFileName = "testFile" + Date.now() + ".jpg"; - let fileAsset = await mgr.createPhotoAsset(testFileName) + let fileAsset = await mgr.createPhotoAsset(testFileName); console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } catch (err) { @@ -279,7 +279,7 @@ getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResul import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPhotoAlbumsDemo') + console.info('getPhotoAlbumsDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let albumFetchOptions = { predicates: predicates @@ -294,11 +294,11 @@ async function example() { } else { console.info('album is undefined, err = ', err); } - }) + }); } else { console.info('getPhotoAlbums fail, message = ', err); } - }) + }); } ``` @@ -330,7 +330,7 @@ getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>& import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPhotoAlbumsDemo') + console.info('getPhotoAlbumsDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let albumFetchOptions = { predicates: predicates @@ -368,7 +368,7 @@ getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult&l ```ts async function example() { - console.info('getPrivateAlbumDemo') + console.info('getPrivateAlbumDemo'); mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { if (fetchResult != undefined) { let trashAlbum = await fetchResult.getFirstObject(); @@ -459,7 +459,7 @@ async function example() { } else { console.info('fetchFileResult fail' + err); } - }) + }); } ``` @@ -499,7 +499,7 @@ async function example() { predicates: predicates }; try { - var fetchResult = await mgr.getAudioAssets(fetchOptions) + var fetchResult = await mgr.getAudioAssets(fetchOptions); } catch (err) { console.info('getAudioAssets failed, message = ', err); } @@ -517,7 +517,7 @@ async function example() { delete(uri: string, callback: AsyncCallback<void>): void; -删除媒体文件,删除的文件进入到回收站。 +删除媒体文件,删除的文件进入到回收站。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -536,7 +536,7 @@ delete(uri: string, callback: AsyncCallback<void>): void; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('deleteAssetDemo') + console.info('deleteAssetDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOptions = { fetchColumns: [], @@ -546,11 +546,11 @@ async function example() { const fetchResult = await mgr.getPhotoAssets(fetchOptions); var asset = await fetchResult.getFirstObject(); } catch (err) { - console.info('fetch failed, message =', err) + console.info('fetch failed, message =', err); } if (asset == undefined) { - console.error('asset not exist') + console.error('asset not exist'); return; } mgr.delete(asset.uri, (err) => { @@ -590,7 +590,7 @@ delete(uri: string): Promise<void>; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('deleteDemo') + console.info('deleteDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOptions = { fetchColumns: [], @@ -600,11 +600,11 @@ async function example() { const fetchResult = await mgr.getPhotoAssets(fetchOptions); var asset = await fetchResult.getFirstObject(); } catch (err) { - console.info('fetch failed, message =', err) + console.info('fetch failed, message =', err); } if (asset == undefined) { - console.error('asset not exist') + console.error('asset not exist'); return; } try { @@ -635,7 +635,7 @@ on(type: ChangeEvent, callback: Callback<void>): void ```ts async function example() { - console.info('onDemo') + console.info('onDemo'); let count = 0; mgr.on('imageChange', () => { count++; @@ -680,7 +680,7 @@ off(type: ChangeEvent, callback?: Callback<void>): void ```ts async function example() { - console.info('offDemo') + console.info('offDemo'); let count = 0; mgr.on('imageChange', () => { count++; @@ -726,15 +726,15 @@ getActivePeers(callback: AsyncCallback<Array<PeerInfo>>): void; ```ts async function example() { - console.info('getActivePeersDemo') + console.info('getActivePeersDemo'); mgr.getActivePeers((err, devicesInfo) => { if (devicesInfo != undefined) { - console.log('getActivePeers succeed.') + console.log('getActivePeers succeed.'); for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('getActivePeers failed. message = ', err) + console.info('getActivePeers failed. message = ', err); } }); } @@ -758,19 +758,19 @@ getActivePeers(): Promise<Array<PeerInfo>>; ```ts async function example() { - console.info('getActivePeersDemo') + console.info('getActivePeersDemo'); try { var devicesInfo = await mgr.getActivePeers(); } catch (err) { - console.info('getActivePeers failed. message = ', err) + console.info('getActivePeers failed. message = ', err); } if (devicesInfo != undefined) { - console.log('getActivePeers succeed.') + console.log('getActivePeers succeed.'); for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail') + console.info('get distributed fail'); } } ``` @@ -793,15 +793,15 @@ getAllPeers(callback: AsyncCallback<Array<PeerInfo>>): void; ```ts async function example() { - console.info('getAllPeersDemo') + console.info('getAllPeersDemo'); mgr.getAllPeers((err, devicesInfo) => { if (devicesInfo != undefined) { - console.log('getAllPeers succeed.') + console.log('getAllPeers succeed.'); for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('getAllPeers failed. message = ', err) + console.info('getAllPeers failed. message = ', err); } }); } @@ -825,19 +825,19 @@ getAllPeers(): Promise<Array<PeerInfo>>; ```ts async function example() { - console.info('getAllPeersDemo') + console.info('getAllPeersDemo'); try { var devicesInfo = await mgr.getAllPeers(); } catch (err) { - console.info('getAllPeers failed. message = ', err) + console.info('getAllPeers failed. message = ', err); } if (devicesInfo != undefined) { - console.log('getAllPeers succeed.') + console.log('getAllPeers succeed.'); for (let i = 0; i < devicesInfo.length; i++) { console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); } } else { - console.info('get distributed fail') + console.info('get distributed fail'); } } ``` @@ -868,7 +868,7 @@ async function example() { } else { console.info('release ok.'); } - }) + }); } ``` @@ -920,7 +920,7 @@ async function example() { get(member: string): MemberType; -获取FileAsset成员参数 +获取FileAsset成员参数。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -936,7 +936,7 @@ get(member: string): MemberType; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('fileAssetGetDemo') + console.info('fileAssetGetDemo'); try { let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -945,8 +945,8 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE - let fileAssetTitle = fileAsset.get(title.toString()) + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); } catch (err) { console.info('release failed. message = ', err); @@ -958,7 +958,7 @@ async function example() { set(member: string, value: string): void; -设置FileAsset成员参数 +设置FileAsset成员参数。 **系统能力**:SystemCapability.FileManagement.UserFileManager.Core @@ -975,7 +975,7 @@ set(member: string, value: string): void; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('fileAssetSetDemo') + console.info('fileAssetSetDemo'); try { let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -984,8 +984,8 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE - fileAsset.set(title.toString(), "newTitle") + let title = userFileManager.ImageVideoKey.TITLE; + fileAsset.set(title.toString(), "newTitle"); } catch (err) { console.info('release failed. message = ', err); } @@ -1014,7 +1014,7 @@ commitModify(callback: AsyncCallback<void>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('commitModifyDemo') + console.info('commitModifyDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1022,13 +1022,13 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE - let fileAssetTitle = fileAsset.get(title.toString()) + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); - fileAsset.set(title.toString(), "newTitle") + fileAsset.set(title.toString(), "newTitle"); fileAsset.commitModify((err) => { if (err == undefined) { - let newFileAssetTitle = fileAsset.get(title.toString()) + let newFileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); } else { console.info('commitModify failed, message =', err); @@ -1059,7 +1059,7 @@ commitModify(): Promise<void> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('commitModifyDemo') + console.info('commitModifyDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1067,13 +1067,13 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - let title = userFileManager.ImageVideoKey.TITLE - let fileAssetTitle = fileAsset.get(title.toString()) + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); - fileAsset.set(title.toString(), "newTitle") + fileAsset.set(title.toString(), "newTitle"); try { - await fileAsset.commitModify() - let newFileAssetTitle = fileAsset.get(title.toString()) + await fileAsset.commitModify(); + let newFileAssetTitle = fileAsset.get(title.toString()); console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); } catch (err) { console.info('release failed. message = ', err); @@ -1087,7 +1087,7 @@ open(mode: string, callback: AsyncCallback<number>): void 打开当前文件,使用callback方式返回异步结果。 -**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放 +**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO @@ -1105,13 +1105,13 @@ open(mode: string, callback: AsyncCallback<number>): void ```ts async function example() { - console.info('openDemo') + console.info('openDemo'); let testFileName = "testFile" + Date.now() + ".jpg"; const fileAsset = await mgr.createPhotoAsset(testFileName); fileAsset.open('rw', (err, fd) => { if (fd != undefined) { console.info('File fd' + fd); - fileAsset.close(fd) + fileAsset.close(fd); } else { console.info('File err' + err); } @@ -1125,7 +1125,7 @@ open(mode: string): Promise<number> 打开当前文件,使用promise方式返回异步结果。 -**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放 +**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO @@ -1147,14 +1147,14 @@ open(mode: string): Promise<number> ```ts async function example() { - console.info('openDemo') + console.info('openDemo'); try { let testFileName = "testFile" + Date.now() + ".jpg"; const fileAsset = await mgr.createPhotoAsset(testFileName); - let fd = await fileAsset.open('rw') + let fd = await fileAsset.open('rw'); if (fd != undefined) { console.info('File fd' + fd); - fileAsset.close(fd) + fileAsset.close(fd); } else { console.info(' open File fail'); } @@ -1185,7 +1185,7 @@ close(fd: number, callback: AsyncCallback<void>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('closeDemo') + console.info('closeDemo'); try { let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -1235,7 +1235,7 @@ close(fd: number): Promise<void> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('closeDemo') + console.info('closeDemo'); try { let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -1246,7 +1246,7 @@ async function example() { const asset = await fetchResult.getFirstObject(); let fd = await asset.open('rw'); console.info('file fd', fd); - await asset.close(fd) + await asset.close(fd); console.info('asset close succeed.'); } catch (err) { console.info('close failed, message = ' + err); @@ -1276,7 +1276,7 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getThumbnailDemo') + console.info('getThumbnailDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1284,7 +1284,7 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); const asset = await fetchResult.getFirstObject(); - console.info('asset displayName = ', asset.displayName) + console.info('asset displayName = ', asset.displayName); asset.getThumbnail((err, pixelMap) => { if (err == undefined) { console.info('getThumbnail successful ' + pixelMap); @@ -1318,7 +1318,7 @@ getThumbnail(size: image.Size, callback: AsyncCallback<image.PixelMap>): v import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getThumbnailDemo') + console.info('getThumbnailDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1327,7 +1327,7 @@ async function example() { let size = { width: 720, height: 720 }; let fetchResult = await mgr.getPhotoAssets(fetchOption); const asset = await fetchResult.getFirstObject(); - console.info('asset displayName = ', asset.displayName) + console.info('asset displayName = ', asset.displayName); asset.getThumbnail(size, (err, pixelMap) => { if (err == undefined) { console.info('getThumbnail successful ' + pixelMap); @@ -1366,7 +1366,7 @@ getThumbnail(size?: image.Size): Promise<image.PixelMap> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getThumbnailDemo') + console.info('getThumbnailDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1375,7 +1375,7 @@ async function example() { let size = { width: 720, height: 720 }; let fetchResult = await mgr.getPhotoAssets(fetchOption); const asset = await fetchResult.getFirstObject(); - console.info('asset displayName = ', asset.displayName) + console.info('asset displayName = ', asset.displayName); asset.getThumbnail(size).then((pixelMap) => { console.info('getThumbnail successful ' + pixelMap); }).catch((err) => { @@ -1407,7 +1407,7 @@ favorite(isFavorite: boolean, callback: AsyncCallback<void>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('favoriteDemo') + console.info('favoriteDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1453,7 +1453,7 @@ favorite(isFavorite: boolean): Promise<void> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('favoriteDemo') + console.info('favoriteDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1493,7 +1493,7 @@ getCount(): number import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getCountDemo') + console.info('getCountDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1501,7 +1501,7 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); const fetchCount = fetchResult.getCount(); - console.info('fetchCount = ', fetchCount) + console.info('fetchCount = ', fetchCount); } ``` @@ -1556,7 +1556,7 @@ close(): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('fetchResultCloseDemo') + console.info('fetchResultCloseDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1592,7 +1592,7 @@ getFirstObject(callback: AsyncCallback<T>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getFirstObjectDemo') + console.info('getFirstObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1601,7 +1601,7 @@ async function example() { let fetchResult = await mgr.getPhotoAssets(fetchOption); fetchResult.getFirstObject((err, fileAsset) => { if (fileAsset != undefined) { - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } else { console.info("fileAsset failed with err:" + err); } @@ -1621,7 +1621,7 @@ getFirstObject(): Promise<T> | 类型 | 说明 | | --------------------------------------- | -------------------------- | -| Promise<T> | Promise方式返回。 | +| Promise<T> | Promise方式返回 | **示例**: @@ -1629,7 +1629,7 @@ getFirstObject(): Promise<T> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getFirstObjectDemo') + console.info('getFirstObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1637,7 +1637,7 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getFirstObject(); - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } ``` @@ -1661,7 +1661,7 @@ async function example() { import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getNextObjectDemo') + console.info('getNextObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1672,7 +1672,7 @@ async function example() { if (fetchResult.isAfterLast()) { fetchResult.getNextObject((err, fileAsset) => { if (fileAsset != undefined) { - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } else { console.info("fileAsset failed with err:" + err); } @@ -1701,7 +1701,7 @@ async function example() { import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getNextObjectDemo') + console.info('getNextObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1711,7 +1711,7 @@ async function example() { await fetchResult.getFirstObject(); if (fetchResult.isAfterLast()) { let fileAsset = await fetchResult.getNextObject(); - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } } ``` @@ -1736,7 +1736,7 @@ getLastObject(callback: AsyncCallback<T>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getLastObjectDemo') + console.info('getLastObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1745,7 +1745,7 @@ async function example() { let fetchResult = await mgr.getPhotoAssets(fetchOption); fetchResult.getLastObject((err, fileAsset) => { if (fileAsset != undefined) { - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } else { console.info("fileAsset failed with err:" + err); } @@ -1773,7 +1773,7 @@ getLastObject(): Promise<T> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getLastObjectDemo') + console.info('getLastObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1781,7 +1781,7 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getLastObject(); - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } ``` @@ -1806,7 +1806,7 @@ getPositionObject(index: number, callback: AsyncCallback<T>): void import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPositionObjectDemo') + console.info('getPositionObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1815,7 +1815,7 @@ async function example() { let fetchResult = await mgr.getPhotoAssets(fetchOption); fetchResult.getPositionObject(0, (err, fileAsset) => { if (fileAsset != undefined) { - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } else { console.info("fileAsset failed with err:" + err); } @@ -1849,7 +1849,7 @@ getPositionObject(index: number): Promise<T> import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('getPositionObjectDemo') + console.info('getPositionObjectDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { fetchColumns: [], @@ -1857,7 +1857,7 @@ async function example() { }; let fetchResult = await mgr.getPhotoAssets(fetchOption); let fileAsset = await fetchResult.getPositionObject(0); - console.info('fileAsset displayName: ', fileAsset.displayName) + console.info('fileAsset displayName: ', fileAsset.displayName); } ``` @@ -1881,7 +1881,7 @@ async function example() { getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -获取相册中的文件。该方法使用callback形式来返回文件 +获取相册中的文件。该方法使用callback形式来返回文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO @@ -1900,7 +1900,7 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumGetFileAssetsDemoCallback') + console.info('albumGetFileAssetsDemoCallback'); let predicates = new dataSharePredicates.DataSharePredicates(); let albumFetchOptions = { @@ -1925,7 +1925,7 @@ async function example() { getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -获取相册中的文件。该方法使用Promise来返回文件 +获取相册中的文件。该方法使用Promise来返回文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO @@ -1944,7 +1944,7 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumGetFileAssetsDemoPromise') + console.info('albumGetFileAssetsDemoPromise'); let predicates = new dataSharePredicates.DataSharePredicates(); let albumFetchOptions = { @@ -1986,7 +1986,7 @@ commitModify(callback: AsyncCallback<void>): void; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumCommitModifyDemo') + console.info('albumCommitModifyDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let albumFetchOptions = { predicates: predicates @@ -2026,7 +2026,7 @@ commitModify(): Promise<void>; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('albumCommitModifyDemo') + console.info('albumCommitModifyDemo'); let predicates = new dataSharePredicates.DataSharePredicates(); let albumFetchOptions = { predicates: predicates @@ -2047,7 +2047,8 @@ async function example() { ``` ## PrivateAlbum -系统相册 + +系统相册。 ### 属性 @@ -2065,7 +2066,7 @@ async function example() { getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -获取系统相册中的文件。该方法使用callback形式来返回文件 +获取系统相册中的文件。该方法使用callback形式来返回文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO @@ -2084,7 +2085,7 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('privateAlbumGetFileAssetsDemoCallback') + console.info('privateAlbumGetFileAssetsDemoCallback'); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -2107,7 +2108,7 @@ async function example() { getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -获取系统相册中的文件。该方法使用Promise来返回文件 +获取系统相册中的文件。该方法使用Promise来返回文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO @@ -2131,7 +2132,7 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('privateAlbumGetFileAssetsDemoPromise') + console.info('privateAlbumGetFileAssetsDemoPromise'); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -2148,7 +2149,7 @@ async function example() { delete(uri: string, callback: AsyncCallback<void>): void; -删除系统相册中的文件 +删除系统相册中的文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -2191,7 +2192,7 @@ async function example() { delete(uri: string): Promise<void>; -删除系统相册中的文件 +删除系统相册中的文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -2215,7 +2216,7 @@ delete(uri: string): Promise<void>; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('privateAlbumDeleteDemoPromise') + console.info('privateAlbumDeleteDemoPromise'); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -2238,7 +2239,7 @@ async function example() { recover(uri: string, callback: AsyncCallback<void>): void; -恢复系统相册中的文件 +恢复系统相册中的文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -2281,7 +2282,7 @@ async function example() { recover(uri: string): Promise<void>; -恢复系统相册中的文件 +恢复系统相册中的文件。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -2305,7 +2306,7 @@ recover(uri: string): Promise<void>; import dataSharePredicates from '@ohos.data.dataSharePredicates'; async function example() { - console.info('privateAlbumRecoverDemoPromise') + console.info('privateAlbumRecoverDemoPromise'); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index 5c7c72542afd36379f4f8fc2dab46d84347163c7..5ce015beec6af2e213f2ad20efb7753152a9035a 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -2121,6 +2121,42 @@ that.decode(array).then(val=>{ }) ``` +## ScopeType8+ + +用于表示范围中的值的类型。该类型的值,类型可以为ScopeComparable或number。 + +ScopeComparable类型的值需要实现compareTo方法,确保传入的数据具有可比性。 + +```js +interface ScopeComparable{ + compareTo(other: ScopeComparable): boolean; +} +type ScopeType = ScopeComparable | number; +``` + + +构造新类,实现compareTo方法。后续示例代码中,均通过Temperature,获取[ScopeType](#scopetype8)的实例化对象。 + + +示例: +```js +class Temperature{ + constructor(value){ + // 当使用ts语言开发时,需要补充以下代码: + // private readonly _temp: Temperature; + this._temp = value; + } + compareTo(value){ + return this._temp >= value.getTemp(); + } + getTemp(){ + return this._temp; + } + toString(){ + return this._temp.toString(); + } +} +``` ## types8+ @@ -3860,43 +3896,6 @@ entries(): IterableIterator<[K,V]> let result = pro[Symbol.iterator](); ``` -### ScopeType8+ - -用于表示范围中的值的类型。该类型的值,类型可以为ScopeComparable或number。 - -ScopeComparable类型的值需要实现compareTo方法,确保传入的数据具有可比性。 - -```js -interface ScopeComparable{ - compareTo(other: ScopeComparable): boolean; -} -type ScopeType = ScopeComparable | number; -``` - - -构造新类,实现compareTo方法。后续示例代码中,均通过Temperature,获取[ScopeType](#scopetype8)的实例化对象。 - - -示例: -```js -class Temperature{ - constructor(value){ - // 当使用ts语言开发时,需要补充以下代码: - // private readonly _temp: Temperature; - this._temp = value; - } - compareTo(value){ - return this._temp >= value.getTemp(); - } - getTemp(){ - return this._temp; - } - toString(){ - return this._temp.toString(); - } -} -``` - ## Scope(deprecated) > **说明:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md index 45f290e0358618e1831a5f83d3f1aca24f9f8583..53e174701707ee071cad97c77062c1ddc4282ba6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @@ -84,7 +84,7 @@ getIdSync(wallpaperType: WallpaperType): number | 类型 | 说明 | | -------- | -------- | -| number | 返回壁纸的ID。如果配置了这种壁纸类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1~2^31-1。 | +| number | 返回壁纸的ID。如果配置了这种壁纸类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1到(2^31-1)。 | **示例**: @@ -385,7 +385,7 @@ getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调函数,调用成功则返回壁纸图片的像素图大小,调用失败则返回error信息。 | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调函数,调用成功则返回壁纸图片的像素图对象,调用失败则返回error信息。 | **示例:** @@ -422,7 +422,7 @@ getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> | 类型 | 说明 | | -------- | -------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | 调用成功则返回壁纸图片的像素图大小,调用失败则返回error信息。 | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | 调用成功则返回壁纸图片的像素图对象,调用失败则返回error信息。 | **示例:** @@ -568,7 +568,7 @@ getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 | -| callback | AsyncCallback<number> | 是 | 回调函数,返回壁纸的ID。如果配置了指定类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1~2^31-1。 | +| callback | AsyncCallback<number> | 是 | 回调函数,返回壁纸的ID。如果配置了指定类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1到(2^31-1)。 | **示例:** @@ -604,7 +604,7 @@ getId(wallpaperType: WallpaperType): Promise<number> | 类型 | 说明 | | -------- | -------- | -| Promise<number> | 壁纸的ID。如果配置了这种壁纸类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1~2^31-1。 | +| Promise<number> | 壁纸的ID。如果配置了这种壁纸类型的壁纸就返回一个大于等于0的数,否则返回-1。取值范围是-1到(2^31-1)。 | **示例:** @@ -1123,7 +1123,7 @@ getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.Pixel | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | 是 | 壁纸类型。 | -| callback | AsyncCallback<image.PixelMap> | 是 | 回调函数,调用成功则返回壁纸图片的像素图大小,调用失败则返回error信息。 | +| callback | AsyncCallback<image.PixelMap> | 是 | 回调函数,调用成功则返回壁纸图片的像素图对象,调用失败则返回error信息。 | **示例:** @@ -1163,7 +1163,7 @@ getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> | 类型 | 说明 | | -------- | -------- | -| Promise<image.PixelMap> | 调用成功则返回壁纸图片的像素图大小,调用失败则返回error信息。 | +| Promise<image.PixelMap> | 调用成功则返回壁纸图片的像素图对象,调用失败则返回error信息。 | **示例:** diff --git a/zh-cn/contribute/OpenHarmony-build-rule.md b/zh-cn/contribute/OpenHarmony-build-rule.md new file mode 100644 index 0000000000000000000000000000000000000000..d27ef7e672da0c4ddeb0ab399a1634edbbdb29bc --- /dev/null +++ b/zh-cn/contribute/OpenHarmony-build-rule.md @@ -0,0 +1,597 @@ +# 开源构建规范 + +## 概述 + +为指导OpenHarmony的开发者开展构建工作,提升构建系统的可重复性、可维护性,提高产品构建质量,构建规范工作组分析总结了各种典型的构建问题,提炼相应的构建规则和建议,制订了本规范。 + +## 构建总体原则 + +**P01 构建过程自动化,从构建启动开始到构建最终结束,中间过程不能手工干预。** +手工操作容易出错,且浪费时间。将所有的构建操作变成自动化的,从而使构建变得高效、可靠。 + +**P02 构建工程和构建环境代码化。** +使用高阶构建框架CMake/Maven/Gradle等描述构建工程;使用Ansible/Dockerfile等描述构建环境。 +使用高阶构建框架的目的是向构建人员隐藏构建系统的复杂性。 + +**P03 构建过程可重复、可追溯。** +管理构建依赖,始终显式指定固定依赖版本号,确保构建依赖版本一致;将构建环境信息/构建工程作为配置项纳入配置管理,确保构建工程可追溯。 + +**P04 构建脚本简洁清晰,易于维护。** +构建脚本也是代码,构建脚本首先是为阅读它的人而编写的,好的脚本应当可以像故事一样发声朗诵出来。 + +**P05 构建标准化** +构建目录结构、构建依赖、构建初始化、构建入口、命名等进行标准化约束,使得公司所有产品、平台和组件的构建风格一致,便于构建管理和维护。 + +## 构建工程 + +### 公共规则 + +#### 一键式构建 + +##### G.COM.01 采用构建脚本,按照交付单元实现一键式自动化构建。 + +一键式自动化构建是指同一个构建环境下,从构建启动开始到最终结束(最终交付的包生成),中间过程禁止人工干预。 +人工干预活动包括但不限于:构建过程中,使用IDE界面进行手工设置、创建或者删除文件目录、创建文件、复制文件、移动文件、删除或者重命名文件、手工设置文件属性、压缩/解压缩文件等。 +交付单元是指可独立编译、加载、部署和运行的产品/平台/组件。 + +【级别】要求 + +【描述】一键式构建大幅降低构建人员操作复杂度。 + +【错误示例】某组件的一键式构建只能通过CI系统触发,没有一键式的本地构建。 + +【错误示例】某组件需要在Xplorer IDE界面手工设置内存映射地址后,再手工编译。 + +【错误示例】某组件需要手工创建r6c03_view\r6c03_client_view目录。 + +【正确示例】使用python脚本自动化创建目录: + +```python +dir_src = os.getcwd() +dir_client_view = r"r6c03_client_view" +# 处理路径使用os.path可以屏蔽系统差异 +dir_mk = os.path.join(dir_src, dir_client_view) + +cmd = "{0} {1}".format("mkdir", dir_mk) +cmd_re = subprocess.run(cmd) +``` + +#### 构建目录 + +##### G.COM.02 构建过程中禁止删除或修改源代码文件及其目录结构。 + +【级别】禁止 + +【描述】 + +- 构建过程中删除或修改源代码目录结构,会导致构建过程不可重复。 + +- 构建过程中,构建输出(包括目标文件、临时文件和构建日志)不能污染源码目录; + +- 构建过程中,避免修改源文件,包括但不限于拷贝、移动、执行dos2unix进行了源代码的格式转换等,源文件的修改应该在构建前的代码准备阶段完成; + +- 工具自动生成源代码应该在构建前的准备阶段完成,如果构建过程中使用工具自动生成源代码,工具自动生成的源代码必须和已有源代码目录隔离,以便区分高价值的源代码和低价值的可重新生成的代码,降低构建系统的复杂性。 + +【例外】构建补丁时,可能会新增或调整部分源代码。 + +##### G.COM.12 构建过程中创建的文件和目录应提供合适的权限。 + +【级别】要求 + +【描述】构建过程中可能需要创建目标系统的目录或文件,这些目录和文件应符合权限最小化的设计。 +例如,构建过程中应尽量避免在Linux系统中创建“777”权限的目录或文件。 + +Linux系统中常见的目录文件和权限可以参考《Linux安全配置操作规范》。 + +#### 构建初始化 + +##### G.COM.03 每个组件提供clean命令。 + +- 当clean不带任何参数时,清除该层级构建工程下的所有目标文件、临时文件和构建日志,并递归调用下层构建工程的clean,使该构建工程恢复到初始状态; +- 当clean带参数时,只清除与之对应的构建生成的目标文件、临时文件和构建日志。 + +【级别】要求 + +【描述】构建前进行clean是为了避免本次构建受到历史构建残留文件和构建日志的影响,确保构建可重复。必须支持不带任何参数clean;带参数的clean,是为了满足日常交付过程和开发人员本地构建的诉求,不作强制要求。 + +【正确示例】 + +``` +base_dir + |---build.suffix + |---logs + |---component_depository_1 + |---build.suffix + |---logs + |---component_depository_2 + |---build.suffix + |---logs + +#不带参数 +base_dir/build.suffix clean +#....分别调用component_depository_1和component_depository_2的clean + +#带参数:组件名 +base_dir/build.suffix clean component_depository_1 +#....调用component_depository_1的clean + +#带参数 +component_depository_1/build.suffix clean makebin hert umpt +#....调用component_depository_1的umpt单板链接任务的clean,支持详细参数的clean主要应用于内部开发和构建。 +``` + +##### G.COM.04 每个组件发布构建,必须保证构建环境中没有历史构建遗留件。 + +【级别】要求 + +【描述】首次下载代码,构建环境已经初始化,构建环境本身确保没有历史构建遗留件,可以不用执行clean命令;如果执行过构建的,必须使用clean命令清除历史构建遗留件。 + +#### 全量构建 + +##### G.COM.05 对于版本发布构建,归档的产品全量交付件(含所依赖的所有平台和组件)必须全部重新编译,禁止使用增量编译,禁止使用手工替换文件等方式修改安装盘。 + +版本发布构建是指产品(含所依赖的所有平台和组件)对外正式发布版本的构建。 + +【级别】要求 + +【描述】修改文件后增量编译,会导致部分二进制文件没有更新,造成新的安全编译选项未集成到版本,编译结果不一致。手工替换文件可能会造成构建不可重复、不一致。 + + +#### 构建配置 + +构建配置数据和构建脚本分离,避免构建工程架构腐化。源码路径、编译选项、目标文件路径等配置与构建脚本放到不同的文件,降低构建脚本维护成本。 + +##### G.COM.06 禁止使用与操作系统强绑定的文件(如excel)作为构建配置文件。建议使用跨平台的标准配置文件(如XML)来存放配置选项。 + +【级别】要求 + +【描述】使用excel作为配置文件带来的问题: + +- 产品和平台编译过程中,使用excel作为配置文件,都将调用微软的OfficeAPI,每次访问excel表格都会在后台打开excel,处理速度慢。 + +- 大量的excel配置需要手动点界面进行操作,可管理性差。 + +#### 构建日志 + +##### G.COM.07 构建输出的日志简洁明晰,构建日志的格式为时间戳+模块名(可选)+日志信息等级+日志内容。 +【级别】要求 + +【描述】建议时间戳格式采取“日期和时间”,如"MM/dd/yyyy HH:mm:ss"。 + +日志信息等级分为error/warning/informational,级别可以全写,也可以简写;对应的简写为: + +| 级别(大小写都可以)| 简写(大小写都可以)| +| :---------: | :--------------------------: | +| error | ERROR | +| warning | WARN | +| information | INFO | + +建议使用“[]”作分隔符。 + +【正确示例】 +[05/21/2020 00:12:40] [ERROR] mkdir: cannot create directory Permission denied. + +【例外】整个日志由工具自动输出的,可用使用以下方式跳过整个日志文件:在日志的最前方(尽可能靠前)输出"This project is built using "+工具名,如"This project is built using CMake."。 + +##### G.COM.08 构建日志出现error信息表示构建失败,必须终止构建。 + +【级别】要求 + +【描述】出现error信息一般是需要人工干预的构建错误,例如配置的环境变量错误,工具的版本错误,操作系统错误等等;或者软件源代码不对。对于版本发布构建,必须消除构建过程中所有的error消息,不允许屏蔽构建error信息。 + +【错误示例】某组件构建成功,但构建日志中包含大量的fail、Critical、cannot、not found、missing、no input files等异常信息,令人困惑。 + +##### G.COM.09 构建日志文件只保留本次构建的日志,避免本次构建的日志与历史构建的日志混淆。 + +【级别】要求 + +【描述】构建日志文件保留历史构建日志会导致混淆错误,比如:最新构建是失败的,由于保留有历史成功构建日志,会误认为最新这次构建是成功的。 + +##### G.COM.10 每条日志建议增加对应的模块名,用于问题的快速定界。 + +【级别】建议 + +【描述】在日志量较大时,很难快速锁定问题责任模块,需要在日志上加以区分。 + +【例外】CMake等工具的原生日志,因为输出带有对应模块路径,可以界定问题边界,不用特殊增加模块名维测信息。 + +#### 构建用户 + +##### G.COM.11 禁止使用超级管理员用户root和系统用户执行构建,应该使用普通user账户执行构建。 + +【级别】要求 + +【描述】超级管理员用户root和系统用户具有比较高的系统权限,使用此类账户执行构建可能导致构建环境被篡改。 + +安装态可以使用root用户;执行态使用普通user账户,如果需要使用sudo提升权限的,请遵守《身份和访问管理安全设计规范》。 + +#### 构建输出文件 + +##### G.COM.12 构建输出文件命名后缀遵守业界约定。 + +【级别】要求 + +【描述】错误的后缀命名令人误解。 + +对lib库、obj等构建输出文件的文件缀,应遵从构建工具默认的命名规则。 + +【错误示例】某文本文件命名为XXX.lib。 + +【错误示例】某object文件命名为XXX.a。 + +【错误示例】某静态库命名无后缀,命名为libxxx。 + +【正确示例】业界如下网址可以查询常见的文件后缀命名约定:http://www.fileextension.org/ , https://fileinfo.com/ , https://www.file-extensions.org/, http://file-extension.net/ 。 + +下面是一些常见的文件后缀的命名约定: + +| 文件后缀名 | 类型约定 | 文件后缀名 | 类型约定 | +| ---------- | -------------------- | ---------- | --------------- | +| .a | 静态库 | .so | 动态库 | +| .o | object文件 | .7z | 7zip压缩文件 | +| .tar | tar存档文件 | .gz/.gzip | GNU压缩存档文件 | +| .pack | java pack200压缩文件 | .rar/.rar5 | rar压缩包 | + +### C/C++构建工程 + +#### 构建目录 + +##### G.C&C++.01 构建目录结构标准化。 + +构建目录按用途分为源树Source Tree、构建中间件树Build Tree、构建安装树Install Tree三种。 + +- Source Tree是保存源码和构建脚本的目录。 +- Build Tree是保存构建中间件的目录,目录名称一般为"build"。 +- Install Tree是保存构建发布件的目录,目录名称固定为"output"。 + +Source Tree、Build Tree和Install Tree目录隔离,互相不重叠,没有交集,即不允许一个目录同时承担两种及以上的用途,譬如一个目录既作为Source Tree存放源码,又作为Build Tree存放编译中间件,这是不允许的。 + +Source Tree包含下列文件和目录: + +- 构建工具入口文件,如CMakeLists.txt,CMakeLists.txt中通过add_subdirectory()命令添加子目录,CMake将自动迭代调用子目录中的CMakeLists.txt,并逐级向下展开。 +- build.suffix脚本文件,该文件是一键式构建入口,仅调用该脚本即可完成构建。".suffix"表示对应的构建脚本语言后缀,譬如".bat",".sh",".py"等。 +- config.suffix配置文件,该文件用于存放构建配置项,是唯一的配置文件入口。 +- 构建脚本目录,可选,如cmake目录,用于保存CMake脚本文件。CMake脚本文件包括宏、函数、toolchain等, CMakeLists.txt通过include()命令包含CMake脚本文件,并调用其中的宏、函数等。 +- 组件代码目录,用于存放各组件的源码及构建脚本。 +- 上述文件和目录,只有CMakeLists.txt、build.suffix、config.suffix这三个文件是必需的,其它文件或者目录仅用作示例,不强制要求。 + +Build Tree包含下列目录: + +- build目录,用于存放构建中间件。该目录可能在构建过程中创建,在git库上可能没有该目录。 +- 有的工程已经将build目录用于保存构建脚本,可以创建别的目录作为Build Tree。 + +Install Tree包含下列目录: + +- output目录,用于存放交付件。该目录可能在构建过程中创建,在git库上可能没有该目录。 + +【级别】要求 + +【描述】 + +典型目录结构如下: + +``` +base_dir + |---CMakeLists.txt ---| + |---build.suffix | + |---config.suffix | + |---cmake |--> Source Tree + |---component_1 | + |---component_2 | + |---...... | + |---component_n ---| + |---build ------> Build Tree + |---output ------> Install Tree +``` + +各组件的目录结构与顶层的目录结构类似,譬如: + +``` +component_1 + |---CMakeLists.txt ---| + |---build.suffix | + |---config.suffix | + |---cmake |--> Source Tree + |---module_1 | + |---module_2 | + |---...... | + |---module_n ---| + |---build ------> Build Tree + |---output ------> Install Tree +``` + +##### G.C&C++.02 构建过程中禁止以任何形式修改Source Tree。 + +【级别】建议 + +【描述】构建过程中修改Source Tree会导致构建过程不可重复。 + +常见的修改Source Tree的操作有: +1)打补丁 +2)打点 +3)裁剪 +4)自动生成源码 +5)先修改源码然后还原 +6)增加/修改/删除临时文件或者目录 +7)修改文件/目录属性或者格式,譬如修改文件可执行权限、dos2unix等 + +建议解决方案如下: +1)将代码拷贝到Build Tree,然后打补丁,编译。 +2)打点工具修改源码,使得构建过程不可信,因此禁止在构建过程中使用打点工具。应将打点后的代码上传到代码库,使用打点后的代码进行构建。 +3)裁剪是独立的源码交付需求,裁剪可以看做是代码准备阶段。裁剪前的版本和裁剪后的版本都必须满足在构建过程中不修改Source Tree。 +4)自动生成的源码应放在Build Tree下。 +5)先修改源码然后还原是掩耳盗铃,构建过程中源码已经发生了变更。 +6)临时文件或者目录都应该放在Build Tree下。 +7)必须保证代码库中的文件属性和格式是正确的,而不是构建时修改。 + +检验Source Tree是否发生变化的方法之一:编译完成后在源码目录下执行git status命令,不能有任何变更。先修改后还原导致的Source Tree变更,通过git status可能检测不出来。 + +【例外】 +1)git status检测到Build Tree和Install Tree这两个目录的变更是允许的。 +2)git status检测到由于裁剪导致的变更是允许的。 + +##### G.C&C++.03 Windows构建根目录建议为D:\交付单元的名称+版本号(可选);Linux构建根目录建议为/usr1/交付单元的名称+版本号(可选)。 + +【级别】建议 + +【描述】构建根目录按交付单元的名称+版本号命名,禁止使用build或code等无法区分交付单元的目录名称。 +清晰的构建目录结构,便于测试人员配置构建参数、执行一键式构建入口和对比构建结果。 +根目录示例如下: + +``` +D:\Offering [Version,可选]或/usr1/Offering [Version,可选] +``` + +##### G.C&C++.04 构建过程中生成的所有中间件保存在Build Tree中。 + +【级别】要求 + +【描述】构建过程中产生的中间件包括构建工具CMake自动生成的makefile、构建脚本自动生成的源码、构建脚本拷贝的源码及补丁、编译产生的object文件、库文件、可执行程序、构建日志等等。如果中间件放在Build Tree以外的目录,势必污染Source Tree或者Install Tree。因此,所有中间件都要保存在Build Tree中。Build Tree仅用于保存构建中间件,不能将Source Tree下某个放置源码或者构建脚本的目录用作Build Tree。 +Build Tree下创建构建日志子目录logs,构建日志后缀文件命名为.log。 + +##### G.C&C++.05 支持指定Source Tree和Install Tree以外的任意目录作为Build Tree。 + +【级别】要求 + +【描述】支持指定Source Tree和Install Tree以外的任意目录作为Build Tree,做到构建过程与目录无关。在哪个目录下执行构建,哪个目录就是Build Tree,编译中间件就保存在哪个目录下。Build Tree的目录名称一般为“build”,也可以使用其它名称。 + +【正确示例】使用CMake系统变量CMAKE_BINARY_DIR和CMAKE_CURRENT_BINARY_DIR访问Build Tree,避免Build Tree与Source Tree产生耦合。 + +##### G.C&C++.06 所有发布件保存在Install Tree中。 + +【级别】要求 + +【描述】本地编译场景下,发布件直接"install"到HOST Computer上并运行。交叉编译场景下,发布件并不在HOST Computer上运行,而是在TARGET Computer上运行。 + +发布件包括库文件、可执行程序、包文件、头文件等,是组件对外的二进制接口。所有发布件都保存在Install Tree中,不应将发布件放在Install Tree以外的目录下。 + +Install Tree只用于保存发布件,不应将编译中间件放在Install Tree中。 + +##### G.C&C++.07 支持指定Source Tree和Build Tree以外的任意目录作为Install Tree。 + +【级别】要求 + +【描述】支持指定Source Tree和Build Tree以外的任意目录作为Install Tree,做到构建过程与目录无关。Install Tree的目录名称固定为“output”。 + +【正确示例】CMake构建工程应支持通过系统变量CMAKE_INSTALL_PREFIX指定Install Tree的根目录。 + +#### 构建入口 + +##### G.C&C++.08 每个交付单元的构建入口单一。构建脚本入口名称统一命名为build.suffix,并且路径要求在构建根目录下。 + +【级别】要求 + +【描述】通过使用一致的构建入口点,构建过程可以变得更加高效和可自动执行。每个交付单元只有单一构建入口,便于一键式自动构建。 + +【错误示例】如下构建有多个入口点,如果没有说明文档,无法确认哪一个入口是正确的,造成选择困难。 +build.bat +build_all.sh +build_v6.sh + +【正确示例】一键式构建脚本build.sh的典型写法如下: + +```bash +#!/bin/bash + +if [ -d "build" ]; then + rm -fr build/* +else + mkdir build +fi + +if [ -d "output" ]; then + rm -fr output/* +else + mkdir output +fi + +cd build +cmake .. + +cpu_processor_num=$(grep processor /proc/cpuinfo | wc -l) +job_num=$(expr "$cpu_processor_num" \* 2) +echo Parallel job num is "$job_num" +make -j"$job_num" +``` + +##### G.C&C++.09 支持指定target进行构建。 + +【级别】要求 + +【描述】日常开发场景下,通过指定target编译,开发人员只需要编译修改了的代码,不需要编译全部代码,达到快速验证的目的。编译工程应支持指定target进行构建,从而满足灵活多变的编译调试需求。 + +【正确示例】典型命令如下: + +``` +base_dir # cd build +base_dir/build # cmake .. +# 编译全部目标 +base_dir/build # make +# 编译特定目标 +base_dir/build # make target_name +``` + +##### G.C&C++.10 支持重复编译。 + +【级别】要求 + +【描述】编译成功后,不对源代码做任何修改,不清理上次编译的中间件和发布件,不修改编译环境,再次执行编译,必须能重复编译成功。 + +##### G.C&C++.11 支持增量编译。 + +【级别】建议 + +【描述】日常开发场景下,增量编译可以缩短编译时间,提高开发效率,因此建议支持增量编译。 + +##### G.C&C++.12 支持并行编译。 + +【级别】要求 + +【描述】通过"make -jN"命令进行并行编译,可以提高编译速度。本规则仅适用于使用make工具的工程。 + +支持jobserver统一调度,使整个工程的负载最优。不能出现下面两个告警: + +``` +warning: jobserver unavailable: using -j1. Add '+' to parent make rule. +warning: -jN forced in submake: disabling jobserver mode. +``` + +支持jobserver的方法如下: + +1. 通过$(MAKE)直接调用make命令 + + ```cmake + ExternalProject_Add(foo + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/foo + CONFIGURE_COMMAND sh configure_ext.sh + BUILD_COMMAND $(MAKE) + ) + ``` + +2. 通过shell脚本调用make命令 + + ```cmake + ExternalProject_Add(foo + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/foo + CONFIGURE_COMMAND sh configure_ext.sh + BUILD_COMMAND sh build_ext.sh $(MAKE) + ) + ``` + + build_ext.sh内容如下: + + ```bash + #!/bin/bash + + make + ``` + + 注意:build_ext.sh不需要解析和使用参数$(MAKE)。 + +3. 通过python脚本调用make命令 + + ```cmake + ExternalProject_Add(foo + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/foo + CONFIGURE_COMMAND sh configure_ext.sh + BUILD_COMMAND python build_ext.py $(MAKE) + ) + ``` + + build_ext.py内容如下: + + ```bash + #!/usr/bin/python + # -*- coding: UTF-8 -*- + + import subprocess + + def main(): + child = subprocess.Popen("make", close_fds=False) + ret = child.wait() + return + + if __name__ == '__main__': + main() + ``` + + 注意:build_ext.py不需要解析和使用参数$(MAKE)。 + + +#### 构建依赖 + +##### G.C&C++.13 定义一个构建依赖文件dependence.xml,文件中描述构建依赖的所有组件。构建脚本自动读取该依赖文件,用于制作最终的软件包。 + +【级别】建议 + +【描述】按照依赖文件进行软件包制作,避免在构建脚本中定义依赖组件,提高构建过程可维护性。 + +#### 构建配置 + +##### G.C&C++.14 构建根目录的config.suffix配置文件是整个交付项目唯一的配置入口。 + +【级别】要求 + +【描述】顶层的config.suffix中,应暴露最少的配置项,只需要用户配置的构建环境、构建工具相关的信息。 + +【例外】如果构建配置的内容非常少,采取系统键值对配置项,配置文件可以命名成config.conf。 + +### GN 编写规范 + +#### 编译规范 + +##### 规则1.1 禁止在gn中调用外部编译工具编译软件模块 + +【级别】禁止 + +【描述】需要将外部组件移植成gn的编译形式,避免编译过程对环境产生不必要的依赖,而且可获得编译框架提供的公共能力,包括不限于:安全编译选项,ASAN等。 + +【反例】在gn中使用action调用automake和Make来编译三方组件。 + +【例外】Linux Kernel 编译框架实际完成的用户态程序编译,内核完全可以在编译框架之外完成独立编译。某些平台实现为了实现一键编译,使用gn将内核编译加在编译过程中,是可以接受的。 + +##### 规则1.2 禁止在模块的gn文件中,再次添加编译系统已经添加的安全编译选项 + +【级别】禁止 + +【描述】对于全局已经添加的默认选项,模块开发者应当知晓,不需要为了满足内外部规则再次添加。 + +| 编译选项 | 编译参数 | 默认值 | +|---------|------------|------------| +| 栈保护 | -fstack-protector-strong| 开 | +| Fortify Source | -D_FORTIFY_SOURCE=2 -O2 | 开 | + +【反例】在模块的编译添加 -fstack-protector-strong + +##### 规则1.3 禁止在gn中添加和默认编译选项相反的编译选项 + +【级别】禁止 + +【描述】默认的编译选项代表了系统的默认能力,自研模块有特殊情况需要去掉部分能力,必须有足有的理由。 + +【反例】在自研模块中添加 -wno-unused 以消除编译告警。 + +【例外】移植三方组件,或者使用因为三方组件时,可根据三方组件的要求覆盖默认的编译选项。 + +##### 规则 2.1 使用gn format 对添加或者修改的gn文件进行格式化,满足格式和排版的需求 + +【级别】要求 + +##### 规则 2.2 编写action时,使用python而不是shell + +【级别】建议 + +【描述】python 环境更容易保持统一,可以比较容易的多重操作系统上运行,并且扩展性可读性可测试更好。 + +##### 规则 2.3 禁止在gn和ninja执行过程修改源码目录的内容 + +【级别】禁止 + +【描述】包括但不限于给源码目录打patch,向源码目录中拷贝,在源码目录中执行编译,在源码目录生成中间文件等。 + +##### 规则 2.4 编译脚本的编码格式设置为utf-8,换行符设置为unix格式 + +【级别】要求 + +【反例】在windows上编写脚本后,使用了中文注释并保存为本地编码。 + diff --git a/zh-cn/contribute/OpenHarmony-compile-rule.md b/zh-cn/contribute/OpenHarmony-compile-rule.md new file mode 100644 index 0000000000000000000000000000000000000000..6bfe64f2ddbcc248a3b9363fd6c4401ead700289 --- /dev/null +++ b/zh-cn/contribute/OpenHarmony-compile-rule.md @@ -0,0 +1,1369 @@ + +# 开源编译规范 + +## 概述 + +**简介:** + +本规范包括C/C++/Java语言编译选项或系统配置,包括语言选项、警告选项、安全选项、总体选项、代码生成选项、架构选项、优化选项、编译宏等。 + +**范围:** + +本规范规定了C/C++/Java语言在编译构建过程中需要添加的编译选项或系统配置,并对这些选项的作用进行了简单说明。此外,规范中对涉及到的例外场景也进行了阐释说明。 + +无OS(如裸核、BIOS、Bootloader、BSBC等)需遵循的安全编译选项还未制定,本规范暂不做要求,在相关规范发布之前,建议实施栈保护。 + +对于本规范未描述的例外情况,如果存在争议,可申请仲裁。 + +**条款组织方式:** + +每个条款一般包含标题、级别、描述等组成部分。条款内容中的“正确示例”表示符合该条款要求的例子,“错误示例”表示不符合该条款要求的例子。 + +**标题:** + +描述本条款的内容。 + +规范条款分为原则和规则两个类别,原则可以评价规则内容制定的好坏并引导规则进行相应的调整;规则是需要遵从或参考的实践。通过标题前的编号标识出条款的类别为原则或者规则。 + +标题前的编号规则参见《安全工程规范内容总纲》,其中'P'为单词Principle首字母,'G'为单词Guideline的首字母。原则条款的编号规则为P.Number。规则的编号方式为G.Language.Element. Number,其中Language是语言分类,Element为领域知识中关键元素(本规范中对应的一级目录)的英文字母缩略语。Number是从1开始递增的两位阿拉伯数字,不足两位时高位补0。 + +| Language | Element | 目录 | Language | Element | 目录 | +|----------|---------|----------|----------|---------|--------------| +| C&C++ | LANG | 语言选项 | C&C++ | WARN | 警告选项 | +| C&C++ | SEC | 安全选项 | C&C++ | CDG | 代码生成选项 | +| C&C++ | OPT | 优化选项 | C&C++ | MD | 架构选项 | +| C&C++ | OVA | 总体选项 | C&C++ | LNK | 链接选项 | +| C&C++ | DBG | 调试选项 | C&C++ | PRE | 编译宏 | +| C&C++ | OTH | 其他 | JAVA | JAVAC | JAVAC | +| JAVA | MAVEN | MAVEN | | | | + +**级别:** + +规则类条款分为两个级别:要求、建议。 + +- 要求:表示产品原则上应该遵从,但可以按照具体产品版本计划和节奏分期实现。 + +- 建议:表示该条款属于最佳实践,有助于进一步消解风险,产品可结合业务情况考虑是否纳入。 + +**描述:** + +对条款的进一步描述,描述条款的原理,配合正确和错误的代码例子作为示范。有的条款还包含一些规则不适用的例外场景。 + +## C/C++语言编译选项 + +### 语言选项 + +##### G.C&C++.LANG.01 显式设置编译的语言标准 + +**【级别】** 要求 + +**【描述】** 按时间先后顺序,常用的ISO C标准包括:"-std=c90","-std=c99","-std=c11",对应的GNU扩展标准为"-std=gnu90","-std=gnu99","-std=gnu11"。 + +按时间先后顺序,常用的ISO C++标准包括:"-std=c++98","-std=c++11","-std=c++14","-std=c++1z",对应的GNU扩展标准为"-std=gnu++98","-std=gnu++11","-std=gnu++14","-std=gnu++1z"。 + +"-ansi"对应ISO C标准"-std=c90"和ISO C++标准"-std=c++98"。 + +GNU扩展标准完全支持对应的ISO标准,并在对应的ISO标准上做了扩展。 + +"-Wpedantic","-pedantic","-pedantic-errors"等选项用于检查是否严格符合对应的ISO标准,对不符合标准的语法进行警告,GNU扩展语法也可能产生警告。 + +##### G.C&C++.LANG.02 采用较新的语言标准 + +**【级别】** 建议 + +##### G.C&C++.LANG.03 显式设置char的类型:"-fsigned-char"或"-funsigned-char" + +**【级别】** 建议 + +**【描述】**"-fsigned-char":x86环境默认char是signed类型,但是ARM64下,默认char是unsigned类型;编译器适配不同平台后端的指令集,故为了考虑平台兼容性,使用该选项。 + +部分产品可能默认char等效于unsignd char,这种情况下建议使用选项"-funsigned-char"显式设置。 + +##### G.C&C++.LANG.04 对C++语言,禁止使用"-fpermissive"选项 + +**【级别】** 要求 + +**【描述】** 使用"-fpermissive"选项将C++代码中不符合标准的语法error降级成warning。不允许使用该选项,应采用符合标准的C++语法。 + +### 警告选项 + +#### 选项集 + +##### G.C&C++.WARN.01 打开"-Wall"选项,检查有用的警告选项集 + +**【级别】** 要求 + +**【描述】** "-Wall"是gcc编译器认可的、很有用的警告选项集合,包括"-Wpointer-sign"、"-Wframe-address"、"-Wmaybe-uninitialized"、"-Wint-in-bool-context"等警告。对于这些警告,应该理解其含义,通过修改代码来消除警告。 + +##### G.C&C++.WARN.02 打开"-Wextra"选项,检查除"-Wall"外附加的选项集;"-Wextra"中误报较多的选项,可以使用"-Wno-XXXX"屏蔽 + +**【级别】** 要求 + +**【描述】** "-Wextra"是除"-Wall"外的一些有用的警告选项集合,包括“-Wempty-body”、"Wmissing-field-initializers"、"-Wunused-parameter"等警告。 + +"-Wextra"中某些警告可能存在较多误报,产品在实测的基础上,可以使用“-Wno-XXXX”屏蔽其中误报较多的警告,如某产品实测“-Wunused-parameter +\-Wmissing-field-initializers”误报较多,可以设置“-Wextra -Wno-unused-parameter +\-Wno-missing-field-initializers”,由产品线软件总工批准。 + +##### G.C&C++.WARN.03 打开"-Weffc++"选项,检查Scott Meyers’ Effective C++选项 + +**【级别】** 建议 + +**【描述】** "-Weffc++":Scott Meyers’ Effective C++对应的警告选项集。 + +#### 警告屏蔽 + +##### G.C&C++.WARN.04 禁止使用"-w"选项屏蔽所有警告 + +**【级别】** 要求 + +**【描述】** 编译器提示的警告通常对于鉴别低劣的代码和隐晦的bug非常有用,使用-w选项会屏蔽了所有的警告。 + +##### G.C&C++.WARN.05 禁止使用"-Wno-XXXX"抑制"-Wall"包含的所有警告选项 + +**【级别】** 要求 + +**【描述】** "-Wall"是gcc编译器认可的、很有用的警告选项集合,禁止使用比如"-Wno-pointer-sign"、"-Wno-frame-address"、"-Wno-maybe-uninitialized"、"-Wno-int-in-bool-context"抑制"-Wall"包含的"-Wpointer-sign"、"-Wframe-address"、"-Wmaybe-uninitialized"、"-Wint-in-bool-context"选项。 + +##### G.C&C++.WARN.06 禁止使用"-Wno-error= XXXX"选项将已指定的升级错误的警告再次降级成警告 + +**【级别】** 要求 + +**【描述】** "-Werror=XXXX"把指定警告升级错误,"-Wno-error=XXXX":将指定升级成错误的警告再次降级成警告,令人困惑。 + +##### G.C&C++.WARN.07 避免使用"-Wno-XXXX"抑制编译器缺省打开的编译警告选项 + +**【级别】** 建议 + +**【描述】** 编译器缺省打开的编译警告选项,是gcc编译器认可的、很有用的警告选项,如"-Wwrite-strings"、"-Wdelete-incomplete"、"-Wsizeof-array-argument"等。对于这些警告,应该理解其含义,通过修改代码来消除警告。 + +**【错误示例】** 某组件的构建工程中使用"-Wno-write-strings"抑制"-Wwrite-strings"编译警告7749次。 + +**例外:** 为了确保构建一致性,可以重定义 \__FILE_\_ 宏,消除绝对路径,可以使用"-Wno-builtin-macro-redefined"抑制"-Wbuiltin-macro-redefined"警告。 + +#### 警告升级 + +##### G.C&C++.WARN.08 使用"-Werror"、"-Werror=XXXX"选项把警告当错误处理 + +**【级别】** 建议 + +**【描述】** 建议打开"-Werror"、"-Werror=XXXX"选项:把警告当错误处理 + +"-Werror":把警告当错误处理,一旦出现警告,编译就会失败,有利于在开发过程中清除所有的警告。 + +"-Werror=XXXX":把指定警告当错误处理。使用"-Werror=XXXX"指定某些警告当错误处理,有利于在开发过程中清除所指定的警告。,如"-Werror=implicit-function-declaration"、"-Werror=format-SEC"。 + +#### 警告管理 + +##### G.C&C++.WARN.09 同一构建工程中,统一编译警告选项。 + +**【级别】** 要求 + +**【描述】** 统一的编译警告选项,确保各部分代码质量统一。 + +#### 函数 + +##### G.C&C++.WARN.10 打开"-Wtrampolines"选项,避免内嵌函数生成trampoline + +**【级别】** 建议 + +**【描述】** 内嵌函数是定义于函数中的函数。当内嵌函数指针生成trampoline时,会触发警告。Trampoline是在运行时创建于栈区的一小段数据或代码,它包含了内嵌函数的地址信息,它被用于内嵌函数的间接调用。某些平台上,Trampoline仅仅由一些特殊处理的数据构成。但是,大多数平台上,它是由代码构成的,因此它需要栈可执行来支持。栈变成可执行栈,CPU读取栈上指令执行,攻击者可能通过缓冲区溢出攻击等手段运行栈内存上自己得代码。 + +**【错误示例】** 在函数main内部定义并通过函数指针调用内嵌函数fun,在”-Wtrampolines”选项下编译警告。 + +- 源程序: +``` +\#include \ +int main(){ + int ret; + int (\*pfunc)(int a, int b); + int fun(int a, int b){ + return a + b; + } + pfunc = fun; + ret = pfunc(10, 20); + printf("test gcc option -Wtrampolines! ret = %d\\n", ret); + return 0; +} +``` + +- 编译选项: +``` +gcc -Wtrampolines trampolines.c -o out +``` + +- 编译结果: +``` +warning:trampoline generated for nested function ‘fun’ [-Wtrampolines] +``` +**例外**:"-Wtrampolines" xt-xcc和clang编译器不支持。 + +##### G.C&C++.WARN.11 打开"-Wformat=2"选项,检查格式化输入/输出函数的安全 + +**【级别】** 建议 + +**【描述】** "-Wformat=2"是“-Wformat”、“-Wformat-nonliteral”、“-Wformat-SEC“、”\-Wformat-y2k“的集合。 + +1. “-Wformat”:格式化函数的参数类型、格式错误时,警告 + +2. “-Wformat-nonliteral”:当格式化字符串为非字符串常量时,警告 + +3. “-Wformat-SEC“、” -Wformat-y2k“ + +对于产品自行封装的格式化输入输出框架函数, 应于 API 声明 format attribute +以利用编译器检查能力, 详细参考 +[https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html\#Common-Function-Attributes](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes) + +##### G.C&C++.WARN.12 打开"-Wstrict-prototypes "选项,避免函数在声明或定义中没有指定参数类型 + +**【级别】** 建议 + +**【描述】** 在函数的声明或定义时,显式指明函数参数类型,编译器检查函数调用和定义之间参数类型的不匹配情况。 + +**【错误示例】** + +- 源程序: +``` +\#include \ +int func(param){ + return param; +} + +``` +- 编译选项: +``` +gcc -Wstrict-prototypes strict_prototypes.c -o out +``` +- 编译结果: +``` + warning: function declaration isn't a prototype [-Wstrict-prototypes] int func(param){ +``` + +相关文档:《SEI CERT C Coding Standard》DCL07-C. Include the appropriate type +information in function declarators + +#### 二进制一致性 + +##### G.C&C++.WARN.13 打开"-Wdate-time"选项,避免使用时间宏,确保二进制一致性 + +**【级别】** 建议 + +**【描述】** "-Wdate-time":避免代码使用__DATE__、__TIME__、__TIMESTAMP__,以确保二进制一致性。 + +**【错误示例】** + +- 源程序: +``` +\#include \ +int main() { + printf ("%s %s %s\\n",_DATE_,_TIME_,_TIMESTAMP_); + return 0; +} +``` +- 编译选项: +``` +gcc -Wdate-time datetime.c -o out +``` +- 编译结果: +``` +warning:macro "_DATE_" might prevent reproducible builds [-Wdate-time] warning:macro "_TIME_" might prevent reproducible builds [-Wdate-time] warning:macro "_TIMESTAMP_" might prevent reproducible builds [-Wdate-time] +``` + +#### 语句 + +##### G.C&C++.WARN.14 打开"-Wfloat-equal"选项,避免浮点数相等比较运算 + +**【级别】** 要求 + +**【描述】** 由于浮点数存在精度问题,大多数情况下是近似值,不能精确判断是否相等。浮点数相等或不相等比较是不安全的行为,建议通过判断两数之差的绝对值是否小于可接受误差来判断浮点数是否相等,可以使用C语言标准库函数fabs()求两浮点数之差的绝对值,然后与可接受误差比较,如果在可接受误差范围内,则相等,否则不相等。需要特别注意的是:\>、\<、\>=、\<=这四种比较运算符用于浮点数比较不会警告。 + +**【错误示例】** + +- 源程序 : +``` +\#include \ +int main() { + double a = 0.3; + double b = 0.6; + ouble c = 0.9; + if ((a+b) == c) { + /\* 看似相等,实际运行时,a+b与c不相等\*/ + printf("double equal\\n"); + } + return 0; +} +``` + +- 编译选项: +``` +gcc -Wfloat-equal float_equal.c -o out +``` + +上述示例中,进行双精度浮点数相等比较,编译器警告"warning:comparing floating +point with == or != is unsafe[-Wfloat-equal]",a+b和c看似应该相等,但是程序运行时并不相等,这是因为浮点数是近似表达,a+b和c均为近似值,浮点数的相等性比较不可信,是一种不安全的行为。浮点数正确的比较方式是设定一个可接受的误差精度,如果两个浮点数差值的绝对值在这个误差范围内,就表示相等,正确方式如下: + +**【正确示例】** 浮点数相等比较 + +- 源程序 : +``` +\#include \ \#include \ \#define EPSILON 1e-6 / +\* 双精度比较可接受的误差 \*/ +int main() { + double a = 0.3; + double b = 0.6; + double c = 0.9; + if (fabs((a+b)-c) \< EPSILON) { + printf("double equal\\n"); + } + return 0; +} +``` + +- 编译选项: + +``` +gcc -Wfloat-equal float_equal.c -o out +``` + +##### G.C&C++.WARN.15 打开"-Wswitch-default"选项,确保switch语句有default分支 + +**【级别】** 建议 + +**【描述】** 如果switch语句没有default分支,在-Wswitch-default选项下编译警告。 + +**【错误示例】** + +- 源程序: +``` +enum TintColor{ + RED, DARK_RED, GREEN, LIGHT_GREEN +}; +void Colorize(enum TintColor Color) { + switch (Color) { + case RED: + /\* code \*/ + break; + case DARK_RED: + break; + } +} +``` +- 编译选项: +``` +gcc -Wswitch-default switch_default.c -o out +``` +- 编译结果: +``` +warning: switch missing default case [-Wswitch-default] switch (Color) +``` + +#### 变量 + +##### G.C&C++.WARN.16 打开"-Wshadow"选项,检查变量覆盖 + +**【级别】** 建议 + +**【描述】** "-Wshadow":局部变量覆盖全局变量、函数参数等产生的警告。C++语言打开该选项警告较多,团队可以根据实际情况评估是否打开该选项。 + +**【错误示例】** + +- 源程序: +``` +int num = 0; +int foo(int a, int b){ + int num = a + b; + return num; +} + +``` +- 编译选项: +``` +gcc -Wshadow shadow.c -o out +``` +- 编译结果: +``` +warning: declaration of 'num' shadows a global declaration [-Wshadow] int num = a + b; +``` + +##### G.C&C++.WARN.17 打开"-Wstack-usage=len"选项,设置栈大小,避免栈溢出 + +**【级别】** 建议 + +**【描述】** 如果函数使用的栈内存可能超过len个字节,编译警告。len的值,团队根据实际情况设置。 + +**【错误示例】** + +- 源程序: +``` +void foo(void) { + int arr[1000] = {0}; + return; +} +``` +- 编译选项: +``` +gcc -Wstack-usage=1000 stack_usage.c -o out +``` +- 编译结果: +``` +warning: stack usage is 4012 bytes [-Wstack-usage=] void foo(void) { +``` + +##### G.C&C++.WARN.18 打开"-Wframe-larger-than=len" 选项,设置栈框架大小,避免栈溢出 + +**【级别】** 建议 + +**【描述】** 如果一个函数的栈框架超过len字节,编译警告。len的值,团队根据实际情况设置。 + +**【错误示例】** + +- 源程序: +``` +void foo(void) { + int arr[1000] = {0}; + return; +} +``` +- 编译选项: +``` +gcc -Wframe-larger-than=1000 stack_usage.c -o out +``` +- 编译结果: +``` +warning: the frame size of 4000 bytes is larger than 1000 bytes [-Wframe-larger-than=] +``` + +##### G.C&C++.WARN.19 不建议打开“-Wno-return-local-addr“选项,检查返回局部变量地址 + +**【级别】** 建议 + +**【描述】** 如果函数返回局部变量的地址,编译时默认产生“-Wreturn-local-addr”警告。禁止开启“-Wno-return-local-addr”选项屏蔽这些警告。 + +**【错误示例】** + +- 源程序: +``` +int\* foo() { + int a=0; + return \&a; +} +``` +- 编译选项: +``` +gcc -Wreturn-local-addr return_local_addr.c -o out +``` +- 编译结果: +``` +warning: function returns address of local variable [-Wreturn-local-addr] return \&a; +``` + +#### 类型转换 + +##### G.C&C++.WARN.20 打开"-Wconversion"选项,避免隐式转换改变数值 + +**【级别】** 建议 + +**【描述】** 如果代码中的隐式转换会改变数值,在-Wconversion下编译警告。 +可能造成数值改变的隐式转换包括:带小数的实数转换成整数,无符号数和有符号数之间的转换,较大类型的数转换成较小类型。需要注意的是,如果代码进行显式强转,在-Wconversion下编译不会警告。 + +**【错误示例】** + +- 源程序: +``` +int foo(void) { + double num = 1.2; + return num; +} +``` +- 编译选项: +``` +gcc-Wconversion conversion.c -o out +``` +- 编译结果: +``` +warning: conversion from 'double' to 'int' may change value [-Wfloat-conversion] return num; +``` + +不同类型的对象指针之间不应进行强制转换。 + +##### G.C&C++.WARN.21 打开"-Wcast-qual"选项,指针类型强制转换时,避免目标类型丢失类型限定词 + +**【级别】** 建议 + +对指针类型强制转化,导致目标类型丢失类型限定词 + +**【描述】** 如将const char\*指针类型强制转换为普通的char\*时会丢失const类型限定词,const修饰指针是期望该指针指向的内存不可修改,如果强制转化丢失了const类型限定词,就可以通过转换后的结果指针修改原本不期望被修改的内存,失去了对对象const约束的意义。 + +**【错误示例】** + +- 源程序: +``` +static char buf[8]; +void foo(){ + const char\* ptr = buf; + char\* q = (char\*)ptr; +} +``` +- 编译选项: +``` +gcc -Wcast-qual cast_qual.c -o out +``` +- 编译结果: +``` +warning: cast discards 'const' qualifier from pointer target type [-Wcast-qual] char\* q = (char\*)ptr; +``` + +##### G.C&C++.WARN.22 打开“-Wcast-align”选项,检查指针类型强制转换,避免目标所需的地址对齐字节数增加 + +**【级别】** 建议 + +**【描述】** 当源程序中某个指针类型强制转换导致目标所需的地址对齐字节数增加时,则产生警告。比如在整型只能以两字节或四字节边界进行访问的机器上,将 char \* 转换为 int \* 则给出警告。 + +#### 数组 + +##### G.C&C++.WARN.23 打开“-Wvla”选项,避免变长数组 + +**【级别】** 建议 + +**【描述】** 定义数组时,如果数据长度是变量而非固定值,在-Wvla选项下编译警告。 + +**【错误示例】** + +- 源程序: +``` +void foo(int len) { + int arr[len]; +} +``` +- 编译选项: +``` +gcc -Wvla val.c -o out +``` +- 编译结果: +``` +warning: ISO C90 forbids variable length array 'arr' [-Wvla] int arr[len]; +``` + +#### 无效代码 + +##### G.C&C++.WARN.24 打开“-Wunused”选项,避免无效代码 + +**【级别】** 建议 + +**【描述】** -Wunused选项检查代码中未使用的变量、函数、参数、别名等问题。-Wunused选项包含了多个针对某种类型对象未使用的子选项: + +\-Wunused-but-set-variable + +\-Wunused-function + +\-Wunused-label + +\-Wunused-local-typedefs + +\-Wunused-variable + +\-Wunused-value + +需要注意的是,需要使用-Wextra \-Wunused或者-Wunused-parameter,才能对函数中未使用的形参警告。 + +**【错误示例】** + +- 源程序: +``` +void foo(void) { + int a; +} +``` +- 编译选项: +``` +gcc -Wunused unused.c -o out +``` +- 编译结果: +``` +warning: unused variable 'a' [-Wunused-variable] int a; +``` + +#### 预处理 + +##### G.C&C++.WARN.25 打开“-Wundef ”选项,避免预编译指令\#if语句中出现未定义的标识符 + +**【级别】** 建议 + +**【描述】** 当一个没有定义的标识符出现在 \#if 中时,给出警告。 + +**【错误示例】** + +- 源程序: +``` +\#if DEFINE_A_VALUE +\#endif +``` +- 编译选项: +``` +gcc -Wunused unused.c -o out +``` + +- 编译结果: +``` +warning: "DEFINE_A_VALUE" is not defined, evaluates to 0 [-Wundef] \#if DEFINE_A_VALUE +``` + +#### 类 + +##### G.C&C++.WARN.26 打开“-Wnon-virtual-dtor”选项,避免基类析构函数没有定义虚函数 + +**【级别】** 建议 + +**【描述】** 只有基类析构函数是virtual,通过多态调用的时候才能保证派生类的析构函数被调用。 + +**【错误示例】** + +- 源程序 : +``` +class Base { + public: virtual void foo() const = 0;\ + ~Base() {} +}; +class Derived: public Base { + public: virtual void foo() const {} + Derived() {} +}; +``` +- 编译选项: +``` +gcc-Wnon-virtual-dtor non_virtual_destructors.cpp -o out +``` + +- 编译结果: +``` +warning: 'class Base' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor] +``` + +##### G.C&C++.WARN.27 打开“-Wdelete-non-virtual-dtor”选项,当基类析构函数没有定义虚函数时,避免通过指向基类的指针来执行删除操作 + +**【级别】 建议** + +**【描述】** 当基类没有定义虚析构函数,指向基类的指针来执行删除操作,可导致未定义的行为。禁止开启“-Wno-delete-non-virtual-dtor”选项屏蔽这些警告。 + +**【错误示例】** + +- 源程序: +``` +class Base { + public: virtual void f(); +}; +class Sub: public Base { + public: void f(int); +}; +int main() { + Sub\ * sub = new Sub(); + Base\ * base = sub; + delete base; +} +``` +- 编译选项: +``` +gcc--Woverloaded-virtual overloaded_virtual.cpp -o out +``` +- 编译结果: +``` +warning: deleting object of polymorphic class type 'Base' which has non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor] delete base; +``` + +##### G.C&C++.WARN.28 打开"-Woverloaded-virtual"选项,避免隐藏基类虚函数 + +**【级别】** 建议 + +**【描述】** 派生类重新定义基类的虚函数,导致基类的虚函数被隐藏。 + +**【错误示例】** + +- 源程序: +``` +class Base { + public: virtual void f(); +}; +class Sub: public Base { + public: void f(int); +}; +``` +- 编译选项: +``` +gcc--Woverloaded-virtual overloaded_virtual.cpp -o out +``` +- 编译结果: +``` +warning: by 'void Sub::f(int)' [-Woverloaded-virtual] void f(int); +``` +### 安全选项 + +#### 选项集 + +##### G.C&C++.SEC.01 打开栈保护选项 + +**【级别】** 要求 + +**【描述】** + +**Linux平台用户态** + +作用阶段:编译选项 + +作用范围:可重定位文件(.o)、动态库、可执行程序 + +用法:-fstack-protector-all/-fstack-protector-strong + +**说明:** 当存在缓冲区溢出攻击漏洞时,攻击者可以覆盖栈上的返回地址来劫持程序控制流。启用栈保护后,在缓冲区和控制信息间插入一个canary word。攻击者在覆盖返回地址的时候,往往也会覆盖canary word。通过检查canary word的值是否被修改,就可以判断是否发生了溢出攻击。 + +1\. GCC4.9版本及以上落地-fstack-protector-strong; + +2\. GCC4.9版本以下落地-fstack-protector-all。 + +3\. windriver linux 4.3 + MIPS的环境不支持该特性。 + +**Linux平台内核** + +作用阶段:编译选项 + +作用范围:Linux平台内核态 + +用法:内核编译前打开配置CONFIG_CC_STACKPROTECTOR/CONFIG_CC_STACKPROTECTOR_STRONG + +**说明:** + +内核3.14及以上版本可支持CONFIG_CC_STACKPROTECTOR_STRONG,原有CONFIG_CC_STACKPROTECTOR(对应-fstack-protector)修改为CONFIG_CC_STACKPROTECTOR_REGULAR,内核4.18及以上版本CONFIG_CC_STACKPROTECTOR_REGULAR(对应-fstack-protector)修改为CONFIG_STACKPROTECTOR,CONFIG_CC_STACKPROTECTOR_STRONG(对应-fstack-protector-strong)修改为CONFIG_STACKPROTECTOR_STRONG + +受限于OS内核不支持本选项,导致驱动程序也无法使能本选项的情况可例外。其中,所使用的OS内核必须是下列情况中的一种或多种: + +1.官方发布的最新版本或者公司推荐的OS版本; + +2.由于产品配套(如,兼容客户OS)或兼容现网存量产品,而必须选择的OS版本; + +3.由于商务原因(如,实体名单)无法与OS厂商联系并获取新版本,只能使用老版本的场景; + +**LiteOS平台** + +作用阶段:编译选项 + +作用范围:LiteOS V200R003C00及之后的版本 + +用法:-fstack-protector-all/-fstack-protector-strong + +**说明:** 1.GCC4.9版本及以上落地-fstack-protector-strong; + +2.GCC4.9版本以下落地-fstack-protector-all。 + +受限于编译器版本不支持本选项或硬件提供类似栈保护的情况可例外。如以下两种情况: + +1.由于IAR 8.20版本以下版本不支持任务栈保护,不作要求。 + +2.使用硬件栈保护的不作要求(如ARC架构下部分产品能够提供硬件栈保护机制,栈溢出时能够触发硬件异常)。 + +##### G.C&C++.SEC.02 打开地址随机化选项 + +**【级别】** 要求 + +windows平台HighASLR & ForceASLR选项实施级别为建议 + +**【描述】** + +**Linux(用户态)** + +**a. 使用命令 echo 2 \>/proc/sys/kernel/randomize_va_space 打开系统随机化配置** + +**作用阶段:** 运行系统配置 + +**作用范围:** 堆、栈、内存映射区(mmap基址、shared libraries、vdso页) + +**用法:** echo 2 \>/proc/sys/kernel/randomize_va_space + +**说明**: + +ASLR是一种针对缓冲区溢出的安全保护技术,通过对堆、栈、共享库映射等线性区布局的随机化,增加攻击者预测目的地址的难度,防止攻击者直接定位攻击代码位置,达到阻止溢出攻击的目的。randomize_va_space等于1时,栈、数据段、VDSO会随机化,randomize_va_space等于2时堆地址也会随机化。 + +需要ASLR开启的级别为最高级别,即randomize_va_space等于2 + +**b. 打开PIC选项实现动态库随加载** + +**作用阶段**:编译选项 + +**作用范围**:动态库 + +**用法:** –fPIC(-fpic) + +**说明:** + +地址无关选项将发生在代码段的重定位移到数据段实现,so文件加载时代码段不会发生任何变化,做到所有进程共用一个代码段副本。 + +\-fPIC和-fpic均指示GCC产生地址无关代码,唯一的区别是-fPIC产生代码稍大,-fpic产生代码相对较小。 + +**c. 打开PIE选项实现可执行文件随机加载** + +**作用阶段:** 编译链接选项 + +**作用范围:** 可执行程序 + +**用法:** –fPIE(-fpie)-pie + +**说明:** + +具备PIE的可执行文件,在加载执行时可像共享库一样随机加载。有研究表明:PIE可有效降低固定地址类攻击、缓冲溢出类攻击的成功概率。 + +(1)关注对应的热补丁版本是否支持PIE选项,不支持的场景下不建议使用该选项 + +(2)-fPIE编译选项,-pie链接选项。 + +(3)-fPIE产生代码稍大,-fpie产生代码相对较小。 + +**LiteOS平台** + +**a. 配置代码段、数据段随机加载** + +**作用阶段:** 编译、链接选项以及运行系统配置 + +**作用范围:** LiteOS V200R003C00及之后的版本 + +**用法:** 先编译成可随机的镜像;然后镜像加载时,对地址进行随机修正 + +**说明:** 1.依赖支持随机地址加载的bootloader,依赖MMU、DDR空间。 + +2.开启后性能下降10%左右。 + +3.方案:-fPIE -pie借助GOT表实现地址随机,gcc和自研HCC编译器均可提供支持; + +4.开销较大无法落地时,需要业务提供具体的数据到TMG审核。 + +受限于产品硬件设计或启动流程不支持的情况可例外。如以下三种情况: + +1.XIP场景,即系统直接运行于Flash。 + +2.rom化场景,即全部或部分代码rom化,无法重新加载的场景。 + +3.bootloader不支持随机地址加载。 + +**b.配置动态库随机加载** + +**作用阶段:** 编译选项 + +**作用范围:** LiteOS V200R003C00及之后的版本 + +**用法:** -fPIC + +**说明:** 1.动态库编译阶段采用-fPIC。 + +##### G.C&C++.SEC.03 打开GOT表重定位只读选项 + +**【级别】** 要求 + +**【描述】** + +**Linux平台-用户态** + +**a.部分重定向只读选项:** + +**作用阶段:** 链接选项 + +**作用范围:** 动态库、可执行程序 + +**用法:** -Wl,-z,relro + +**说明**: + +动态链接的ELF二进制程序使用称为全局偏移表(GOT)的查找表去动态解析位于共享库中的函数。攻击者通过缓冲区溢出修改GOT表项的函数地址值来达到攻击的目的。通过增加RELRO选项,可以防止GOT表被恶意重写。 + +**b.全部重定向只读选项:** + +**作用阶段:** 链接选项 + +**作用范围:** 动态库、可执行程序 + +**用法:** -Wl,-z,now + +**说明**: + +开启部分重定项只读保护后,再开启立即绑定可实现全部重定向只读保护,即:全部重定向只读(GOT表全保护):-Wl,-z,relro,-z,now 可较好对ret2plt的攻击进行防护,而对诸如缓冲区溢出等攻击无法防范。 + +对于大量使用共享库中的函数代码产品,在一定程会导致程序装载(启动)阶段缓慢,而运行时性能不会有影响。 + +##### G.C&C++.SEC.04 打开堆栈不可执行/数据执行保护选项实现堆栈不可执行保护 + +**【级别】** 要求 + +**【描述】** + +**Linux平台-用户态** + +**作用阶段:** 链接选项 + +**作用范围:** 动态库、可执行程序 + +**用法:** -Wl,-z,noexecstack + +**说明**: + +1.如果有内嵌函数,会导致功能错误,需要先用-Wtrampolines进行检测,GCC4.6.4版本及以上。 +2.windriver linux 4.3普通版本不支持该特性。 +3.windriver linux 6 + MIPS不支持该特性。 + +**LiteOS平台** + +**作用阶段:** 运行系统配置 + +**作用范围:** LiteOS V200R003C00及之后的版本 + +**用法:** 运行时配置堆栈不可执行、数据段(BSS,DATA)不可执行 + +**说明:** 1.依赖硬件支持MMU/MPU/PMP等内存保护单元。 + +##### G.C&C++.SEC.05 使用-s选项或者strip工具去除符号表 + +**【级别】** linux平台-用户态:要求,其它平台:建议。 + +**【描述】** + +**Linux平台-用户态** + +**作用阶段:** 链接选项 + +**作用范围:** 动态库、可执行程序 + +**用法:** -s(strip工具) + +**说明:** + +符号在链接过程中,发挥着至关重要的作用,链接过程的本质就是把多个不同的目标文件“粘”到一起,符号可看作链接的粘合剂,整个链接过程正是基于符号才正确完成的。链接完成后,符号表对可执行文件运行已经无任何作用,反而会成为攻击者构造攻击的工具,因此删除符号表可防御黑客攻击。事实上删除符号表除防攻击外,还可对文件减肥,降低文件大小。 + +1.对于静态库,可重定位文件(.o)不能strip,否则出现编译错误,只涉及ELF可执行文件和动态库交付的产品才可以去除符号表 + +2.仅交付给产品,并不直接参与公司外部发布的组件和平台,需提供正式机制通知下游产品在发布阶段统一执行删除符号表操作 + +3.因为strip会影响产品定位网上问题和热补丁,构建流程上需要保证strip前后的版本同步,即需要产品本地保留未strip符号表的版本供补丁制作和网上调测使用。如可采用以下方案: + +3.1 执行机在编译的时候,生成未剥离符号表的可执行文件和动态库的版本,版本归档到VMP上(CMC)供产品做热补丁 + +3.2 使用strip工具对动态库和可执行文件删除符号表 + +3.3 剥离符号的可执行文件和动态库压缩到启动大包 + +4.strip工具和-s选项可达到一样的去除符号表的效果,基于-s选项会造成版本两次编译构建,建议发布前直接使用strip工具,strip级别为默认,如stripbin.out。 + +**LiteOS平台** + +**作用阶段:** 链接选项 + +**作用范围:** LiteOS V200R003C00及之后的版本 + +**用法:** -s(strip) + +**说明:** 1.LiteOS产品最终用于烧录的编译结果为bin文件,本身不存在符号表信息,建议不开启。 + +##### G.C&C++.SEC.06 禁止使用Run-time Search Path选项 + +**【级别】** 要求 + +**【描述】** + +**Linux平台-用户态** + +**作用阶段:** 链接选项 + +**作用范围:** 动态库、可执行程序 + +**用法:** -Wl,--disable-new-dtags,--rpath,/libpath1:/libpath2;-Wl,--enable-new-dtags,--rpath,/libpath1:/libpath2 + +**说明**: + +主要用于防护LD_LIBRARY_PATH替换同名动态库的攻击。通过加入此选项可以指定一个运行时动态库搜索的路径,该路径的搜索优先级高于LD_LIBRARY_PATH指定的路径。可执行文件在运行阶段进行动态库搜索时会首先在--rpath指定的路径查找动态库,然后才会到LD_LIBRARY_PATH指定的路径搜索。因此可以有效防御LD_LIBRARY_PATH=[attackpath]来替换同名动态库的攻击。但是该选项有也很多局限性,如指向的路径不安全,若普通用户可以在这些目录中使用恶意程序替换正常程序,造成权限提升,引发不安全路径漏洞。 + +##### G.C&C++.SEC.07 打开代码段/数据段写保护选项 + +**【级别】** 建议 + +**【描述】** + +**LiteOS平台** + +**a. 配置代码段、只读数据段写保护** + +**作用阶段:** 运行系统配置 + +**作用范围:** LiteOS V200R003C00及之后的版本 + +**用法:** 运行时配置代码段、ReadOnly Data段不可修改 + +**说明:** 1.依赖硬件支持MMU/MPU/PMP等内存保护单元。 + +##### G.C&C++.SEC.10 启用FORTIFY_SOURCE编译宏来打开FS选项 + +**【级别】** 建议 + +**【描述】** + +**Linux平台-用户态** + +**作用阶段:** 编译选项 + +**用法:** -D_FORTIFY_SOURCE=2 -O2 + +**说明**: + +程序中使用到静态的固定大小的缓冲区,增加了该选项之后,编译器或运行时库会对相关函数的调用在编译时或运行时进行检查。 + +原则上推荐级别为-O2(基于性能优化效果优于O1),若产品基于O2的风险性允许使用-O1。 + +先在分支版本添加,重点做性能测试,根据测试结果取舍。 + +**LiteOS平台** + +**作用阶段:** 编译选项 + +**作用范围:** LiteOS V200R003C00及之后的版本 + +**用法:** -D_FORTIFY_SOURCE=2 -O2 + +**说明:** 1. 选项收益和lib库实现有关。 + +2.当前LiteOS使用musl库,如果产品替换支持相关功能的lib库,需按需开启。 + +受限于lib库不支持情况可例外。如以下情况: + +1.musl库配置D_FORTIFY_SOURCE=2没有作用,容易对用户造成误导,可不开启。 + +##### G.C&C++.SEC.11 打开ftrapv选项来检测整数溢出 + +**【级别】** 建议 + +**【描述】** + +**Linux平台-用户态、LiteOS平台** + +**作用阶段:** 编译选项 + +**用法**:-ftrapv + +使用了-ftrapv选项后,执行带符号的整数间的加、减、乘运算时,不是通过CPU的指令,而是用包含在GCC附属库libgcc.c里的函数来实现。 + +性能影响较大,建议在Release版本不实施。 + +##### G.C&C++.SEC.13 打开栈检查选项 + +**【级别】** + +Linux平台-用户态:建议 + +LiteOS平台:要求(禁用) + +**【描述】** + +**Linux平台-用户态** + +**作用阶段:** 编译选项 + +**作用范围:** 可重定位文件、动态库、可执行程序 + +**用法:** -fstack-check + +**说明:** + +stack-check在编译时检查程序中栈空间,如果超过编译告警阀值则产生告警;然后在程序中生成额外的指令来检查运行时栈不会被溢出,stack-check选项会在每个栈空间最低底部设置一个安全的缓冲区,如果函数中申请的栈空间进入安全缓冲区,则触发一个Storage_Error异常。但它所生成的代码实际上并不处理异常,如果检测到异常则会发出一个消息,通知操作系统处理。它只保证操作系统可以检测到栈扩展。 + +性能影响较大,建立在Debug版本中实施,Release版本不实施 + +**实施建议:** 可选 + +**LiteOS平台** + +**作用阶段:** 编译选项 + +**作用范围:** LiteOS V100R003C00及之后的版本 + +**用法:** -fstack-check + +**说明:** 1.开启后程序会访问非法地址,导致执行异常,因此LiteOS平台下禁止打开栈检查选项。 + +### 优化选项 + +#### 选项集 + +##### P.C&C++.01 在实测的基础上,选择合适优化等级和各种优化选项 + +**【描述】** 在实测的基础上,尝试各种代码优化选项,以查看它们是否确实为生成程序更快。 + +##### G.C&C++.OPT.01 优化等级建议选"-O2"、"-Os"、"-O3" + +**【级别】** 建议 + +##### G.C&C++.OPT.02 当代码中存在较多的不同类型指针互转时,使用"-fno-strict-aliasing"选项关闭严格别名优化 + +**【级别】** 建议 + +**【描述】** GCC的"-O2"打开"-fstrict-aliasing"严格别名规则优化:编译器假定相同的内存地址绝不会存放不同类型的数据,该优化选项相对激进。为了避免代码中不同类型指针互转导致优化问题,可以使用"-fno-strict-aliasing"关闭优化;最好的方式是修改代码,遵守严格别名规则。 + +注意使用"-fno-strict-aliasing"选项可能会影响产品性能,如某产品一个性能敏感组件实测,"-O2 +\-fno-strict-aliasing"相比"-O2"会有性能下降,测的数据最多下降有9%。 + +##### G.C&C++.OPT.03 X86/ARM架构下,基于DOPRA平台的产品建议使用"-fno-omit-frame-pointer"选项关闭去SFP(Stack Frame Pointer)优化 + +**【级别】** 建议 + +**【描述】** "-fno-omit-frame-pointer":GCC的“-O” +("-O1")会打开"-fomit-frame-pointer"优化选项,也就是去掉函数调用时的frame +pointer,优化会导致代码难以调试,建议通过选项"-fno-omit-frame-pointer"禁止该项优化。 + +产品需要在性能优化和保留调试信息进行权衡。 + +### 代码生成选项 + +#### 选项集 + +##### G.C&C++.CDG.01 未初始化的全局变量放置在目标文件的数据段:"-fno-common" + +**【级别】** 要求 + +**【描述】** "-fno-common":未初始化的全局变量放置在目标文件的数据段,两个不同的编译单元中声明了同一个全局变量导致警告。多个临时的全局变量定义会增加代码维护难度,降低链接速度和增加空间消耗。 + +##### G.C&C++.CDG.02 将结构体放在寄存器中直接返回:"-freg-struct-return" + +**【级别】** 建议 + +**【描述】** "-freg-struct-return":采用寄存器返回结构与联合值。 + +“-fpcc-struct-return”:在返回短的结构和联合值时,与较长的值一样,使用内存而非寄存器。 + +尽可能在寄存器中返回结构和联合值。对小结构而言,这比“-fpcc-struct-return”效率更高。 +如果既未使用“-fpcc-struct-return”, 又未使用相反的“-freg-struct-return ”, GNU +CC缺省使用目标机器指定的标准规则。如果没有标准规则, 除了在GNUCC为主要编译器的机器上,GNU CC缺省采用“-fpcc-struct-return”,在可以选择标准的情况下, 我们选择了更高效的寄存器返 回方式。 + +注意,此选项影响二进制兼容性,应整个产品统一。 + +##### G.C&C++.CDG.03 设置默认的ELF镜像中符号的可见性为隐藏:"-fvisibility=hidden" + +**【级别】** 建议 + +**【描述】** "-fvisibility=hidden":可以让动态库中仅API外部可见,有效实现二进制的模块化。使用该选项可以提高动态库链接和加载的速度,防止符号冲突。但该选项加上后,需要考虑对该模块函数打补丁的成本,因为原来的全局符号变成LOCAL属性,对其打补丁时需要重新组名(DOPRA补丁规范有详细的组名规则),构建补丁的成本会增加。是否打开该选项,需要权衡。 + +##### G.C&C++.CDG.04 启用表达式计算顺序强化规则: “-fstrong-eval-order” + +**【级别】** 建议 + +**【描述】** "-fstrong-eval-order":按C++17的规格确定子表达式之间的计算顺序,比如表达式 +T().m_i = A().B() 在未开启时可能生成指令的求值顺序时 A() T() B() ,不符合常规预期;该选项当启用 "-std=c++17" 时自动开启, 但当前 gcc7.3默认"-std=c++14",建议显式开启以降低不可预期行为。 + +### 总体选项 + +#### 选项集 + +##### G.C&C++.OVA.01 打开总体选项:"-pipe" + +**【级别】** 建议 + +**【描述】** "-pipe" :编译过程中多管道并发,节省编译时间 + +### 架构选项 + +#### 选项集 + +##### G.C&C++.MD.01 对于嵌入式软件,显式指明如下架构选项 + +1. 软硬浮点(按照CPU支持类型进行添加或者不添加) + +2. 指令集 (如:march=armv7-a/ march=armv8-a) + +**【级别】** 要求 + +### 链接选项 + +#### 选项集 + +##### G.C&C++.LNK.01 打开如下链接选项:"-Wl,-Bsymbolic"、"-rdynamic"、" -Wl,--no-undefined" + +**【级别】** 建议 + +**【描述】** -Wl,-Bsymbolic:同名符号优先使用本so,减少got表调转 +"-rdynamic":解决dlopen反向依赖的问题;BIN文件通过地址返回符号名称,需要加,否则backtrace_symbol返回的是地址,不能定位;影响:产品BIN文件增大。 + +"-Wl,--no-undefined":可以将运行时加载错误,在链接期提前识别出来。打开该选项,导致链接时间会变长,因为链接期要进行依赖关系校验。如果-l指定依赖库不全,会有功能问题,需要产品权衡。 + + +### 调试选项 +#### 选项集 + +##### G.C&C++.DBG.01 对于版本发布构建,禁止携带调试信息 + +**【级别】** 要求 + +**【描述】** 调试信息指 符号表 和 +详细调试信息表,根据当前安全规定,调试信息,不是运行所必须,要求发布件删除这些信息,包括符号表,以提升攻击难度;热补丁、perf分析、抓堆栈等维测场景受影响。 + +使用 "-s" 链接选项可完全不生成调试信息,需注意此方法生成的组件与不加 "-s" +后重新构建生成的组件 build-id 是不一致的,不能直接用来 gdb定位问题;也可以链接后使用 objcopy --only-keep-debug \ \ 加上objcopy objcopy --strip-unneeded \ 方式分离调试符号,同样可达成交付件不含有符号表等调试信息。 + +如果编译阶段启用了 -g 生成详细调试信息表, 会因含有源代码绝对路径信息造成不同目录下构建的二进制差异, 此时可使用 -fdebug-prefix-map=old=new来将绝对路径映射成相对路径,达成 BEP 要求。 + +### 编译宏 +#### 选项集 + +##### G.C&C++.PRE.01 明确-D编译宏的具体用途,建立-D编译宏的清单 + +**【级别】** 要求 + +**【描述】** 每增加一个-D编译宏,就需要对它进行额外的测试。为每一种软件-D编译宏所作的代码修改,必须验证能否适用于其他-D编译宏。首先必须针对所有的-D编译宏,对软件进行构建,以确保没有编译错误;其次必须针对所有的-D编译宏进行完整的测试。 + +对于未使用的-D编译宏,应该直接删除。 + +### 其他 +#### 选项集 + +##### G.C&C++.OTH.01 同一构建工程中,避免使用重复的或包含关系的编译选项 + +**【级别】** 建议 + +**【描述】** 重复的编译选项是冗余信息,不利于维护。如果编译选项具有不同的参数,可能导致与初始预期不同的方式编译源文件。 + +编译选项之间存在包含关系时,同时使用会导致冗余。譬如"-Wall"包含40多个子警告选项,"-O"包含40多个子优化选项,当它们与子选项同时使用时就会导致冗余。 + +**【错误示例】** 某组件对编译优化选项"-O"取值达到7055次,其中同一构建工程中出现多个"-O",如"-O2...-O6"、"-O2...-O3"。 + +\# "-Wall"包含"-Waddress",同时使用产生冗余 + +gcc -Wall -Waddress -c test.c -o test.o + +\# "-O"包含"-fauto-inc-dec",同时使用产生冗余 + +gcc -O -fauto-inc-dec -c test.c -o test.o + +##### G.C&C++.OTH.02 避免使用相反冲突的选项 + +**【级别】** 建议 + +**【描述】** 大多数'-f'和'-W'有两个相反的互相否定的选项: +\-fname/-fno-name和-Wname/-Wno-name,同时引用导致冲突,令人疑惑,不利于维护。 + +**【错误示例】** + +\#同时引用-fomit-frame-pointer和-fno-omit-frame-pointer + +``` +set(CMAKE_C_FLAGS "-MD -MF -Wall -save-temps -fverbose-asm -fsigned-char +\-fomit-frame-pointer -fno-stack-protector \\ + +\-fno-delete-null-pointer-checks -fno-common -freg-struct-return -O2 +\-fno-omit-frame-pointer -fno-strength-reduce" ) +``` + +##### G.C&C++.OTH.03 编译选项的编写顺序:优化等级(如-O2)+总体选项+警告选项+语言选项+代码生成选项+架构选项(MD-Dependent Options)+优化选项+安全编译选项+自定义宏 + +**【级别】** 建议 + +**【描述】** 有选项集的,先写选项集,例如"-Wall"应该写到"-Wformat=2"前。 + +**【正确示例】** + +``` +\# Copyright (c) Huawei Technologies Co., Ltd. 2019. All rights reserved. +\# toolchain for ARMA15(without FPU)HI1381/HI1215 +\# cpu_family = arm +\# bit_width_in_run = 32 +\# cpu_core = a15 +\# compile flags +set(CC_OPT_LEVEL "-O2") +set(CC_OVERALL_FLAGS "-pipe") +set(CC_WARN_FLAGS "-Wall -Wextra -Wdate-time -Wtrampolines -Wfloat-equal +\-Wshadow -Wformat=2") +set(CC_LANGUAGE_FLAGS "-fsigned-char") +set(CC_CDG_FLAGS "-fno-common -freg-struct-return") +set(CC_MD_DEPENDENT_FLAGS "-mfloat-abi=soft -march=armv7-a -mtune=cortex-a15") +set(CC_OPT_FLAGS "-fno-strict-aliasing -fno-omit-frame-pointer") +set(CC_SEC_FLAGS "-fPIC -fstack-protector-strong --param=ssp-buffer-size=4") +set(CC_DEFINE_FLAGS "-DXXXXX") +set(CC_ALL_OPTIONS "\${CC_OPT_LEVEL} \${CC_OVERALL_FLAGS} \${CC_WARN_FLAGS} +\${CC_LANNGUAGE_FLAGS} \\ +\${CC_CDG_FLAGS} \${CC_MD_DEPENDENT_FLAGS} \${CC_OPT_FLAGS} \${CC_SEC_FLAGS} +\${CC_DEFINE_FLAGS}") + +\# public link flags +set(PUBLIC_LNK_FLAGS "-rdynamic -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now") + +\# link flag for module +set(SHARED_LNK_FLAGS "-shared \${PUBLIC_LNK_FLAGS}") +set(PIE_EXE_LNK_FLAGS "-pie \${PUBLIC_LNK_FLAGS}") + +``` + +## Java语言编译选项 + +### 语言级别 +#### 选项集 + +##### G.JAVA.LANG.01 每个交付单元使用的Java编译语言级别必须一致,且必须与使用的Java版本对应的编译语言级别一致。 + +**【级别】** 要求 + +**【描述】** 不同模块的编译语言级别不一致,这些模块需要配置不同的编译选项,导致构建脚本不一致。 + +使用与Java版本对应的编译语言级别,可以在编译阶段提示对应Java版本不推荐的编码实践,如Java 8版本将Java 7版本部分可用的API标记为 @Deprecated,推荐用更好的API来替换。当使用编译语言级别8时就会在编译阶段发出警告,代码中使用了将被弃用的API。 + +### MAVEN +#### 选项集 + +##### G.JAVA.MAVEN.01 版本发布构建时禁止使用maven 编译选项-X,避免输出大量的debug日志。 + +**【级别】** 要求 + +**【描述】** -X是debug选项,会输出大量的debug日志。 + +### JAVAC +#### 选项集 + +##### G.JAVA.JAVAC.01 禁止使用的javac编译选项:-nowarn/-Xlint:none/-Xlint:name 选项关闭所有或部分javac编译告警;-g:none/-g:[keyword list]选项关闭全部或指定生成部分调试信息 + +**【级别】** 要求 + +**【描述】** 编译告警能够帮助提前发现代码存在的缺陷和风险,关闭编译告警会给代码质量带来隐患;使用-g:none或-g:[keywordlist]会导致生成过少或过多的调试信息,影响可维护性或降低运行效率。 + +**例外**:-Xlint:all,-processing +运行时处理的注解不需要注解处理器,产生编译告警可以通过-Xlint的参数-processing进行抑制。 + +##### G.JAVA.JAVAC.02 必须使用的javac编译选项:-source,-target,-Xlint:all。 同时maven-compiler-plugin的showWarnings属性必须设置为true。 + +**【级别】** 求 + +**【描述】** + +\-source 指定编译器接受的java源文件版本 + +\-target 指定编译器生成的class文件版本 + +\-Xlint:all 使能所有推荐编译告警 + +showWarnings 属性必须设置为true,不设置或者设置为false时部分编译告警无法检查出来 + +**【正确示例】** + +``` +\ + +\org.apache.maven.plugins\ + +\maven-compiler-plugin\ + +\ + +\1.8\ + +\1.8\ + +\true\ + +\ + +\-Xlint:all\ + +\ + +\ + +\ + +``` + diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-filemanagement.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-filemanagement.md new file mode 100644 index 0000000000000000000000000000000000000000..15cf796c6820cfb09820d43fe3e4c52d7b7f15f9 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-filemanagement.md @@ -0,0 +1,90 @@ +# 文件管理子系统ChangeLog + +## cl.filemanagement.1 fileio相关接口异常处理方式变更 + +file_api部件fileio接口返回值不包含错误码error.code,现进行错误码整改,废弃原有相关接口,新增相关接口。 + +**变更影响** + +基于此前版本开发的应用,需注意废弃接口的迭代更新。新接口在接口规格上进行了微调,需注意新接口使用方法。 + +**关键接口/组件变更** + +为适配统一的API异常处理方式,对fileio相关接口进行废弃,并新增对应接口,原接口位于@ohos.fileio,新接口位于@ohos.file.fs。新增接口支持统一的错误码异常处理规范,功能上与原接口保持一致,参数上有微调。 + +| 模块名 | 方法/属性/枚举/常量 | 变更类型 | +| ------------------------- | ------------------------------------------------------------ | -------- | +| @ohos.fileio | **function** open(path: string, flags?: number, mode?: number, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** openSync(path: string, flags?: number, mode?: number): number; | 废弃 | +| @ohos.file.fs | **function** open(path: string, mode?: number, callback?: AsyncCallback): void \| Promise; | 新增 | +| @ohos.file.fs | **function** openSync(path: string, mode?: number): File; | 新增 | +| @ohos.fileio | **function** read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }): number; | 废弃 | +| @ohos.file.fs | **function** read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }, callback?: AsyncCallback): void \| Promise; | 新增 | +| @ohos.file.fs | **function** readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; }): number; | 新增 | +| @ohos.fileio | **function** stat(path: string, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** statSync(path: string): Stat; | 废弃 | +| @ohos.fileio | **function** fstat(fd: number, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** fstatSync(fd: number): Stat; | 废弃 | +| @ohos.file.fs | **function** stat(file: string \| number, callback?: AsyncCallback): void \| Promise; | 新增 | +| @ohos.file.fs | **function** statSync(file: string \| number): Stat; | 新增 | +| @ohos.fileio | **function** truncate(path: string, len?: number, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** truncateSync(path: string, len?: number): void; | 废弃 | +| @ohos.fileio | **function** ftruncate(fd: number, len?: number, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** ftruncateSync(fd: number, len?: number): void; | 废弃 | +| @ohos.file.fs | **function** truncate(file: string \| number, len?: number, callback?: AsyncCallback): void \| Promise; | 新增 | +| @ohos.file.fs | **function** truncateSync(file: string \| number, len?: number): void; | 新增 | +| @ohos.fileio | **function** write(fd: number, buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }, callback?: AsyncCallback): void \| Promise; | 废弃 | +| @ohos.fileio | **function** writeSync(fd: number, buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): number; | 废弃 | +| @ohos.file.fs | **function** write(fd: number, buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; encoding?: string; }, callback?: AsyncCallback): void \| Promise; | 新增 | +| @ohos.file.fs | **function** writeSync(fd: number, buffer: ArrayBuffer \| string, options?: { offset?: number; length?: number; encoding?: string; }): number; | 新增 | + +**适配指导** + +原接口使用的是@ohos.fileio,以以下方式import: + +```js +import fileio from '@ohos.fileio'; +``` + +现新接口使用的是@ohos.file.fs,以以下方式import: + +```js +import fs from '@ohos.file.fs'; +``` + +此外还需要适配异常处理,同步接口异常处理示例代码: +```js +import fs from '@ohos.file.fs' + +try { + let file = fs.openSync(path, fs.OpenMode.READ_ONLY); +} catch (err) { + console.error("openSync errCode:" + err.code + ", errMessage:" + err.message); +} +``` +异步接口promise方法异常处理示例代码: +```js +import fs from '@ohos.file.fs' + +try { + let file = await fs.open(path, fs.OpenMode.READ_ONLY); +} catch (err) { + console.error("open promise errCode:" + err.code + ", errMessage:" + err.message); +} +``` + +异步接口callback方法异常处理示例代码: +```js +import fs from '@ohos.file.fs' + +try { + fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ //异步线程的错误(如系统调用等)在回调中获取 + if (e) { + console.error("open in async errCode:" + e.code + ", errMessage:" + e.message); + } + }); +} catch (err) { //主线程的错误(如非法参数等)通过try catch获取 + console.error("open callback errCode:" + err.code + ", errMessage:" + err.message); +} +``` diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-power.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-power.md new file mode 100644 index 0000000000000000000000000000000000000000..f981146225f2d667916415d5670f050f57e15b0e --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-power.md @@ -0,0 +1,68 @@ +# 电源子系统ChangeLog + +## cl.powermgr.1 API错误信息返回方式变更 + +下列API使用业务逻辑返回值表示错误信息,不符合OpenHarmony接口错误码规范。从API9进行变更。 + +- 耗电统计:[@ohos.batteryStatistics](../../../application-dev/reference/apis/js-apis-batteryStatistics.md) + - 屏幕亮度:[@ohos.brightness](../../../application-dev/reference/apis/js-apis-brightness.md) + - 系统电源管理:[@ohos.power](../../../application-dev/reference/apis/js-apis-power.md) + - Runninglock锁:[@ohos.runningLock](../../../application-dev/reference/apis/js-apis-runninglock.md) + - 热管理:[@ohos.thermal](../../../application-dev/reference/apis/js-apis-thermal.md) + +异步接口:通过AsyncCallback或Promise的error对象返回错误信息。 + +同步接口:通过抛出异常的方式返回错误信息。 + +#### 变更影响 + +基于此前版本开发的应用,需适配接口的错误信息返回方式,否则会影响原有业务逻辑。 + +#### 关键的接口/组件变更 + +在以下接口增加错误码处理: + - getBatteryStats(callback: AsyncCallback): void + - getAppPowerValue(uid: number): number + - getAppPowerPercent(uid: number): number + - getHardwareUnitPowerValue(type: ConsumptionType): number + - getHardwareUnitPowerPercent(type: ConsumptionType): number + - setValue(value: number): void + - shutdown(reason: string): void; + - isActive(): boolean + - wakeup(detail: string): void + - suspend(): void + - getPowerMode(): DevicePowerMode + - setPowerMode(mode: DevicePowerMode, callback: AsyncCallback<void>): void + - setPowerMode(mode: DevicePowerMode): Promise<void> + - hold(timeout: number): void + - isHolding(): boolean + - unhold(): void + - isSupported(type: RunningLockType): boolean + - isSupported(type: RunningLockType): boolean + - create(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void + - create(name: string, type: RunningLockType): Promise<RunningLock> + - registerThermalLevelCallback(callback: Callback<ThermalLevel>): void + - unregisterThermalLevelCallback(callback?: Callback<void>): void + - getLevel(): ThermalLevel + +#### 适配指导 + +请参考各接口的API参考。 +## cl.powermgr.2 系统接口变更 + +#### 变更影响 + +基于此前版本开发的应用,需适配新接口名和错误信息返回方式,否则会影响原有业务逻辑。 + +#### 关键的接口/组件变更 + +| 包名 | 旧接口 | 新接口 | +| ----------- | ------------------------------------ | ------------------------------ | +| @ohos.power | shutdownDevice(reason: string): void | shutdown(reason: string): void | +| @ohos.power | rebootDevice(reason: string): void | reboot(reason: string): void | +| @ohos.power | wakeupDevice(detail: string): void | wakeup(detail: string): void | +| @ohos.power | suspendDevice(): void | suspend(): void | + +#### 适配指导 + +请参考系统电源管理[@ohos.power](../../../application-dev/reference/apis/js-apis-power.md)的API参考。 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-request.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-request.md new file mode 100644 index 0000000000000000000000000000000000000000..ec7e3f8202e14792db1a8df9fde33390a935944c --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-request.md @@ -0,0 +1,108 @@ +# 上传下载子系统ChangeLog + +OpenHarmony 3.2.8.1版本相较于OpenHarmony 3.2.beta3版本,request子系统的API变更如下 + +## cl.request.1 错误码定义及API部分接口名称变更 + +- 新增上传下载接口的[错误码](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/errorcodes/errorcode-request.md)处理。 +- 错误信息通过AsyncCallback或Promise的error对象返回。其中,参数类型和数量错误信息,通过抛出异常的方式返回。 +- API部分接口需要用新的接口替换,参数不变。 + +**变更影响** + +基于此前版本开发的应用,需适配变更后的新错误码和错误信息返回方式,否则会影响原有业务逻辑。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 变更类型 | +|--------------|--------------|-----------------------------------------------------------------------------------------------------------------------|-----------| +| ohos.request | request | EXCEPTION_PERMISSION | 新增 | +| ohos.request | request | EXCEPTION_PARAMCHECK | 新增 | +| ohos.request | request | EXCEPTION_UNSUPPORTED | 新增 | +| ohos.request | request | EXCEPTION_FILEIO | 新增 | +| ohos.request | request | EXCEPTION_FILEPATH | 新增 | +| ohos.request | request | EXCEPTION_SERVICE | 新增 | +| ohos.request | request | EXCEPTION_OTHERS | 新增 | +| ohos.request | request | ERROR_OFFLINE | 新增 | +| ohos.request | request | ERROR_UNSUPPORTED_NETWORK_TYPE | 新增 | +| ohos.request | request | function downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback): void; | 新增 | +| ohos.request | request | function downloadFile(context: BaseContext, config: DownloadConfig): Promise; | 新增 | +| ohos.request | request | function uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback): void; | 新增 | +| ohos.request | request | function uploadFile(context: BaseContext, config: UploadConfig): Promise; | 新增 | +| ohos.request | DownloadTask | delete(callback: AsyncCallback): void; | 新增 | +| ohos.request | DownloadTask | delete(): Promise; | 新增 | +| ohos.request | DownloadTask | suspend(callback: AsyncCallback): void; | 新增 | +| ohos.request | DownloadTask | suspend(): Promise; | 新增 | +| ohos.request | DownloadTask | restore(callback: AsyncCallback): void; | 新增 | +| ohos.request | DownloadTask | restore(): Promise; | 新增 | +| ohos.request | DownloadTask | getTaskInfo(callback: AsyncCallback): void; | 新增 | +| ohos.request | DownloadTask | getTaskInfo(): Promise; | 新增 | +| ohos.request | DownloadTask | getTaskMimeType(callback: AsyncCallback): void; | 新增 | +| ohos.request | DownloadTask | getTaskMimeType(): Promise; | 新增 | +| ohos.request | UploadTask | delete(callback: AsyncCallback): void; | 新增 | +| ohos.request | UploadTask | delete(): Promise; | 新增 | +| ohos.request | request | function download(config: DownloadConfig, callback: AsyncCallback): void;
代替接口:function downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback): void; | 废弃 | +| ohos.request | request | function download(config: DownloadConfig): Promise;
代替接口:function downloadFile(context: BaseContext, config: DownloadConfig): Promise; | 废弃 | +| ohos.request | request | function download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback): void;
代替接口:function downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback): void; | 废弃 | +| ohos.request | request | function download(context: BaseContext, config: DownloadConfig): Promise;
代替接口:function downloadFile(context: BaseContext, config: DownloadConfig): Promise; | 废弃 | +| ohos.request | request | function upload(config: UploadConfig, callback: AsyncCallback): void;
代替接口:function uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback): void; | 废弃 | +| ohos.request | request | function upload(config: UploadConfig): Promise;
代替接口:function uploadFile(context: BaseContext, config: UploadConfig): Promise; | 废弃 | +| ohos.request | request | function upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback): void;
代替接口:function uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback): void; | 废弃 | +| ohos.request | request | function upload(context: BaseContext, config: UploadConfig): Promise;
代替接口:function uploadFile(context: BaseContext, config: UploadConfig): Promise; | 废弃 | +| ohos.request | DownloadTask | remove(callback: AsyncCallback): void;
代替接口:delete(callback: AsyncCallback): void | 废弃 | +| ohos.request | DownloadTask | remove(): Promise;
代替接口:delete(): Promise; | 废弃 | +| ohos.request | DownloadTask | pause(callback: AsyncCallback): void;
代替接口:suspend(callback: AsyncCallback): void; | 废弃 | +| ohos.request | DownloadTask | pause(): Promise;
代替接口:suspend(): Promise; | 废弃 | +| ohos.request | DownloadTask | resume(callback: AsyncCallback): void;
代替接口:restore(callback: AsyncCallback): void; | 废弃 | +| ohos.request | DownloadTask | resume(): Promise;
代替接口:restore(): Promise; | 废弃 | +| ohos.request | DownloadTask | query(callback: AsyncCallback): void;
代替接口:getTaskInfo(callback: AsyncCallback): void; | 废弃 | +| ohos.request | DownloadTask | query(): Promise;
代替接口:getTaskInfo(): Promise; | 废弃 | +| ohos.request | DownloadTask | queryMimeType(callback: AsyncCallback): void;
代替接口:getTaskMimeType(callback: AsyncCallback): void; | 废弃 | +| ohos.request | DownloadTask | queryMimeType(): Promise;
代替接口:getTaskMimeType(): Promise; | 废弃 | +| ohos.request | UploadTask | remove(callback: AsyncCallback): void;
代替接口:delete(callback: AsyncCallback): void; | 废弃 | +| ohos.request | UploadTask | remove(): Promise;
代替接口:delete(): Promise; | 废弃 | +| system.request | UploadResponse | code | 废弃 | +| system.request | UploadResponse | data | 废弃 | +| system.request | UploadResponse | headers | 废弃 | +| system.request | DownloadResponse | token | 废弃 | +| system.request | OnDownloadCompleteResponse | uri | 废弃 | +| system.request | RequestFile | filename | 废弃 | +| system.request | RequestFile | name | 废弃 | +| system.request | RequestFile | uri | 废弃 | +| system.request | RequestFile | type | 废弃 | +| system.request | RequestData | name | 废弃 | +| system.request | RequestData | value | 废弃 | +| system.request | UploadRequestOptions | url | 废弃 | +| system.request | UploadRequestOptions | data | 废弃 | +| system.request | UploadRequestOptions | files | 废弃 | +| system.request | UploadRequestOptions | header | 废弃 | +| system.request | UploadRequestOptions | description | 废弃 | +| system.request | UploadRequestOptions | success | 废弃 | +| system.request | UploadRequestOptions | fail | 废弃 | +| system.request | UploadRequestOptions | complete | 废弃 | +| system.request | OnDownloadCompleteOptions | token | 废弃 | +| system.request | OnDownloadCompleteOptions | success | 废弃 | +| system.request | OnDownloadCompleteOptions | fail | 废弃 | +| system.request | OnDownloadCompleteOptions | complete | 废弃 | +| system.request | Request | static upload(options: UploadRequestOptions): void; | 废弃 | +| system.request | Request | static download(options: DownloadRequestOptions): void; | 废弃 | +| system.request | Request | static onDownloadComplete(options: OnDownloadCompleteOptions): void; | 废弃 | + + +**适配指导** + +以downloadFile为例,在新版本上需要使用如下方式进行调用: + +```ts +try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + }); +} catch (err) { + console.log("downloadFile callback fail." + "errCode:" + err.code + ",errMessage:" + err.message); +} +``` \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-theme.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-theme.md new file mode 100644 index 0000000000000000000000000000000000000000..87c2c62d7cdb8ef1c0c2b6b26724be8224813ec8 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.1/changelogs-theme.md @@ -0,0 +1,148 @@ +# 主题框架changeLog + +## cl.theme.1 API9接口支持异常处理 + +下列模块内部接口使用业务逻辑返回值表示错误信息,不符合OpenHarmony接口错误码规范。在API9进行变更。 + - 壁纸管理服务:@ohos.wallpaper.d.ts + + - 锁屏管理服务:@ohos.screenLock.d.ts + +以上模块中的接口变更为: +同步接口:通过抛出异常的方式返回错误信息。 +异步接口:参数检查错误同步抛出,业务逻辑错误通过AsyncCallback或Promise的error对象抛出。 + +**变更影响** + +基于此前版本开发的应用,需适配接口的错误信息返回方式,否则会影响原有业务逻辑。 + +**关键接口/组件变更** + +以下标记为壁纸管理服务接口废除: + - getColors(wallpaperType: WallpaperType, callback: AsyncCallback>): void; + - getColors(wallpaperType: WallpaperType): Promise>; + - getId(wallpaperType: WallpaperType, callback: AsyncCallback): void; + - getId(wallpaperType: WallpaperType): Promise; + - getMinHeight(callback: AsyncCallback): void; + - getMinHeight(): Promise; + - getMinWidth(callback: AsyncCallback): void; + - getMinWidth(): Promise; + - isChangePermitted(callback: AsyncCallback): void; + - isChangePermitted(): Promise; + - isOperationAllowed(callback: AsyncCallback): void; + - isOperationAllowed(): Promise; + - reset(wallpaperType: WallpaperType, callback: AsyncCallback): void; + - reset(wallpaperType: WallpaperType): Promise; + - setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + - setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; + - getFile(wallpaperType: WallpaperType, callback: AsyncCallback): void; + - getFile(wallpaperType: WallpaperType): Promise; + - getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback): void; + - getPixelMap(wallpaperType: WallpaperType): Promise; + +壁纸管理服务替代接口如下: + - getColorsSync(wallpaperType: WallpaperType): Array; + - getIdSync(wallpaperType: WallpaperType): number; + - getMinHeightSync(): number; + - getMinWidthSync(): number; + - isChangeAllowed(): boolean; + - isUserChangeAllowed(): boolean; + - restore(wallpaperType: WallpaperType, callback: AsyncCallback): void; + - restore(wallpaperType: WallpaperType): Promise; + - setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback): void; + - setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise; + - getFileSync(wallpaperType: WallpaperType): number; + - getImage(wallpaperType: WallpaperType, callback: AsyncCallback): void; + - getImage(wallpaperType: WallpaperType): Promise; + +以下标记为壁纸管理服务接口变更: + - on(type: 'colorChange', callback: (colors: Array, wallpaperType: WallpaperType) => void): void + - off(type: 'colorChange', callback?: (colors: Array, wallpaperType: WallpaperType) => void): void + +以下标记为锁屏管理服务接口废除: + - isScreenLocked(callback: AsyncCallback): void; + - isScreenLocked(): Promise; + - isSecureMode(callback: AsyncCallback): void; + - isSecureMode(): Promise; + - unlockScreen(callback: AsyncCallback): void; + - unlockScreen(): Promise; + +锁屏管理服务替代接口如下: + - isLocked(): boolean; + - isSecure(): boolean; + - unlock(callback: AsyncCallback): void; + - unlock():Promise; + +以下标记为锁屏管理服务接口删除: + - lockScreen(callback: AsyncCallback): void; + - lockScreen(): Promise; + +以下标记为锁屏管理服务接口新增: + - lock(callback: AsyncCallback): void; + - lock():Promise; + +以下标记为锁屏管理服务接口变更: + - onSystemEvent(callback: Callback): boolean; + - sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback): void; + - sendScreenLockEvent(event: String, parameter: number): Promise; + +**壁纸管理服务适配指导** + +异步接口以getImage为例,示例代码如下: + +```ts +import pointer from '@ohos.wallpaper'; +try { + wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getImage: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getImage because: ${JSON.stringify(error)}`); + }); +} catch (err) { + console.error(`failed to getImage because: ${JSON.stringify(err)}`); +} + +``` + +同步接口以getFileSync为例,示例代码如下: + +```ts +import pointer from '@ohos.wallpaper'; +try { + let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); +} catch (err) { + console.error(`failed to getFileSync because: ${err.message}`); +} +``` + +**锁屏管理服务适配指导** + +异步接口以lock为例,示例代码如下: + +```ts +import screenLock from '@ohos.screenlock'; +try { + screenLock.lock((err, data) => { + if (err) { + console.error(`Failed to lock the screen, because: ${err.message}`); + return; + } + console.info(`lock the screen successfully. result: ${data}`); + }); +} catch (err) { + console.error(`Failed to lock the screen, because: ${err.message}`); +} + +``` + +同步接口以onSystemEvent为例,示例代码如下: + +```ts +import screenLock from '@ohos.screenlock'; +try { + let isSuccess = screenLock.onSystemEvent((event) => { + console.log(`Register the system event which related to screenlock successfully. eventType: ${event.eventType}`) + }); +} catch (err) { + console.error(`Failed to register the system event which related to screenlock, because: ${err.message}`) +} +``` diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.3/changelog-wifi.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.3/changelog-wifi.md new file mode 100644 index 0000000000000000000000000000000000000000..1f84833ca57af98d069eeba6c13c993f31cd1e8a --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.8.3/changelog-wifi.md @@ -0,0 +1,115 @@ +# 基础通信WIFI子系统ChangeLog + + +## cl.wifi.1 系统API和API9接口迁移到新增的@ohos.wifiManager.d.ts +@ohos.wifi.d.ts接口不支持抛出错误码,而API9以及SystemAPI都需要支持错误码抛出,为支持该功能,将@ohos.wifi.d.ts中的所有SystemAPI以及API9接口迁移到新增的@ohos.wifiManager.d.ts当中,并添加错误码描述。 + +后续需要import @ohos.wifiManager.d.ts才能够使用wifi的系统API以及API9接口: + +import wifiManager from '@ohos.wifiManager'; + + +**变更影响** + +仅对系统API以及API9所有接口的使用有影响,需要import @ohos.wifiManager才能使用wifi的系统API和API9接口 + +import wifiManager from '@ohos.wifiManager'; + +对于其他接口无影响 + + +**关键的接口/组件变更** + +| 类名 | 接口类型 | 接口声明 | 变更类型 | +| -- | -- | -- | -- | +| wifi | namespace | declare namespace wifi | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function enableWifi(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值改为void | +| wifi | method | function disableWifi(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值改为void | +| wifi | method | function scan(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值改为void | +| wifi | method | function getScanResults(): Promise<Array<WifiScanInfo>> | API9接口变更,迁移到@ohos.wifiManager.d.ts,由getScanInfos修改为getScanResults | +| wifi | method | function getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,由getScanInfos修改为getScanResults | +| wifi | method | function getScanResultsSync():  Array<[WifiScanInfo]> | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function addCandidateConfig(config: WifiDeviceConfig): Promise<number> | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function removeCandidateConfig(networkId: number): Promise<void> | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> | API9接口变更,该接口删除 | +| wifi | method | function addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void | API9接口变更,该接口删除 | +| wifi | method | function removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> | API9接口变更,该接口删除 | +| wifi | method | function removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void | API9接口变更,该接口删除 | +| wifi | method | function getCandidateConfigs():  Array<[WifiDeviceConfig]> | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function connectToCandidateConfig(networkId: number): void | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function connectToNetwork(networkId: number): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function connectToDevice(config: WifiDeviceConfig): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function disconnect(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function reassociate(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function reconnect(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function disableNetwork(netId: number): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function removeAllNetwork(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function removeDevice(id: number): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function enableHotspot(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function disableHotspot(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function setHotspotConfig(config: HotspotConfig): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function getP2pLocalDevice(): Promise<WifiP2pDevice> | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | method | function createGroup(config: WifiP2PConfig): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function removeGroup(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function p2pConnect(config: WifiP2PConfig): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function p2pCancelConnect(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function startDiscoverDevices(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function stopDiscoverDevices(): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function deletePersistentGroup(netId: number): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | method | function setDeviceName(devName: string): void | API9接口变更,迁移到@ohos.wifiManager.d.ts,返回值修改为void | +| wifi | interface | export interface WifiEapConfig | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | enum | export enum EapMethod | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | enum | export enum Phase2Method | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | interface | export interface WifiDeviceConfig | API9接口变更,迁移到@ohos.wifiManager.d.ts,增加eapConfig参数 | +| wifi | interface | export interface IpConfig | API9接口变更,迁移到@ohos.wifiManager.d.ts,增加prefixLength参数 | +| wifi | interface | export interface WifiInfoElem | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | enum | export enum WifiChannelWidth | API9接口变更,迁移到@ohos.wifiManager.d.ts | +| wifi | interface | export interface WifiScanInfo | API9接口变更,迁移到@ohos.wifiManager.d.ts,增加centerFrequency0、centerFrequency1、infoElems三个参数 | +| wifi | enum | export enum WifiSecurityType | API9接口变更,迁移到@ohos.wifiManager.d.ts,增加4种加密类型 | +| wifi | interface | export interface WifiLinkedInfo | API9接口变更,迁移到@ohos.wifiManager.d.ts,增加MacType参数 | + + +**适配指导(可选,不涉及则可以删除)** + +以getLinkedInfo为例,在新版本中需要使用如下方式进行调用: + +``` +import wifiManager from '@ohos.wifiManager' + +wifiManager.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get linked info: " + JSON.stringify(data)); +}); + +wifiManager.getLinkedInfo().then(data => { + console.info("get linked info: " + JSON.stringify(data)); +}).catch(error => { + console.info("get linked info error"); +}); + +``` + +## cl.wifiext.1 系统API和API9接口迁移到新增的@ohos.wifiManagerExt.d.ts + +@ohos.wifiext.d.ts接口不支持抛出错误码,而API9以及SystemAPI都需要支持错误码抛出,为支持该功能,将@ohos.wifiext.d.ts中的所有SystemAPI以及API9接口迁移到新增的@ohos.wifiManagerExt.d.ts当中,并添加错误码描述 + +后续需要import @ohos.wifiManagerExt.d.ts才能够使用wifi的系统API以及API9接口: + +import wifiManagerExt from '@ohos.wifiManagerExt'; + + +**变更影响** + +仅对系统API以及API9所有接口的使用有影响,需要import @ohos.wifiManagerExt才能使用wifi的系统API和API9接口,与wifiManager配套使用 + +import wifiManagerExt from '@ohos.wifiManagerExt'; + +对于其他接口无影响 diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md index a60636178bd9d6ecdbec90501d7c2b6b51b0582a..4ce56f7346c9f1f0c92dc1037eb9eb1845e7a6e5 100644 --- a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md @@ -100,3 +100,27 @@ ArkUI子系统alertDialog, actionSheet, customDialog组件及prompt, promptActio **适配指导** 按文档提示修改,使用其它装饰器变量或常规变量赋值。 + +## cl.arkui.5 单一子组件校验补全 + +对 'Button', 'FlowItem','GridItem','GridCol','ListItem','Navigator','Refresh','RichText','ScrollBar','StepperItem','TabContent'等只支持一个子组件的开启校验。 + + +**变更影响** + +如果上述组件内有超过一个子组件,编译报错。 + +**关键的接口/组件变更** + +```js +RichText('RichText') { + Text('Text1') + Text('Text2') +} +/* ArkTS:ERROR File: /root/newOH/developtools/ace-ets2bundle/compiler/sample/pages/home.ets:25:7 + The component 'RichText' can only have a single child component. */ +``` + +**适配指导** + +按报错提示修改,指定组件内只能有一个子组件。 diff --git a/zh-cn/release-notes/changelogs/v3.2-beta3/changelog-v3.2-beta3.md b/zh-cn/release-notes/changelogs/v3.2-beta3/changelog-v3.2-beta3.md index 411ee5c31b0bbafb237fae401acf30963693cc49..17479bdd769a91863a6485970379359541e6c9b2 100644 --- a/zh-cn/release-notes/changelogs/v3.2-beta3/changelog-v3.2-beta3.md +++ b/zh-cn/release-notes/changelogs/v3.2-beta3/changelog-v3.2-beta3.md @@ -227,4 +227,30 @@ struct Index { **关键的接口/组件变更** +无 + +## 电源管理子系统 + +### 修改@ohos.batteryinfo.d.ts文件名 + +API声明文件@ohos.batteryinfo.d.ts,变更其文件名为@ohos.batteryInfo.d.ts。 + +**变更影响** + +JS/TS 引用该声明时,由`import batteryInfo from '@ohos.batteryinfo';` 变为`import batteryInfo from '@ohos.batteryInfo';` + +**关键的接口/组件变更** + +无 + +### 修改runninglock.d.ts文件名 + +API声明文件@ohos.runninglock.d.ts,变更其文件名为@ohos.runningLock.d.ts。 + +**变更影响** + +JS/TS 引用该声明时,由`import runningLock from '@ohos.runninglock';` 变为`import runningLock from '@ohos.runningLock';` + +**关键的接口/组件变更** + 无 \ No newline at end of file